llama.cpp 583 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986
  1. #define LLAMA_API_INTERNAL
  2. #include "llama.h"
  3. #include "unicode.h"
  4. #include "ggml.h"
  5. #include "ggml-alloc.h"
  6. #include "ggml-backend.h"
  7. #ifdef GGML_USE_CUBLAS
  8. # include "ggml-cuda.h"
  9. #elif defined(GGML_USE_CLBLAST)
  10. # include "ggml-opencl.h"
  11. #elif defined(GGML_USE_VULKAN)
  12. # include "ggml-vulkan.h"
  13. #elif defined(GGML_USE_SYCL)
  14. # include "ggml-sycl.h"
  15. #elif defined(GGML_USE_KOMPUTE)
  16. # include "ggml-kompute.h"
  17. #endif
  18. #ifdef GGML_USE_METAL
  19. # include "ggml-metal.h"
  20. #endif
  21. #ifdef GGML_USE_MPI
  22. # include "ggml-mpi.h"
  23. #endif
  24. #ifndef QK_K
  25. # ifdef GGML_QKK_64
  26. # define QK_K 64
  27. # else
  28. # define QK_K 256
  29. # endif
  30. #endif
  31. #ifdef __has_include
  32. #if __has_include(<unistd.h>)
  33. #include <unistd.h>
  34. #if defined(_POSIX_MAPPED_FILES)
  35. #include <sys/mman.h>
  36. #include <fcntl.h>
  37. #endif
  38. #if defined(_POSIX_MEMLOCK_RANGE)
  39. #include <sys/resource.h>
  40. #endif
  41. #endif
  42. #endif
  43. #if defined(_WIN32)
  44. #define WIN32_LEAN_AND_MEAN
  45. #ifndef NOMINMAX
  46. #define NOMINMAX
  47. #endif
  48. #include <windows.h>
  49. #ifndef PATH_MAX
  50. #define PATH_MAX MAX_PATH
  51. #endif
  52. #include <io.h>
  53. #endif
  54. #include <algorithm>
  55. #include <array>
  56. #include <cassert>
  57. #include <cfloat>
  58. #include <cinttypes>
  59. #include <climits>
  60. #include <cmath>
  61. #include <cstdarg>
  62. #include <cstddef>
  63. #include <cstdint>
  64. #include <cstdio>
  65. #include <cstring>
  66. #include <ctime>
  67. #include <cwctype>
  68. #include <forward_list>
  69. #include <fstream>
  70. #include <functional>
  71. #include <initializer_list>
  72. #include <locale>
  73. #include <map>
  74. #include <memory>
  75. #include <mutex>
  76. #include <numeric>
  77. #include <queue>
  78. #include <random>
  79. #include <regex>
  80. #include <set>
  81. #include <sstream>
  82. #include <thread>
  83. #include <type_traits>
  84. #include <unordered_map>
  85. #if defined(_MSC_VER)
  86. #pragma warning(disable: 4244 4267) // possible loss of data
  87. #endif
  88. #ifdef __GNUC__
  89. #ifdef __MINGW32__
  90. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  91. #else
  92. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  93. #endif
  94. #else
  95. #define LLAMA_ATTRIBUTE_FORMAT(...)
  96. #endif
  97. #define LLAMA_MAX_NODES 8192
  98. #define LLAMA_MAX_EXPERTS 8
  99. //
  100. // logging
  101. //
  102. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  103. static void llama_log_internal (ggml_log_level level, const char* format, ...);
  104. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
  105. #define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  106. #define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  107. #define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  108. //
  109. // helpers
  110. //
  111. static size_t utf8_len(char src) {
  112. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  113. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  114. return lookup[highbits];
  115. }
  116. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  117. std::string result;
  118. for (size_t pos = 0; ; pos += search.length()) {
  119. auto new_pos = s.find(search, pos);
  120. if (new_pos == std::string::npos) {
  121. result += s.substr(pos, s.size() - pos);
  122. break;
  123. }
  124. result += s.substr(pos, new_pos - pos) + replace;
  125. pos = new_pos;
  126. }
  127. s = std::move(result);
  128. }
  129. static bool is_float_close(float a, float b, float abs_tol) {
  130. // Check for non-negative tolerance
  131. if (abs_tol < 0.0) {
  132. throw std::invalid_argument("Tolerance must be non-negative");
  133. }
  134. // Exact equality check
  135. if (a == b) {
  136. return true;
  137. }
  138. // Check for infinities
  139. if (std::isinf(a) || std::isinf(b)) {
  140. return false;
  141. }
  142. // Regular comparison using the provided absolute tolerance
  143. return std::fabs(b - a) <= abs_tol;
  144. }
  145. static void zeros(std::ofstream & file, size_t n) {
  146. char zero = 0;
  147. for (size_t i = 0; i < n; ++i) {
  148. file.write(&zero, 1);
  149. }
  150. }
  151. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  152. static std::string format(const char * fmt, ...) {
  153. va_list ap;
  154. va_list ap2;
  155. va_start(ap, fmt);
  156. va_copy(ap2, ap);
  157. int size = vsnprintf(NULL, 0, fmt, ap);
  158. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  159. std::vector<char> buf(size + 1);
  160. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  161. GGML_ASSERT(size2 == size);
  162. va_end(ap2);
  163. va_end(ap);
  164. return std::string(buf.data(), size);
  165. }
  166. //
  167. // gguf constants (sync with gguf.py)
  168. //
  169. enum llm_arch {
  170. LLM_ARCH_LLAMA,
  171. LLM_ARCH_FALCON,
  172. LLM_ARCH_BAICHUAN,
  173. LLM_ARCH_GPT2,
  174. LLM_ARCH_GPTJ,
  175. LLM_ARCH_GPTNEOX,
  176. LLM_ARCH_MPT,
  177. LLM_ARCH_STARCODER,
  178. LLM_ARCH_PERSIMMON,
  179. LLM_ARCH_REFACT,
  180. LLM_ARCH_BERT,
  181. LLM_ARCH_NOMIC_BERT,
  182. LLM_ARCH_BLOOM,
  183. LLM_ARCH_STABLELM,
  184. LLM_ARCH_QWEN,
  185. LLM_ARCH_QWEN2,
  186. LLM_ARCH_PHI2,
  187. LLM_ARCH_PLAMO,
  188. LLM_ARCH_CODESHELL,
  189. LLM_ARCH_ORION,
  190. LLM_ARCH_INTERNLM2,
  191. LLM_ARCH_MINICPM,
  192. LLM_ARCH_GEMMA,
  193. LLM_ARCH_STARCODER2,
  194. LLM_ARCH_MAMBA,
  195. LLM_ARCH_COMMAND_R,
  196. LLM_ARCH_UNKNOWN,
  197. };
  198. static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  199. { LLM_ARCH_LLAMA, "llama" },
  200. { LLM_ARCH_FALCON, "falcon" },
  201. { LLM_ARCH_GPT2, "gpt2" },
  202. { LLM_ARCH_GPTJ, "gptj" },
  203. { LLM_ARCH_GPTNEOX, "gptneox" },
  204. { LLM_ARCH_MPT, "mpt" },
  205. { LLM_ARCH_BAICHUAN, "baichuan" },
  206. { LLM_ARCH_STARCODER, "starcoder" },
  207. { LLM_ARCH_PERSIMMON, "persimmon" },
  208. { LLM_ARCH_REFACT, "refact" },
  209. { LLM_ARCH_BERT, "bert" },
  210. { LLM_ARCH_NOMIC_BERT, "nomic-bert" },
  211. { LLM_ARCH_BLOOM, "bloom" },
  212. { LLM_ARCH_STABLELM, "stablelm" },
  213. { LLM_ARCH_QWEN, "qwen" },
  214. { LLM_ARCH_QWEN2, "qwen2" },
  215. { LLM_ARCH_PHI2, "phi2" },
  216. { LLM_ARCH_PLAMO, "plamo" },
  217. { LLM_ARCH_CODESHELL, "codeshell" },
  218. { LLM_ARCH_ORION, "orion" },
  219. { LLM_ARCH_INTERNLM2, "internlm2" },
  220. { LLM_ARCH_MINICPM, "minicpm" },
  221. { LLM_ARCH_GEMMA, "gemma" },
  222. { LLM_ARCH_STARCODER2, "starcoder2" },
  223. { LLM_ARCH_MAMBA, "mamba" },
  224. { LLM_ARCH_COMMAND_R, "command-r" },
  225. { LLM_ARCH_UNKNOWN, "(unknown)" },
  226. };
  227. enum llm_kv {
  228. LLM_KV_GENERAL_ARCHITECTURE,
  229. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  230. LLM_KV_GENERAL_ALIGNMENT,
  231. LLM_KV_GENERAL_NAME,
  232. LLM_KV_GENERAL_AUTHOR,
  233. LLM_KV_GENERAL_URL,
  234. LLM_KV_GENERAL_DESCRIPTION,
  235. LLM_KV_GENERAL_LICENSE,
  236. LLM_KV_GENERAL_SOURCE_URL,
  237. LLM_KV_GENERAL_SOURCE_HF_REPO,
  238. LLM_KV_VOCAB_SIZE,
  239. LLM_KV_CONTEXT_LENGTH,
  240. LLM_KV_EMBEDDING_LENGTH,
  241. LLM_KV_BLOCK_COUNT,
  242. LLM_KV_FEED_FORWARD_LENGTH,
  243. LLM_KV_USE_PARALLEL_RESIDUAL,
  244. LLM_KV_TENSOR_DATA_LAYOUT,
  245. LLM_KV_EXPERT_COUNT,
  246. LLM_KV_EXPERT_USED_COUNT,
  247. LLM_KV_POOLING_TYPE,
  248. LLM_KV_LOGIT_SCALE,
  249. LLM_KV_ATTENTION_HEAD_COUNT,
  250. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  251. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  252. LLM_KV_ATTENTION_CLAMP_KQV,
  253. LLM_KV_ATTENTION_KEY_LENGTH,
  254. LLM_KV_ATTENTION_VALUE_LENGTH,
  255. LLM_KV_ATTENTION_LAYERNORM_EPS,
  256. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  257. LLM_KV_ATTENTION_CAUSAL,
  258. LLM_KV_ROPE_DIMENSION_COUNT,
  259. LLM_KV_ROPE_FREQ_BASE,
  260. LLM_KV_ROPE_SCALE_LINEAR,
  261. LLM_KV_ROPE_SCALING_TYPE,
  262. LLM_KV_ROPE_SCALING_FACTOR,
  263. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  264. LLM_KV_ROPE_SCALING_FINETUNED,
  265. LLM_KV_SPLIT_NO,
  266. LLM_KV_SPLIT_COUNT,
  267. LLM_KV_SPLIT_TENSORS_COUNT,
  268. LLM_KV_SSM_INNER_SIZE,
  269. LLM_KV_SSM_CONV_KERNEL,
  270. LLM_KV_SSM_STATE_SIZE,
  271. LLM_KV_SSM_TIME_STEP_RANK,
  272. LLM_KV_TOKENIZER_MODEL,
  273. LLM_KV_TOKENIZER_LIST,
  274. LLM_KV_TOKENIZER_TOKEN_TYPE,
  275. LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT,
  276. LLM_KV_TOKENIZER_SCORES,
  277. LLM_KV_TOKENIZER_MERGES,
  278. LLM_KV_TOKENIZER_BOS_ID,
  279. LLM_KV_TOKENIZER_EOS_ID,
  280. LLM_KV_TOKENIZER_UNK_ID,
  281. LLM_KV_TOKENIZER_SEP_ID,
  282. LLM_KV_TOKENIZER_PAD_ID,
  283. LLM_KV_TOKENIZER_ADD_BOS,
  284. LLM_KV_TOKENIZER_ADD_EOS,
  285. LLM_KV_TOKENIZER_ADD_PREFIX,
  286. LLM_KV_TOKENIZER_HF_JSON,
  287. LLM_KV_TOKENIZER_RWKV,
  288. };
  289. static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
  290. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  291. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  292. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  293. { LLM_KV_GENERAL_NAME, "general.name" },
  294. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  295. { LLM_KV_GENERAL_URL, "general.url" },
  296. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  297. { LLM_KV_GENERAL_LICENSE, "general.license" },
  298. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  299. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  300. { LLM_KV_VOCAB_SIZE, "%s.vocab_size" },
  301. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  302. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  303. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  304. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  305. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  306. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  307. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  308. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  309. { LLM_KV_POOLING_TYPE , "%s.pooling_type" },
  310. { LLM_KV_LOGIT_SCALE, "%s.logit_scale" },
  311. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  312. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  313. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  314. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  315. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  316. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  317. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  318. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  319. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  320. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  321. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  322. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  323. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  324. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  325. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  326. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  327. { LLM_KV_SPLIT_NO, "split.no" },
  328. { LLM_KV_SPLIT_COUNT, "split.count" },
  329. { LLM_KV_SPLIT_TENSORS_COUNT, "split.tensors.count" },
  330. { LLM_KV_SSM_CONV_KERNEL, "%s.ssm.conv_kernel" },
  331. { LLM_KV_SSM_INNER_SIZE, "%s.ssm.inner_size" },
  332. { LLM_KV_SSM_STATE_SIZE, "%s.ssm.state_size" },
  333. { LLM_KV_SSM_TIME_STEP_RANK, "%s.ssm.time_step_rank" },
  334. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  335. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  336. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  337. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  338. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  339. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  340. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  341. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  342. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  343. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  344. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  345. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  346. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  347. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  348. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  349. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  350. };
  351. struct LLM_KV {
  352. LLM_KV(llm_arch arch) : arch(arch) {}
  353. llm_arch arch;
  354. std::string operator()(llm_kv kv) const {
  355. return ::format(LLM_KV_NAMES.at(kv), LLM_ARCH_NAMES.at(arch));
  356. }
  357. };
  358. enum llm_tensor {
  359. LLM_TENSOR_TOKEN_EMBD,
  360. LLM_TENSOR_TOKEN_EMBD_NORM,
  361. LLM_TENSOR_TOKEN_TYPES,
  362. LLM_TENSOR_POS_EMBD,
  363. LLM_TENSOR_OUTPUT,
  364. LLM_TENSOR_OUTPUT_NORM,
  365. LLM_TENSOR_ROPE_FREQS,
  366. LLM_TENSOR_ATTN_Q,
  367. LLM_TENSOR_ATTN_K,
  368. LLM_TENSOR_ATTN_V,
  369. LLM_TENSOR_ATTN_QKV,
  370. LLM_TENSOR_ATTN_OUT,
  371. LLM_TENSOR_ATTN_NORM,
  372. LLM_TENSOR_ATTN_NORM_2,
  373. LLM_TENSOR_ATTN_OUT_NORM,
  374. LLM_TENSOR_ATTN_ROT_EMBD,
  375. LLM_TENSOR_FFN_GATE_INP,
  376. LLM_TENSOR_FFN_NORM,
  377. LLM_TENSOR_FFN_GATE,
  378. LLM_TENSOR_FFN_DOWN,
  379. LLM_TENSOR_FFN_UP,
  380. LLM_TENSOR_FFN_ACT,
  381. LLM_TENSOR_FFN_DOWN_EXP,
  382. LLM_TENSOR_FFN_GATE_EXP,
  383. LLM_TENSOR_FFN_UP_EXP,
  384. LLM_TENSOR_ATTN_Q_NORM,
  385. LLM_TENSOR_ATTN_K_NORM,
  386. LLM_TENSOR_LAYER_OUT_NORM,
  387. LLM_TENSOR_SSM_IN,
  388. LLM_TENSOR_SSM_CONV1D,
  389. LLM_TENSOR_SSM_X,
  390. LLM_TENSOR_SSM_DT,
  391. LLM_TENSOR_SSM_A,
  392. LLM_TENSOR_SSM_D,
  393. LLM_TENSOR_SSM_OUT,
  394. };
  395. static const std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  396. {
  397. LLM_ARCH_LLAMA,
  398. {
  399. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  400. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  401. { LLM_TENSOR_OUTPUT, "output" },
  402. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  403. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  404. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  405. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  406. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  407. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  408. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  409. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  410. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  411. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  412. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  413. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  414. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  415. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  416. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  417. },
  418. },
  419. {
  420. LLM_ARCH_BAICHUAN,
  421. {
  422. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  423. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  424. { LLM_TENSOR_OUTPUT, "output" },
  425. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  426. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  427. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  428. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  429. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  430. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  431. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  432. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  433. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  434. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  435. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  436. },
  437. },
  438. {
  439. LLM_ARCH_FALCON,
  440. {
  441. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  442. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  443. { LLM_TENSOR_OUTPUT, "output" },
  444. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  445. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  446. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  447. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  448. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  449. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  450. },
  451. },
  452. {
  453. LLM_ARCH_GPT2,
  454. {
  455. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  456. { LLM_TENSOR_POS_EMBD, "position_embd" },
  457. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  458. { LLM_TENSOR_OUTPUT, "output" },
  459. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  460. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  461. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  462. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  463. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  464. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  465. },
  466. },
  467. {
  468. LLM_ARCH_GPTJ,
  469. {
  470. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  471. },
  472. },
  473. {
  474. LLM_ARCH_GPTNEOX,
  475. {
  476. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  477. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  478. { LLM_TENSOR_OUTPUT, "output" },
  479. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  480. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  481. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  482. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  483. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  484. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  485. },
  486. },
  487. {
  488. LLM_ARCH_PERSIMMON,
  489. {
  490. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  491. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  492. { LLM_TENSOR_OUTPUT, "output"},
  493. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  494. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  495. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  496. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  497. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  498. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  499. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  500. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  501. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  502. },
  503. },
  504. {
  505. LLM_ARCH_MPT,
  506. {
  507. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  508. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  509. { LLM_TENSOR_OUTPUT, "output"},
  510. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  511. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  512. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  513. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  514. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  515. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  516. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  517. },
  518. },
  519. {
  520. LLM_ARCH_STARCODER,
  521. {
  522. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  523. { LLM_TENSOR_POS_EMBD, "position_embd" },
  524. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  525. { LLM_TENSOR_OUTPUT, "output" },
  526. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  527. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  528. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  529. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  530. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  531. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  532. },
  533. },
  534. {
  535. LLM_ARCH_REFACT,
  536. {
  537. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  538. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  539. { LLM_TENSOR_OUTPUT, "output" },
  540. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  541. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  542. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  543. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  544. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  545. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  546. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  547. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  548. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  549. },
  550. },
  551. {
  552. LLM_ARCH_BERT,
  553. {
  554. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  555. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  556. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  557. { LLM_TENSOR_POS_EMBD, "position_embd" },
  558. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  559. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  560. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  561. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  562. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  563. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  564. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  565. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  566. },
  567. },
  568. {
  569. LLM_ARCH_NOMIC_BERT,
  570. {
  571. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  572. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  573. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  574. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  575. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  576. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  577. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  578. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  579. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  580. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  581. },
  582. },
  583. {
  584. LLM_ARCH_BLOOM,
  585. {
  586. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  587. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  588. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  589. { LLM_TENSOR_OUTPUT, "output" },
  590. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  591. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  592. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  593. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  594. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  595. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  596. },
  597. },
  598. {
  599. LLM_ARCH_STABLELM,
  600. {
  601. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  602. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  603. { LLM_TENSOR_OUTPUT, "output" },
  604. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  605. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  606. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  607. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  608. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  609. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  610. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  611. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  612. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  613. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  614. },
  615. },
  616. {
  617. LLM_ARCH_QWEN,
  618. {
  619. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  620. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  621. { LLM_TENSOR_OUTPUT, "output" },
  622. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  623. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  624. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  625. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  626. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  627. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  628. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  629. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  630. },
  631. },
  632. {
  633. LLM_ARCH_QWEN2,
  634. {
  635. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  636. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  637. { LLM_TENSOR_OUTPUT, "output" },
  638. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  639. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  640. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  641. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  642. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  643. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  644. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  645. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  646. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  647. },
  648. },
  649. {
  650. LLM_ARCH_PHI2,
  651. {
  652. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  653. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  654. { LLM_TENSOR_OUTPUT, "output" },
  655. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  656. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  657. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  658. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  659. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  660. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  661. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  662. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  663. },
  664. },
  665. {
  666. LLM_ARCH_PLAMO,
  667. {
  668. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  669. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  670. { LLM_TENSOR_OUTPUT, "output" },
  671. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  672. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  673. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  674. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  675. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  676. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  677. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  678. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  679. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  680. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  681. },
  682. },
  683. {
  684. LLM_ARCH_CODESHELL,
  685. {
  686. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  687. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  688. { LLM_TENSOR_OUTPUT, "output" },
  689. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  690. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  691. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  692. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  693. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  694. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  695. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  696. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  697. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  698. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  699. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  700. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  701. },
  702. },
  703. {
  704. LLM_ARCH_ORION,
  705. {
  706. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  707. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  708. { LLM_TENSOR_OUTPUT, "output" },
  709. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  710. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  711. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  712. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  713. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  714. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  715. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  716. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  717. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  718. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  719. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  720. },
  721. },
  722. {
  723. LLM_ARCH_INTERNLM2,
  724. {
  725. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  726. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  727. { LLM_TENSOR_OUTPUT, "output" },
  728. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  729. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  730. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  731. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  732. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  733. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  734. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  735. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  736. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  737. },
  738. },
  739. {
  740. LLM_ARCH_MINICPM,
  741. {
  742. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  743. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  744. { LLM_TENSOR_OUTPUT, "output" },
  745. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  746. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  747. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  748. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  749. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  750. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  751. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  752. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  753. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  754. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  755. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  756. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  757. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  758. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  759. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  760. },
  761. },
  762. {
  763. LLM_ARCH_GEMMA,
  764. {
  765. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  766. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  767. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  768. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  769. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  770. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  771. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  772. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  773. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  774. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  775. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  776. },
  777. },
  778. {
  779. LLM_ARCH_STARCODER2,
  780. {
  781. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  782. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  783. { LLM_TENSOR_OUTPUT, "output" },
  784. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  785. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  786. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  787. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  788. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  789. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  790. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  791. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  792. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  793. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  794. },
  795. },
  796. {
  797. LLM_ARCH_MAMBA,
  798. {
  799. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  800. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  801. { LLM_TENSOR_OUTPUT, "output" },
  802. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  803. { LLM_TENSOR_SSM_IN, "blk.%d.ssm_in" },
  804. { LLM_TENSOR_SSM_CONV1D, "blk.%d.ssm_conv1d" },
  805. { LLM_TENSOR_SSM_X, "blk.%d.ssm_x" },
  806. { LLM_TENSOR_SSM_DT, "blk.%d.ssm_dt" },
  807. { LLM_TENSOR_SSM_A, "blk.%d.ssm_a" },
  808. { LLM_TENSOR_SSM_D, "blk.%d.ssm_d" },
  809. { LLM_TENSOR_SSM_OUT, "blk.%d.ssm_out" },
  810. },
  811. },
  812. {
  813. LLM_ARCH_COMMAND_R,
  814. {
  815. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  816. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  817. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  818. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  819. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  820. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  821. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  822. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  823. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  824. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  825. },
  826. },
  827. {
  828. LLM_ARCH_UNKNOWN,
  829. {
  830. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  831. },
  832. },
  833. };
  834. static llm_arch llm_arch_from_string(const std::string & name) {
  835. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  836. if (kv.second == name) {
  837. return kv.first;
  838. }
  839. }
  840. return LLM_ARCH_UNKNOWN;
  841. }
  842. // helper to handle gguf constants
  843. // usage:
  844. //
  845. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  846. //
  847. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  848. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  849. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  850. //
  851. struct LLM_TN {
  852. LLM_TN(llm_arch arch) : arch(arch) {}
  853. llm_arch arch;
  854. std::string operator()(llm_tensor tensor) const {
  855. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  856. return "__missing__";
  857. }
  858. return LLM_TENSOR_NAMES.at(arch).at(tensor);
  859. }
  860. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  861. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  862. return "__missing__";
  863. }
  864. return LLM_TENSOR_NAMES.at(arch).at(tensor) + "." + suffix;
  865. }
  866. std::string operator()(llm_tensor tensor, int bid) const {
  867. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  868. return "__missing__";
  869. }
  870. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid);
  871. }
  872. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  873. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  874. return "__missing__";
  875. }
  876. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid) + "." + suffix;
  877. }
  878. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  879. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  880. return "__missing__";
  881. }
  882. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid, xid) + "." + suffix;
  883. }
  884. };
  885. //
  886. // gguf helpers
  887. //
  888. static const std::map<llama_rope_scaling_type, const char *> LLAMA_ROPE_SCALING_TYPES = {
  889. { LLAMA_ROPE_SCALING_TYPE_NONE, "none" },
  890. { LLAMA_ROPE_SCALING_TYPE_LINEAR, "linear" },
  891. { LLAMA_ROPE_SCALING_TYPE_YARN, "yarn" },
  892. };
  893. static llama_rope_scaling_type llama_rope_scaling_type_from_string(const std::string & name) {
  894. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  895. if (kv.second == name) {
  896. return (llama_rope_scaling_type) kv.first;
  897. }
  898. }
  899. return LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
  900. }
  901. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  902. switch (type) {
  903. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  904. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  905. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  906. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  907. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  908. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  909. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  910. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  911. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  912. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  913. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  914. default: return format("unknown type %d", type);
  915. }
  916. }
  917. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  918. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  919. switch (type) {
  920. case GGUF_TYPE_STRING:
  921. return gguf_get_val_str(ctx_gguf, i);
  922. case GGUF_TYPE_ARRAY:
  923. {
  924. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  925. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  926. const void * data = gguf_get_arr_data(ctx_gguf, i);
  927. std::stringstream ss;
  928. ss << "[";
  929. for (int j = 0; j < arr_n; j++) {
  930. if (arr_type == GGUF_TYPE_STRING) {
  931. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  932. // escape quotes
  933. replace_all(val, "\\", "\\\\");
  934. replace_all(val, "\"", "\\\"");
  935. ss << '"' << val << '"';
  936. } else if (arr_type == GGUF_TYPE_ARRAY) {
  937. ss << "???";
  938. } else {
  939. ss << gguf_data_to_str(arr_type, data, j);
  940. }
  941. if (j < arr_n - 1) {
  942. ss << ", ";
  943. }
  944. }
  945. ss << "]";
  946. return ss.str();
  947. }
  948. default:
  949. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  950. }
  951. }
  952. //
  953. // llama helpers
  954. //
  955. #if defined(_WIN32)
  956. static std::string llama_format_win_err(DWORD err) {
  957. LPSTR buf;
  958. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  959. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  960. if (!size) {
  961. return "FormatMessageA failed";
  962. }
  963. std::string ret(buf, size);
  964. LocalFree(buf);
  965. return ret;
  966. }
  967. #endif
  968. template <typename T>
  969. struct no_init {
  970. T value;
  971. no_init() { /* do nothing */ }
  972. };
  973. struct llama_file {
  974. // use FILE * so we don't have to re-open the file to mmap
  975. FILE * fp;
  976. size_t size;
  977. llama_file(const char * fname, const char * mode) {
  978. fp = std::fopen(fname, mode);
  979. if (fp == NULL) {
  980. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  981. }
  982. seek(0, SEEK_END);
  983. size = tell();
  984. seek(0, SEEK_SET);
  985. }
  986. size_t tell() const {
  987. #ifdef _WIN32
  988. __int64 ret = _ftelli64(fp);
  989. #else
  990. long ret = std::ftell(fp);
  991. #endif
  992. GGML_ASSERT(ret != -1); // this really shouldn't fail
  993. return (size_t) ret;
  994. }
  995. void seek(size_t offset, int whence) const {
  996. #ifdef _WIN32
  997. int ret = _fseeki64(fp, (__int64) offset, whence);
  998. #else
  999. int ret = std::fseek(fp, (long) offset, whence);
  1000. #endif
  1001. GGML_ASSERT(ret == 0); // same
  1002. }
  1003. void read_raw(void * ptr, size_t len) const {
  1004. if (len == 0) {
  1005. return;
  1006. }
  1007. errno = 0;
  1008. std::size_t ret = std::fread(ptr, len, 1, fp);
  1009. if (ferror(fp)) {
  1010. throw std::runtime_error(format("read error: %s", strerror(errno)));
  1011. }
  1012. if (ret != 1) {
  1013. throw std::runtime_error("unexpectedly reached end of file");
  1014. }
  1015. }
  1016. uint32_t read_u32() const {
  1017. uint32_t ret;
  1018. read_raw(&ret, sizeof(ret));
  1019. return ret;
  1020. }
  1021. void write_raw(const void * ptr, size_t len) const {
  1022. if (len == 0) {
  1023. return;
  1024. }
  1025. errno = 0;
  1026. size_t ret = std::fwrite(ptr, len, 1, fp);
  1027. if (ret != 1) {
  1028. throw std::runtime_error(format("write error: %s", strerror(errno)));
  1029. }
  1030. }
  1031. void write_u32(std::uint32_t val) const {
  1032. write_raw(&val, sizeof(val));
  1033. }
  1034. ~llama_file() {
  1035. if (fp) {
  1036. std::fclose(fp);
  1037. }
  1038. }
  1039. };
  1040. using llama_files = std::vector<std::unique_ptr<llama_file>>;
  1041. struct llama_mmap {
  1042. void * addr;
  1043. size_t size;
  1044. llama_mmap(const llama_mmap &) = delete;
  1045. #ifdef _POSIX_MAPPED_FILES
  1046. static constexpr bool SUPPORTED = true;
  1047. // list of mapped fragments (first_offset, last_offset)
  1048. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  1049. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  1050. size = file->size;
  1051. int fd = fileno(file->fp);
  1052. int flags = MAP_SHARED;
  1053. // prefetch/readahead impairs performance on NUMA systems
  1054. if (numa) { prefetch = 0; }
  1055. #ifdef __linux__
  1056. // advise the kernel to read the file sequentially (increases readahead)
  1057. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  1058. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  1059. strerror(errno));
  1060. }
  1061. if (prefetch) { flags |= MAP_POPULATE; }
  1062. #endif
  1063. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  1064. if (addr == MAP_FAILED) { // NOLINT
  1065. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  1066. }
  1067. if (prefetch > 0) {
  1068. // advise the kernel to preload the mapped memory
  1069. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  1070. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  1071. strerror(errno));
  1072. }
  1073. }
  1074. if (numa) {
  1075. // advise the kernel not to use readahead
  1076. // (because the next page might not belong on the same node)
  1077. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  1078. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  1079. strerror(errno));
  1080. }
  1081. }
  1082. // initialize list of mapped_fragments
  1083. mapped_fragments.emplace_back(0, file->size);
  1084. }
  1085. static void align_range(size_t * first, size_t * last, size_t page_size) {
  1086. // align first to the next page
  1087. size_t offset_in_page = *first & (page_size - 1);
  1088. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  1089. *first += offset_to_page;
  1090. // align last to the previous page
  1091. *last = *last & ~(page_size - 1);
  1092. if (*last <= *first) {
  1093. *last = *first;
  1094. }
  1095. }
  1096. // partially unmap the file in the range [first, last)
  1097. void unmap_fragment(size_t first, size_t last) {
  1098. // note: this function must not be called multiple times with overlapping ranges
  1099. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  1100. int page_size = sysconf(_SC_PAGESIZE);
  1101. align_range(&first, &last, page_size);
  1102. size_t len = last - first;
  1103. if (len == 0) {
  1104. return;
  1105. }
  1106. GGML_ASSERT(first % page_size == 0);
  1107. GGML_ASSERT(last % page_size == 0);
  1108. GGML_ASSERT(last > first);
  1109. void * next_page_start = (uint8_t *) addr + first;
  1110. // unmap the range
  1111. if (munmap(next_page_start, len)) {
  1112. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1113. }
  1114. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  1115. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  1116. for (const auto & frag : mapped_fragments) {
  1117. if (frag.first < first && frag.second > last) {
  1118. // the range is in the middle of the fragment, split it
  1119. new_mapped_fragments.emplace_back(frag.first, first);
  1120. new_mapped_fragments.emplace_back(last, frag.second);
  1121. } else if (frag.first < first && frag.second > first) {
  1122. // the range starts in the middle of the fragment
  1123. new_mapped_fragments.emplace_back(frag.first, first);
  1124. } else if (frag.first < last && frag.second > last) {
  1125. // the range ends in the middle of the fragment
  1126. new_mapped_fragments.emplace_back(last, frag.second);
  1127. } else if (frag.first >= first && frag.second <= last) {
  1128. // the range covers the entire fragment
  1129. } else {
  1130. // the range is outside the fragment
  1131. new_mapped_fragments.push_back(frag);
  1132. }
  1133. }
  1134. mapped_fragments = std::move(new_mapped_fragments);
  1135. }
  1136. ~llama_mmap() {
  1137. for (const auto & frag : mapped_fragments) {
  1138. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  1139. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1140. }
  1141. }
  1142. }
  1143. #elif defined(_WIN32)
  1144. static constexpr bool SUPPORTED = true;
  1145. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  1146. GGML_UNUSED(numa);
  1147. size = file->size;
  1148. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  1149. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  1150. if (hMapping == NULL) {
  1151. DWORD error = GetLastError();
  1152. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  1153. }
  1154. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  1155. DWORD error = GetLastError();
  1156. CloseHandle(hMapping);
  1157. if (addr == NULL) {
  1158. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  1159. }
  1160. if (prefetch > 0) {
  1161. #if _WIN32_WINNT >= 0x602
  1162. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  1163. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  1164. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  1165. // may fail on pre-Windows 8 systems
  1166. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  1167. if (pPrefetchVirtualMemory) {
  1168. // advise the kernel to preload the mapped memory
  1169. WIN32_MEMORY_RANGE_ENTRY range;
  1170. range.VirtualAddress = addr;
  1171. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  1172. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  1173. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  1174. llama_format_win_err(GetLastError()).c_str());
  1175. }
  1176. }
  1177. #else
  1178. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  1179. #endif
  1180. }
  1181. }
  1182. void unmap_fragment(size_t first, size_t last) {
  1183. // not supported
  1184. GGML_UNUSED(first);
  1185. GGML_UNUSED(last);
  1186. }
  1187. ~llama_mmap() {
  1188. if (!UnmapViewOfFile(addr)) {
  1189. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  1190. llama_format_win_err(GetLastError()).c_str());
  1191. }
  1192. }
  1193. #else
  1194. static constexpr bool SUPPORTED = false;
  1195. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  1196. GGML_UNUSED(file);
  1197. GGML_UNUSED(prefetch);
  1198. GGML_UNUSED(numa);
  1199. throw std::runtime_error("mmap not supported");
  1200. }
  1201. void unmap_fragment(size_t first, size_t last) {
  1202. GGML_UNUSED(first);
  1203. GGML_UNUSED(last);
  1204. throw std::runtime_error("mmap not supported");
  1205. }
  1206. #endif
  1207. };
  1208. using llama_mmaps = std::vector<std::unique_ptr<llama_mmap>>;
  1209. // Represents some region of memory being locked using mlock or VirtualLock;
  1210. // will automatically unlock on destruction.
  1211. struct llama_mlock {
  1212. void * addr = NULL;
  1213. size_t size = 0;
  1214. bool failed_already = false;
  1215. llama_mlock() {}
  1216. llama_mlock(const llama_mlock &) = delete;
  1217. ~llama_mlock() {
  1218. if (size) {
  1219. raw_unlock(addr, size);
  1220. }
  1221. }
  1222. void init(void * ptr) {
  1223. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1224. addr = ptr;
  1225. }
  1226. void grow_to(size_t target_size) {
  1227. GGML_ASSERT(addr);
  1228. if (failed_already) {
  1229. return;
  1230. }
  1231. size_t granularity = lock_granularity();
  1232. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1233. if (target_size > size) {
  1234. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1235. size = target_size;
  1236. } else {
  1237. failed_already = true;
  1238. }
  1239. }
  1240. }
  1241. #ifdef _POSIX_MEMLOCK_RANGE
  1242. static constexpr bool SUPPORTED = true;
  1243. static size_t lock_granularity() {
  1244. return (size_t) sysconf(_SC_PAGESIZE);
  1245. }
  1246. #ifdef __APPLE__
  1247. #define MLOCK_SUGGESTION \
  1248. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1249. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  1250. #else
  1251. #define MLOCK_SUGGESTION \
  1252. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  1253. #endif
  1254. bool raw_lock(const void * addr, size_t size) const {
  1255. if (!mlock(addr, size)) {
  1256. return true;
  1257. }
  1258. char* errmsg = std::strerror(errno);
  1259. bool suggest = (errno == ENOMEM);
  1260. // Check if the resource limit is fine after all
  1261. struct rlimit lock_limit;
  1262. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1263. suggest = false;
  1264. }
  1265. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1266. suggest = false;
  1267. }
  1268. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1269. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1270. return false;
  1271. }
  1272. #undef MLOCK_SUGGESTION
  1273. static void raw_unlock(void * addr, size_t size) {
  1274. if (munlock(addr, size)) {
  1275. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1276. }
  1277. }
  1278. #elif defined(_WIN32)
  1279. static constexpr bool SUPPORTED = true;
  1280. static size_t lock_granularity() {
  1281. SYSTEM_INFO si;
  1282. GetSystemInfo(&si);
  1283. return (size_t) si.dwPageSize;
  1284. }
  1285. bool raw_lock(void * ptr, size_t len) const {
  1286. for (int tries = 1; ; tries++) {
  1287. if (VirtualLock(ptr, len)) {
  1288. return true;
  1289. }
  1290. if (tries == 2) {
  1291. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1292. len, size, llama_format_win_err(GetLastError()).c_str());
  1293. return false;
  1294. }
  1295. // It failed but this was only the first try; increase the working
  1296. // set size and try again.
  1297. SIZE_T min_ws_size, max_ws_size;
  1298. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1299. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1300. llama_format_win_err(GetLastError()).c_str());
  1301. return false;
  1302. }
  1303. // Per MSDN: "The maximum number of pages that a process can lock
  1304. // is equal to the number of pages in its minimum working set minus
  1305. // a small overhead."
  1306. // Hopefully a megabyte is enough overhead:
  1307. size_t increment = len + 1048576;
  1308. // The minimum must be <= the maximum, so we need to increase both:
  1309. min_ws_size += increment;
  1310. max_ws_size += increment;
  1311. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1312. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1313. llama_format_win_err(GetLastError()).c_str());
  1314. return false;
  1315. }
  1316. }
  1317. }
  1318. static void raw_unlock(void * ptr, size_t len) {
  1319. if (!VirtualUnlock(ptr, len)) {
  1320. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1321. llama_format_win_err(GetLastError()).c_str());
  1322. }
  1323. }
  1324. #else
  1325. static constexpr bool SUPPORTED = false;
  1326. static size_t lock_granularity() {
  1327. return (size_t) 65536;
  1328. }
  1329. bool raw_lock(const void * addr, size_t len) const {
  1330. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1331. return false;
  1332. }
  1333. static void raw_unlock(const void * addr, size_t len) {}
  1334. #endif
  1335. };
  1336. using llama_mlocks = std::vector<std::unique_ptr<llama_mlock>>;
  1337. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1338. std::vector<char> result(8, 0);
  1339. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1340. if (n_tokens < 0) {
  1341. result.resize(-n_tokens);
  1342. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1343. GGML_ASSERT(check == -n_tokens);
  1344. }
  1345. else {
  1346. result.resize(n_tokens);
  1347. }
  1348. return std::string(result.data(), result.size());
  1349. }
  1350. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1351. ggml_backend_buffer_type_t buft = nullptr;
  1352. #if defined(GGML_USE_CUBLAS)
  1353. // host buffers should only be used when data is expected to be copied to/from the GPU
  1354. if (host_buffer) {
  1355. buft = ggml_backend_cuda_host_buffer_type();
  1356. }
  1357. #elif defined(GGML_USE_SYCL)
  1358. if (host_buffer) {
  1359. buft = ggml_backend_sycl_host_buffer_type();
  1360. }
  1361. #elif defined(GGML_USE_CPU_HBM)
  1362. buft = ggml_backend_cpu_hbm_buffer_type();
  1363. #elif defined(GGML_USE_VULKAN)
  1364. if (host_buffer) {
  1365. buft = ggml_backend_vk_host_buffer_type();
  1366. }
  1367. #endif
  1368. if (buft == nullptr) {
  1369. buft = ggml_backend_cpu_buffer_type();
  1370. }
  1371. return buft;
  1372. GGML_UNUSED(host_buffer);
  1373. }
  1374. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(int gpu) {
  1375. ggml_backend_buffer_type_t buft = nullptr;
  1376. #ifdef GGML_USE_METAL
  1377. buft = ggml_backend_metal_buffer_type();
  1378. #elif defined(GGML_USE_CUBLAS)
  1379. buft = ggml_backend_cuda_buffer_type(gpu);
  1380. #elif defined(GGML_USE_VULKAN)
  1381. buft = ggml_backend_vk_buffer_type(gpu);
  1382. #elif defined(GGML_USE_SYCL)
  1383. buft = ggml_backend_sycl_buffer_type(gpu);
  1384. #elif defined(GGML_USE_CLBLAST)
  1385. buft = ggml_backend_opencl_buffer_type();
  1386. #elif defined(GGML_USE_KOMPUTE)
  1387. buft = ggml_backend_kompute_buffer_type(gpu);
  1388. if (buft == nullptr) {
  1389. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, gpu);
  1390. }
  1391. #endif
  1392. if (buft == nullptr) {
  1393. buft = llama_default_buffer_type_cpu(true);
  1394. }
  1395. return buft;
  1396. GGML_UNUSED(gpu);
  1397. }
  1398. static ggml_backend_buffer_type_t llama_default_buffer_type_split(int fallback_gpu, const float * tensor_split) {
  1399. ggml_backend_buffer_type_t buft = nullptr;
  1400. #ifdef GGML_USE_CUBLAS
  1401. if (ggml_backend_cuda_get_device_count() > 1) {
  1402. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  1403. }
  1404. #endif
  1405. #ifdef GGML_USE_SYCL
  1406. if (ggml_backend_sycl_get_device_count() > 1) {
  1407. buft = ggml_backend_sycl_split_buffer_type(tensor_split);
  1408. }
  1409. #endif
  1410. if (buft == nullptr) {
  1411. buft = llama_default_buffer_type_offload(fallback_gpu);
  1412. }
  1413. return buft;
  1414. GGML_UNUSED(tensor_split);
  1415. }
  1416. static size_t llama_get_device_count() {
  1417. #if defined(GGML_USE_CUBLAS)
  1418. return ggml_backend_cuda_get_device_count();
  1419. #elif defined(GGML_USE_SYCL)
  1420. return ggml_backend_sycl_get_device_count();
  1421. #elif defined(GGML_USE_VULKAN)
  1422. return ggml_backend_vk_get_device_count();
  1423. #else
  1424. return 1;
  1425. #endif
  1426. }
  1427. static size_t llama_get_device_memory(int device) {
  1428. #if defined(GGML_USE_CUBLAS)
  1429. size_t total;
  1430. size_t free;
  1431. ggml_backend_cuda_get_device_memory(device, &total, &free);
  1432. return free;
  1433. #elif defined(GGML_USE_SYCL)
  1434. size_t total;
  1435. size_t free;
  1436. ggml_backend_sycl_get_device_memory(device, &total, &free);
  1437. return free;
  1438. #elif defined(GGML_USE_VULKAN)
  1439. size_t total;
  1440. size_t free;
  1441. ggml_backend_vk_get_device_memory(device, &total, &free);
  1442. return free;
  1443. #else
  1444. return 1;
  1445. GGML_UNUSED(device);
  1446. #endif
  1447. }
  1448. //
  1449. // globals
  1450. //
  1451. struct llama_state {
  1452. llama_state() {
  1453. #ifdef GGML_USE_METAL
  1454. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1455. #endif
  1456. }
  1457. // We save the log callback globally
  1458. ggml_log_callback log_callback = llama_log_callback_default;
  1459. void * log_callback_user_data = nullptr;
  1460. };
  1461. static llama_state g_state;
  1462. // available llama models
  1463. enum e_model {
  1464. MODEL_UNKNOWN,
  1465. MODEL_17M,
  1466. MODEL_22M,
  1467. MODEL_33M,
  1468. MODEL_109M,
  1469. MODEL_137M,
  1470. MODEL_335M,
  1471. MODEL_0_5B,
  1472. MODEL_1B,
  1473. MODEL_2B,
  1474. MODEL_3B,
  1475. MODEL_4B,
  1476. MODEL_7B,
  1477. MODEL_8B,
  1478. MODEL_13B,
  1479. MODEL_14B,
  1480. MODEL_15B,
  1481. MODEL_20B,
  1482. MODEL_30B,
  1483. MODEL_34B,
  1484. MODEL_35B,
  1485. MODEL_40B,
  1486. MODEL_65B,
  1487. MODEL_70B,
  1488. MODEL_SMALL,
  1489. MODEL_MEDIUM,
  1490. MODEL_LARGE,
  1491. MODEL_XL,
  1492. };
  1493. static const size_t kiB = 1024;
  1494. static const size_t MiB = 1024*kiB;
  1495. static const size_t GiB = 1024*MiB;
  1496. struct llama_hparams {
  1497. bool vocab_only;
  1498. bool rope_finetuned;
  1499. uint32_t n_vocab;
  1500. uint32_t n_ctx_train; // context size the model was trained on
  1501. uint32_t n_embd;
  1502. uint32_t n_head;
  1503. uint32_t n_head_kv;
  1504. uint32_t n_layer;
  1505. uint32_t n_rot;
  1506. uint32_t n_embd_head_k; // dimension of keys (d_k). d_q is assumed to be the same, but there are n_head q heads, and only n_head_kv k-v heads
  1507. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1508. uint32_t n_ff;
  1509. uint32_t n_expert = 0;
  1510. uint32_t n_expert_used = 0;
  1511. uint32_t n_vocab_type = 0; // for BERT-style token types
  1512. float f_norm_eps;
  1513. float f_norm_rms_eps;
  1514. float rope_freq_base_train;
  1515. float rope_freq_scale_train;
  1516. uint32_t n_yarn_orig_ctx;
  1517. // for State Space Models
  1518. uint32_t ssm_d_conv = 0;
  1519. uint32_t ssm_d_inner = 0;
  1520. uint32_t ssm_d_state = 0;
  1521. uint32_t ssm_dt_rank = 0;
  1522. float f_clamp_kqv = 0.0f;
  1523. float f_max_alibi_bias = 0.0f;
  1524. float f_logit_scale = 0.0f;
  1525. bool causal_attn = true;
  1526. bool need_kq_pos = false;
  1527. enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_NONE;
  1528. enum llama_rope_type rope_type = LLAMA_ROPE_TYPE_NONE;
  1529. enum llama_rope_scaling_type rope_scaling_type_train = LLAMA_ROPE_SCALING_TYPE_NONE;
  1530. bool operator!=(const llama_hparams & other) const {
  1531. if (this->vocab_only != other.vocab_only) return true;
  1532. if (this->n_vocab != other.n_vocab) return true;
  1533. if (this->n_ctx_train != other.n_ctx_train) return true;
  1534. if (this->n_embd != other.n_embd) return true;
  1535. if (this->n_head != other.n_head) return true;
  1536. if (this->n_head_kv != other.n_head_kv) return true;
  1537. if (this->n_layer != other.n_layer) return true;
  1538. if (this->n_rot != other.n_rot) return true;
  1539. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1540. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1541. if (this->n_ff != other.n_ff) return true;
  1542. if (this->n_expert != other.n_expert) return true;
  1543. if (this->n_expert_used != other.n_expert_used) return true;
  1544. if (this->rope_finetuned != other.rope_finetuned) return true;
  1545. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1546. if (this->ssm_d_conv != other.ssm_d_conv) return true;
  1547. if (this->ssm_d_inner != other.ssm_d_inner) return true;
  1548. if (this->ssm_d_state != other.ssm_d_state) return true;
  1549. if (this->ssm_dt_rank != other.ssm_dt_rank) return true;
  1550. const float EPSILON = 1e-9f;
  1551. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1552. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1553. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1554. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1555. return false;
  1556. }
  1557. uint32_t n_gqa() const {
  1558. if (n_head_kv == 0) {
  1559. return 0;
  1560. }
  1561. return n_head/n_head_kv;
  1562. }
  1563. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1564. return n_embd_head_k * n_head_kv;
  1565. }
  1566. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1567. return n_embd_head_v * n_head_kv;
  1568. }
  1569. uint32_t n_embd_k_s() const { // dimension of the rolling state embeddings
  1570. // corresponds to Mamba's conv_states size
  1571. // TODO: maybe support other convolution strides than 1
  1572. // NOTE: since the first column of the conv_state is shifted out each time, it's not actually needed
  1573. return (ssm_d_conv > 0 ? ssm_d_conv - 1 : 0) * ssm_d_inner;
  1574. }
  1575. uint32_t n_embd_v_s() const { // dimension of the recurrent state embeddings
  1576. // corresponds to Mamba's ssm_states size
  1577. return ssm_d_state * ssm_d_inner;
  1578. }
  1579. };
  1580. struct llama_cparams {
  1581. uint32_t n_ctx; // context size used during inference
  1582. uint32_t n_batch;
  1583. uint32_t n_ubatch;
  1584. uint32_t n_threads; // number of threads to use for generation
  1585. uint32_t n_threads_batch; // number of threads to use for batch processing
  1586. float rope_freq_base;
  1587. float rope_freq_scale;
  1588. uint32_t n_yarn_orig_ctx;
  1589. // These hyperparameters are not exposed in GGUF, because all
  1590. // existing YaRN models use the same values for them.
  1591. float yarn_ext_factor;
  1592. float yarn_attn_factor;
  1593. float yarn_beta_fast;
  1594. float yarn_beta_slow;
  1595. float defrag_thold;
  1596. bool embeddings;
  1597. bool causal_attn;
  1598. bool offload_kqv;
  1599. enum llama_pooling_type pooling_type;
  1600. ggml_backend_sched_eval_callback cb_eval;
  1601. void * cb_eval_user_data;
  1602. };
  1603. struct llama_layer {
  1604. // normalization
  1605. struct ggml_tensor * attn_norm;
  1606. struct ggml_tensor * attn_norm_b;
  1607. struct ggml_tensor * attn_norm_2;
  1608. struct ggml_tensor * attn_norm_2_b;
  1609. struct ggml_tensor * attn_q_norm;
  1610. struct ggml_tensor * attn_q_norm_b;
  1611. struct ggml_tensor * attn_k_norm;
  1612. struct ggml_tensor * attn_k_norm_b;
  1613. struct ggml_tensor * attn_out_norm;
  1614. struct ggml_tensor * attn_out_norm_b;
  1615. // attention
  1616. struct ggml_tensor * wq;
  1617. struct ggml_tensor * wk;
  1618. struct ggml_tensor * wv;
  1619. struct ggml_tensor * wo;
  1620. struct ggml_tensor * wqkv;
  1621. // attention bias
  1622. struct ggml_tensor * bq;
  1623. struct ggml_tensor * bk;
  1624. struct ggml_tensor * bv;
  1625. struct ggml_tensor * bo;
  1626. struct ggml_tensor * bqkv;
  1627. // normalization
  1628. struct ggml_tensor * ffn_norm;
  1629. struct ggml_tensor * ffn_norm_b;
  1630. struct ggml_tensor * layer_out_norm;
  1631. struct ggml_tensor * layer_out_norm_b;
  1632. // ff
  1633. struct ggml_tensor * ffn_gate; // w1
  1634. struct ggml_tensor * ffn_down; // w2
  1635. struct ggml_tensor * ffn_up; // w3
  1636. // ff MoE
  1637. struct ggml_tensor * ffn_gate_inp;
  1638. struct ggml_tensor * ffn_gate_exp[LLAMA_MAX_EXPERTS];
  1639. struct ggml_tensor * ffn_down_exp[LLAMA_MAX_EXPERTS];
  1640. struct ggml_tensor * ffn_up_exp [LLAMA_MAX_EXPERTS];
  1641. // ff bias
  1642. struct ggml_tensor * ffn_down_b; // b2
  1643. struct ggml_tensor * ffn_up_b; // b3
  1644. struct ggml_tensor * ffn_act;
  1645. // mamba proj
  1646. struct ggml_tensor * ssm_in;
  1647. struct ggml_tensor * ssm_x;
  1648. struct ggml_tensor * ssm_dt;
  1649. struct ggml_tensor * ssm_out;
  1650. // mamba
  1651. struct ggml_tensor * ssm_conv1d;
  1652. struct ggml_tensor * ssm_a;
  1653. struct ggml_tensor * ssm_d;
  1654. // mamba bias
  1655. struct ggml_tensor * ssm_conv1d_b;
  1656. struct ggml_tensor * ssm_dt_b;
  1657. };
  1658. struct llama_kv_cell {
  1659. llama_pos pos = -1;
  1660. llama_pos delta = 0;
  1661. int32_t src = 0; // used by recurrent state models to copy states
  1662. std::set<llama_seq_id> seq_id;
  1663. bool has_seq_id(const llama_seq_id & id) const {
  1664. return seq_id.find(id) != seq_id.end();
  1665. }
  1666. bool is_empty() const {
  1667. return seq_id.empty();
  1668. }
  1669. bool is_same_seq(const llama_kv_cell & other) const {
  1670. return seq_id == other.seq_id;
  1671. }
  1672. };
  1673. // ring-buffer of cached KV data
  1674. struct llama_kv_cache {
  1675. bool has_shift = false;
  1676. bool do_defrag = false;
  1677. bool do_copy = false;
  1678. // with recurrent state models, a cell can hold the state for more than one past token
  1679. bool recurrent = false;
  1680. // Note: The value of head isn't only used to optimize searching
  1681. // for a free KV slot. llama_decode_internal also uses it, so it
  1682. // cannot be freely changed after a slot has been allocated.
  1683. uint32_t head = 0;
  1684. uint32_t size = 0;
  1685. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1686. // computed before each graph build
  1687. uint32_t n = 0;
  1688. ggml_type type_k = GGML_TYPE_F16;
  1689. ggml_type type_v = GGML_TYPE_F16;
  1690. std::vector<llama_kv_cell> cells;
  1691. std::vector<struct ggml_tensor *> k_l; // per layer
  1692. std::vector<struct ggml_tensor *> v_l;
  1693. std::vector<struct ggml_context *> ctxs;
  1694. std::vector<ggml_backend_buffer_t> bufs;
  1695. size_t total_size() const {
  1696. size_t size = 0;
  1697. for (ggml_backend_buffer_t buf : bufs) {
  1698. size += ggml_backend_buffer_get_size(buf);
  1699. }
  1700. return size;
  1701. }
  1702. ~llama_kv_cache() {
  1703. for (struct ggml_context * ctx : ctxs) {
  1704. ggml_free(ctx);
  1705. }
  1706. for (ggml_backend_buffer_t buf : bufs) {
  1707. ggml_backend_buffer_free(buf);
  1708. }
  1709. }
  1710. };
  1711. struct llama_control_vector {
  1712. std::vector<struct ggml_tensor *> tensors; // per layer
  1713. std::vector<struct ggml_context *> ctxs;
  1714. std::vector<ggml_backend_buffer_t> bufs;
  1715. int32_t layer_start = -1;
  1716. int32_t layer_end = -1;
  1717. ggml_tensor * tensor_for(int il) const {
  1718. if (il < 0 || il < layer_start || il > layer_end || (size_t) il >= tensors.size()) {
  1719. return nullptr;
  1720. }
  1721. return tensors[il];
  1722. }
  1723. ~llama_control_vector() {
  1724. for (struct ggml_context * ctx : ctxs) {
  1725. ggml_free(ctx);
  1726. }
  1727. for (ggml_backend_buffer_t buf : bufs) {
  1728. ggml_backend_buffer_free(buf);
  1729. }
  1730. }
  1731. };
  1732. struct llama_vocab {
  1733. using id = int32_t;
  1734. using token = std::string;
  1735. using ttype = llama_token_type;
  1736. struct token_data {
  1737. token text;
  1738. float score;
  1739. ttype type;
  1740. };
  1741. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1742. std::unordered_map<token, id> token_to_id;
  1743. std::vector<token_data> id_to_token;
  1744. std::unordered_map<token, id> special_tokens_cache;
  1745. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1746. // default LLaMA special tokens
  1747. id special_bos_id = 1;
  1748. id special_eos_id = 2;
  1749. id special_unk_id = 0;
  1750. id special_sep_id = -1;
  1751. id special_pad_id = -1;
  1752. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1753. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1754. id linefeed_id = 13;
  1755. id special_prefix_id = 32007;
  1756. id special_middle_id = 32009;
  1757. id special_suffix_id = 32008;
  1758. id special_eot_id = 32010;
  1759. bool add_space_prefix = true;
  1760. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1761. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1762. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1763. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1764. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1765. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1766. if (it == bpe_ranks.end()) {
  1767. return -1;
  1768. }
  1769. return it->second;
  1770. }
  1771. };
  1772. struct llama_model {
  1773. e_model type = MODEL_UNKNOWN;
  1774. llm_arch arch = LLM_ARCH_UNKNOWN;
  1775. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1776. std::string name = "n/a";
  1777. llama_hparams hparams = {};
  1778. llama_vocab vocab;
  1779. struct ggml_tensor * tok_embd;
  1780. struct ggml_tensor * type_embd;
  1781. struct ggml_tensor * pos_embd;
  1782. struct ggml_tensor * tok_norm;
  1783. struct ggml_tensor * tok_norm_b;
  1784. struct ggml_tensor * output_norm;
  1785. struct ggml_tensor * output_norm_b;
  1786. struct ggml_tensor * output;
  1787. struct ggml_tensor * output_b;
  1788. std::vector<llama_layer> layers;
  1789. llama_split_mode split_mode;
  1790. int main_gpu;
  1791. int n_gpu_layers;
  1792. // gguf metadata
  1793. std::unordered_map<std::string, std::string> gguf_kv;
  1794. // layer -> buffer type mapping
  1795. struct layer_buft {
  1796. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1797. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1798. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1799. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1800. ggml_backend_buffer_type_t buft; // everything else
  1801. };
  1802. layer_buft buft_input;
  1803. layer_buft buft_output;
  1804. std::vector<layer_buft> buft_layer;
  1805. // contexts where the model tensors metadata is stored
  1806. std::vector<struct ggml_context *> ctxs;
  1807. // the model memory buffers for the tensor data
  1808. std::vector<ggml_backend_buffer_t> bufs;
  1809. // model memory mapped files
  1810. llama_mmaps mappings;
  1811. // objects representing data potentially being locked in memory
  1812. llama_mlocks mlock_bufs;
  1813. llama_mlocks mlock_mmaps;
  1814. // for quantize-stats only
  1815. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1816. int64_t t_load_us = 0;
  1817. int64_t t_start_us = 0;
  1818. ~llama_model() {
  1819. for (struct ggml_context * ctx : ctxs) {
  1820. ggml_free(ctx);
  1821. }
  1822. for (ggml_backend_buffer_t buf : bufs) {
  1823. #ifdef GGML_USE_CUBLAS
  1824. if (ggml_backend_buffer_get_type(buf) == ggml_backend_cpu_buffer_type()) {
  1825. ggml_backend_cuda_unregister_host_buffer(ggml_backend_buffer_get_base(buf));
  1826. }
  1827. #endif
  1828. ggml_backend_buffer_free(buf);
  1829. }
  1830. }
  1831. };
  1832. struct llama_context {
  1833. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1834. ~llama_context() {
  1835. ggml_backend_sched_free(sched);
  1836. for (ggml_backend_t backend : backends) {
  1837. ggml_backend_free(backend);
  1838. }
  1839. #ifdef GGML_USE_VULKAN
  1840. ggml_vk_free_cpu_assist();
  1841. #endif
  1842. ggml_backend_buffer_free(buf_output);
  1843. }
  1844. llama_cparams cparams;
  1845. std::vector<ggml_backend_t> backends;
  1846. #ifdef GGML_USE_METAL
  1847. ggml_backend_t backend_metal = nullptr;
  1848. #endif
  1849. ggml_backend_t backend_cpu = nullptr;
  1850. const llama_model & model;
  1851. // key + value cache for the self attention
  1852. struct llama_kv_cache kv_self;
  1853. std::mt19937 rng;
  1854. bool has_evaluated_once = false;
  1855. int64_t t_start_us;
  1856. int64_t t_load_us;
  1857. int64_t t_sample_us = 0;
  1858. int64_t t_p_eval_us = 0;
  1859. int64_t t_eval_us = 0;
  1860. int64_t t_compute_start_us = 0;
  1861. int64_t n_queued_tokens = 0;
  1862. int32_t n_sample = 0; // number of tokens sampled
  1863. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1864. int32_t n_eval = 0; // number of eval calls
  1865. // host buffer for the model output (logits and embeddings)
  1866. ggml_backend_buffer_t buf_output = nullptr;
  1867. // decode output (2-dimensional array: [n_tokens][n_vocab])
  1868. size_t logits_size = 0;
  1869. float * logits = nullptr;
  1870. #ifndef NDEBUG
  1871. // guard against access to unset logits
  1872. std::vector<bool> logits_valid;
  1873. #endif
  1874. bool logits_all = false;
  1875. // embeddings output (2-dimensional array: [n_tokens][n_embd])
  1876. // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE
  1877. size_t embd_size = 0;
  1878. float * embd = nullptr;
  1879. // sequence embeddings output (map of [n_embd] vectors)
  1880. // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE
  1881. std::map<llama_seq_id, std::vector<float>> embd_seq;
  1882. // memory buffers used to evaluate the model
  1883. std::vector<uint8_t> buf_compute_meta;
  1884. ggml_backend_sched_t sched = nullptr;
  1885. ggml_abort_callback abort_callback = nullptr;
  1886. void * abort_callback_data = nullptr;
  1887. // input tensors
  1888. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  1889. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  1890. struct ggml_tensor * inp_pos; // I32 [n_batch]
  1891. struct ggml_tensor * inp_KQ_mask; // F32 [kv_size, n_batch]
  1892. struct ggml_tensor * inp_KQ_pos; // F32 [kv_size]
  1893. struct ggml_tensor * inp_K_shift; // I32 [kv_size]
  1894. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  1895. struct ggml_tensor * inp_cls; // I32 [n_batch]
  1896. struct ggml_tensor * inp_s_copy; // I32 [kv_size]
  1897. struct ggml_tensor * inp_s_mask; // F32 [1, kv_size]
  1898. struct ggml_tensor * inp_s_seq; // I32 [kv_size, n_batch]
  1899. // control vectors
  1900. struct llama_control_vector cvec;
  1901. #ifdef GGML_USE_MPI
  1902. ggml_mpi_context * ctx_mpi = NULL;
  1903. #endif
  1904. };
  1905. //
  1906. // kv cache helpers
  1907. //
  1908. static bool llama_kv_cache_init(
  1909. struct llama_kv_cache & cache,
  1910. const llama_model & model,
  1911. ggml_type type_k,
  1912. ggml_type type_v,
  1913. uint32_t kv_size,
  1914. bool offload) {
  1915. const struct llama_hparams & hparams = model.hparams;
  1916. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  1917. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  1918. const int64_t n_layer = hparams.n_layer;
  1919. cache.has_shift = false;
  1920. // TODO: find a nicer way to add other recurrent model architectures
  1921. cache.recurrent = model.arch == LLM_ARCH_MAMBA;
  1922. // TODO: support mixed reccurent Transformer architectues
  1923. // NOTE: (!a || b) is a logical implication (a -> b)
  1924. GGML_ASSERT(!cache.recurrent || n_embd_k_gqa == hparams.n_embd_k_s());
  1925. GGML_ASSERT(!cache.recurrent || n_embd_v_gqa == hparams.n_embd_v_s());
  1926. GGML_ASSERT( cache.recurrent || n_embd_k_gqa == hparams.n_embd_k_gqa());
  1927. GGML_ASSERT( cache.recurrent || n_embd_v_gqa == hparams.n_embd_v_gqa());
  1928. cache.head = 0;
  1929. cache.size = kv_size;
  1930. cache.used = 0;
  1931. cache.type_k = type_k;
  1932. cache.type_v = type_v;
  1933. cache.cells.clear();
  1934. cache.cells.resize(kv_size);
  1935. if (cache.recurrent) {
  1936. // init state copy sources
  1937. for (uint32_t i = 0; i < cache.size; ++i) {
  1938. cache.cells[i].src = i;
  1939. }
  1940. }
  1941. #ifdef GGML_USE_CLBLAST
  1942. offload = false;
  1943. #endif
  1944. // count used buffer types
  1945. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  1946. if (offload) {
  1947. for (int64_t i = 0; i < n_layer; ++i) {
  1948. buft_layer_count[model.buft_layer[i].buft]++;
  1949. }
  1950. } else {
  1951. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  1952. }
  1953. // create a context for each buffer type
  1954. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  1955. for (auto & it : buft_layer_count) {
  1956. int n_layers = it.second;
  1957. struct ggml_init_params params = {
  1958. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  1959. /*.mem_buffer =*/ NULL,
  1960. /*.no_alloc =*/ true,
  1961. };
  1962. ggml_context * ctx = ggml_init(params);
  1963. if (!ctx) {
  1964. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  1965. return false;
  1966. }
  1967. ctx_map[it.first] = ctx;
  1968. cache.ctxs.push_back(ctx);
  1969. }
  1970. cache.k_l.reserve(n_layer);
  1971. cache.v_l.reserve(n_layer);
  1972. for (int i = 0; i < (int) n_layer; i++) {
  1973. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  1974. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  1975. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*kv_size);
  1976. ggml_format_name(k, "cache_k_l%d", i);
  1977. ggml_format_name(v, "cache_v_l%d", i);
  1978. cache.k_l.push_back(k);
  1979. cache.v_l.push_back(v);
  1980. }
  1981. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  1982. for (auto it : ctx_map) {
  1983. ggml_backend_buffer_type_t buft = it.first;
  1984. ggml_context * ctx = it.second;
  1985. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  1986. if (!buf) {
  1987. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  1988. return false;
  1989. }
  1990. ggml_backend_buffer_clear(buf, 0);
  1991. LLAMA_LOG_INFO("%s: %10s KV buffer size = %8.2f MiB\n", __func__, ggml_backend_buffer_name(buf), ggml_backend_buffer_get_size(buf)/1024.0/1024.0);
  1992. cache.bufs.push_back(buf);
  1993. }
  1994. return true;
  1995. }
  1996. // find an empty slot of size "n_tokens" in the cache
  1997. // updates the cache head
  1998. // Note: On success, it's important that cache.head points
  1999. // to the first cell of the slot.
  2000. static bool llama_kv_cache_find_slot(
  2001. struct llama_kv_cache & cache,
  2002. const struct llama_batch & batch) {
  2003. const uint32_t n_ctx = cache.size;
  2004. const uint32_t n_tokens = batch.n_tokens;
  2005. if (cache.recurrent) {
  2006. // For recurrent state architectures (like Mamba),
  2007. // each KV cache cell can store the state for a whole sequence.
  2008. llama_seq_id min = cache.size - 1;
  2009. llama_seq_id max = 0;
  2010. for (uint32_t i = 0; i < n_tokens; ++i) {
  2011. for (int32_t j = 0; j < batch.n_seq_id[i]; ++j) {
  2012. llama_seq_id seq_id = batch.seq_id[i][j];
  2013. // make sure it's a valid seq_id
  2014. if ((uint32_t) seq_id < cache.size) {
  2015. if (seq_id > max) {
  2016. max = seq_id;
  2017. }
  2018. if (seq_id < min) {
  2019. min = seq_id;
  2020. }
  2021. // Assuming the tokens are in-order
  2022. if (batch.pos[i] != cache.cells[seq_id].pos + 1) {
  2023. // What should happen when the pos backtracks or skips a value?
  2024. // Clearing the state mid-batch would require special-casing which isn't done.
  2025. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d\n",
  2026. __func__, batch.pos[i], cache.cells[seq_id].pos, seq_id);
  2027. }
  2028. if (cache.cells[seq_id].pos < 0 && 0 <= batch.pos[i]) {
  2029. cache.used += 1;
  2030. }
  2031. cache.cells[seq_id].pos = batch.pos[i];
  2032. // NOTE: seq_ids are not inserted here; they are handled when the input tensors are set
  2033. } else {
  2034. // too big seq_id
  2035. // TODO: would it be possible to resize the KV cache size instead?
  2036. LLAMA_LOG_ERROR("%s: seq_id=%d >= kv_size=%d Try using a bigger --parallel value\n", __func__, seq_id, cache.size);
  2037. return false;
  2038. }
  2039. }
  2040. }
  2041. // allow getting the range of used cells, from head to head + n
  2042. cache.head = min;
  2043. cache.n = max - min + 1;
  2044. // sanity check
  2045. return max >= min;
  2046. }
  2047. // otherwise, one cell per token.
  2048. if (n_tokens > n_ctx) {
  2049. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  2050. return false;
  2051. }
  2052. uint32_t n_tested = 0;
  2053. while (true) {
  2054. if (cache.head + n_tokens > n_ctx) {
  2055. n_tested += n_ctx - cache.head;
  2056. cache.head = 0;
  2057. continue;
  2058. }
  2059. bool found = true;
  2060. for (uint32_t i = 0; i < n_tokens; i++) {
  2061. if (cache.cells[cache.head + i].pos >= 0) {
  2062. found = false;
  2063. cache.head += i + 1;
  2064. n_tested += i + 1;
  2065. break;
  2066. }
  2067. }
  2068. if (found) {
  2069. break;
  2070. }
  2071. if (n_tested >= n_ctx) {
  2072. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  2073. return false;
  2074. }
  2075. }
  2076. for (uint32_t i = 0; i < n_tokens; i++) {
  2077. cache.cells[cache.head + i].pos = batch.pos[i];
  2078. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  2079. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  2080. }
  2081. }
  2082. cache.used += n_tokens;
  2083. return true;
  2084. }
  2085. // find how many cells are currently in use
  2086. static uint32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  2087. for (uint32_t i = cache.size; i > 0; --i) {
  2088. const llama_kv_cell & cell = cache.cells[i - 1];
  2089. if (cell.pos >= 0 && !cell.is_empty()) {
  2090. return i;
  2091. }
  2092. }
  2093. return 0;
  2094. }
  2095. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  2096. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  2097. cache.cells[i].pos = -1;
  2098. cache.cells[i].seq_id.clear();
  2099. }
  2100. cache.head = 0;
  2101. cache.used = 0;
  2102. }
  2103. static bool llama_kv_cache_seq_rm(
  2104. struct llama_kv_cache & cache,
  2105. llama_seq_id seq_id,
  2106. llama_pos p0,
  2107. llama_pos p1) {
  2108. uint32_t new_head = cache.size;
  2109. if (p0 < 0) p0 = 0;
  2110. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2111. // models like Mamba can't have a state partially erased
  2112. if (cache.recurrent) {
  2113. if (seq_id >= (int64_t) cache.size) {
  2114. // could be fatal
  2115. return false;
  2116. }
  2117. if (0 <= seq_id) {
  2118. // partial intersection is invalid
  2119. if ((0 < p0 && p0 <= cache.cells[seq_id].pos) || (0 < p1 && p1 <= cache.cells[seq_id].pos)) {
  2120. return false;
  2121. }
  2122. } else {
  2123. // seq_id is negative, then the range should include everything or nothing
  2124. if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
  2125. return false;
  2126. }
  2127. }
  2128. }
  2129. for (uint32_t i = 0; i < cache.size; ++i) {
  2130. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2131. if (seq_id < 0) {
  2132. cache.cells[i].seq_id.clear();
  2133. } else if (cache.cells[i].has_seq_id(seq_id)) {
  2134. cache.cells[i].seq_id.erase(seq_id);
  2135. } else {
  2136. continue;
  2137. }
  2138. if (cache.cells[i].is_empty()) {
  2139. // keep count of the number of used cells
  2140. if (cache.cells[i].pos >= 0) cache.used--;
  2141. cache.cells[i].pos = -1;
  2142. if (new_head == cache.size) new_head = i;
  2143. }
  2144. }
  2145. }
  2146. // If we freed up a slot, set head to it so searching can start there.
  2147. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2148. return true;
  2149. }
  2150. static void llama_kv_cache_seq_cp(
  2151. struct llama_kv_cache & cache,
  2152. llama_seq_id seq_id_src,
  2153. llama_seq_id seq_id_dst,
  2154. llama_pos p0,
  2155. llama_pos p1) {
  2156. if (p0 < 0) p0 = 0;
  2157. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2158. if (cache.recurrent) {
  2159. if ((uint32_t) seq_id_dst < cache.size && (uint32_t) seq_id_src < cache.size) {
  2160. seq_id_src = cache.cells[seq_id_src].src;
  2161. GGML_ASSERT((uint32_t) seq_id_src < cache.size);
  2162. // intent to "copy from"
  2163. // supports copy chains thanks to taking the source of the source
  2164. cache.cells[seq_id_dst].src = seq_id_src;
  2165. // preserve the "keep or clear" status of the copied sequence
  2166. if (cache.cells[seq_id_src].has_seq_id(seq_id_src)) {
  2167. cache.cells[seq_id_dst].seq_id.insert(seq_id_dst);
  2168. } else {
  2169. cache.cells[seq_id_dst].seq_id.erase(seq_id_dst);
  2170. }
  2171. cache.do_copy = true;
  2172. cache.cells[seq_id_dst].pos = cache.cells[seq_id_src].pos;
  2173. }
  2174. return;
  2175. }
  2176. // otherwise, this is the KV cache of a Transformer-like model
  2177. cache.head = 0;
  2178. for (uint32_t i = 0; i < cache.size; ++i) {
  2179. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2180. cache.cells[i].seq_id.insert(seq_id_dst);
  2181. }
  2182. }
  2183. }
  2184. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2185. uint32_t new_head = cache.size;
  2186. for (uint32_t i = 0; i < cache.size; ++i) {
  2187. if (!cache.cells[i].has_seq_id(seq_id)) {
  2188. if (cache.cells[i].pos >= 0) cache.used--;
  2189. cache.cells[i].pos = -1;
  2190. cache.cells[i].seq_id.clear();
  2191. if (new_head == cache.size) new_head = i;
  2192. } else {
  2193. cache.cells[i].seq_id.clear();
  2194. cache.cells[i].seq_id.insert(seq_id);
  2195. }
  2196. }
  2197. // If we freed up a slot, set head to it so searching can start there.
  2198. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2199. }
  2200. static void llama_kv_cache_seq_add(
  2201. struct llama_kv_cache & cache,
  2202. llama_seq_id seq_id,
  2203. llama_pos p0,
  2204. llama_pos p1,
  2205. llama_pos delta) {
  2206. uint32_t new_head = cache.size;
  2207. if (p0 < 0) p0 = 0;
  2208. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2209. if (cache.recurrent) {
  2210. // for Mamba-like models, only the pos needs to be shifted
  2211. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2212. llama_kv_cell & cell = cache.cells[seq_id];
  2213. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2214. cell.pos += delta;
  2215. }
  2216. }
  2217. return;
  2218. }
  2219. for (uint32_t i = 0; i < cache.size; ++i) {
  2220. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2221. cache.has_shift = true;
  2222. cache.cells[i].pos += delta;
  2223. cache.cells[i].delta += delta;
  2224. if (cache.cells[i].pos < 0) {
  2225. if (!cache.cells[i].is_empty()) {
  2226. cache.used--;
  2227. }
  2228. cache.cells[i].pos = -1;
  2229. cache.cells[i].seq_id.clear();
  2230. if (new_head == cache.size) {
  2231. new_head = i;
  2232. }
  2233. }
  2234. }
  2235. }
  2236. // If we freed up a slot, set head to it so searching can start there.
  2237. // Otherwise we just start the next search from the beginning.
  2238. cache.head = new_head != cache.size ? new_head : 0;
  2239. }
  2240. static void llama_kv_cache_seq_div(
  2241. struct llama_kv_cache & cache,
  2242. llama_seq_id seq_id,
  2243. llama_pos p0,
  2244. llama_pos p1,
  2245. int d) {
  2246. if (p0 < 0) p0 = 0;
  2247. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2248. if (cache.recurrent) {
  2249. // for Mamba-like models, only the pos needs to be changed
  2250. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2251. llama_kv_cell & cell = cache.cells[seq_id];
  2252. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2253. cell.pos /= d;
  2254. }
  2255. }
  2256. return;
  2257. }
  2258. for (uint32_t i = 0; i < cache.size; ++i) {
  2259. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2260. cache.has_shift = true;
  2261. {
  2262. llama_pos p_old = cache.cells[i].pos;
  2263. cache.cells[i].pos /= d;
  2264. cache.cells[i].delta += cache.cells[i].pos - p_old;
  2265. }
  2266. }
  2267. }
  2268. }
  2269. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2270. llama_pos result = 0;
  2271. for (uint32_t i = 0; i < cache.size; ++i) {
  2272. if (cache.cells[i].has_seq_id(seq_id)) {
  2273. result = std::max(result, cache.cells[i].pos);
  2274. }
  2275. }
  2276. return result;
  2277. }
  2278. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  2279. cache.do_defrag = true;
  2280. }
  2281. //
  2282. // model loading and saving
  2283. //
  2284. enum llama_fver {
  2285. GGUF_FILE_VERSION_V1 = 1,
  2286. GGUF_FILE_VERSION_V2 = 2,
  2287. GGUF_FILE_VERSION_V3 = 3,
  2288. };
  2289. static const char * llama_file_version_name(llama_fver version) {
  2290. switch (version) {
  2291. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  2292. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  2293. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  2294. }
  2295. return "unknown";
  2296. }
  2297. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  2298. char buf[256];
  2299. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  2300. for (size_t i = 1; i < ne.size(); i++) {
  2301. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  2302. }
  2303. return buf;
  2304. }
  2305. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  2306. char buf[256];
  2307. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  2308. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  2309. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  2310. }
  2311. return buf;
  2312. }
  2313. namespace GGUFMeta {
  2314. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  2315. struct GKV_Base_Type {
  2316. static constexpr gguf_type gt = gt_;
  2317. static T getter(const gguf_context * ctx, const int kid) {
  2318. return gfun(ctx, kid);
  2319. }
  2320. };
  2321. template<typename T> struct GKV_Base;
  2322. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  2323. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  2324. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  2325. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  2326. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  2327. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  2328. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  2329. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  2330. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  2331. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  2332. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  2333. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  2334. template<> struct GKV_Base<std::string> {
  2335. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  2336. static std::string getter(const gguf_context * ctx, const int kid) {
  2337. return gguf_get_val_str(ctx, kid);
  2338. }
  2339. };
  2340. struct ArrayInfo {
  2341. const gguf_type gt;
  2342. const size_t length;
  2343. const void * data;
  2344. };
  2345. template<> struct GKV_Base<ArrayInfo> {
  2346. public:
  2347. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  2348. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  2349. return ArrayInfo {
  2350. gguf_get_arr_type(ctx, k),
  2351. size_t(gguf_get_arr_n(ctx, k)),
  2352. gguf_get_arr_data(ctx, k),
  2353. };
  2354. }
  2355. };
  2356. template<typename T>
  2357. class GKV : public GKV_Base<T> {
  2358. GKV() = delete;
  2359. public:
  2360. static T get_kv(const gguf_context * ctx, const int k) {
  2361. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  2362. if (kt != GKV::gt) {
  2363. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  2364. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  2365. }
  2366. return GKV::getter(ctx, k);
  2367. }
  2368. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  2369. switch (ty) {
  2370. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  2371. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  2372. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  2373. }
  2374. return "unknown";
  2375. }
  2376. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  2377. if (!ovrd) { return false; }
  2378. if (ovrd->tag == expected_type) {
  2379. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  2380. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  2381. switch (ovrd->tag) {
  2382. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  2383. LLAMA_LOG_INFO("%s\n", ovrd->bool_value ? "true" : "false");
  2384. } break;
  2385. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  2386. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->int_value);
  2387. } break;
  2388. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  2389. LLAMA_LOG_INFO("%.6f\n", ovrd->float_value);
  2390. } break;
  2391. default:
  2392. // Shouldn't be possible to end up here, but just in case...
  2393. throw std::runtime_error(
  2394. format("Unsupported attempt to override %s type for metadata key %s\n",
  2395. override_type_to_str(ovrd->tag), ovrd->key));
  2396. }
  2397. return true;
  2398. }
  2399. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  2400. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  2401. return false;
  2402. }
  2403. template<typename OT>
  2404. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  2405. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2406. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  2407. target = ovrd->bool_value;
  2408. return true;
  2409. }
  2410. return false;
  2411. }
  2412. template<typename OT>
  2413. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  2414. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2415. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  2416. target = ovrd->int_value;
  2417. return true;
  2418. }
  2419. return false;
  2420. }
  2421. template<typename OT>
  2422. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  2423. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2424. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  2425. target = ovrd->float_value;
  2426. return true;
  2427. }
  2428. return false;
  2429. }
  2430. template<typename OT>
  2431. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  2432. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2433. (void)target;
  2434. (void)ovrd;
  2435. if (!ovrd) { return false; }
  2436. // Currently, we should never end up here so it would be a bug if we do.
  2437. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  2438. ovrd ? ovrd->key : "NULL"));
  2439. }
  2440. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2441. if (try_override<T>(target, ovrd)) {
  2442. return true;
  2443. }
  2444. if (k < 0) { return false; }
  2445. target = get_kv(ctx, k);
  2446. return true;
  2447. }
  2448. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2449. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  2450. }
  2451. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2452. return set(ctx, key.c_str(), target, ovrd);
  2453. }
  2454. };
  2455. }
  2456. using llama_buf_map = std::unordered_map<uint32_t, ggml_backend_buffer_t>;
  2457. struct llama_model_loader {
  2458. int n_kv = 0;
  2459. int n_tensors = 0;
  2460. int n_created = 0;
  2461. int64_t n_elements = 0;
  2462. size_t n_bytes = 0;
  2463. bool use_mmap = false;
  2464. llama_files files;
  2465. llama_ftype ftype;
  2466. llama_fver fver;
  2467. llama_mmaps mappings;
  2468. // Holds information on a model weights
  2469. struct llama_tensor_weights {
  2470. uint16_t idx; // source file index
  2471. size_t offs; // tensor data offset in the original file
  2472. ggml_tensor * tensor;
  2473. llama_tensor_weights(uint16_t idx, const char * name, const struct gguf_context * gguf_ctx, ggml_tensor * tensor) : idx(idx), tensor(tensor) {
  2474. const int tensor_idx = gguf_find_tensor(gguf_ctx, name);
  2475. offs = gguf_get_data_offset(gguf_ctx) + gguf_get_tensor_offset(gguf_ctx, tensor_idx);
  2476. }
  2477. };
  2478. std::vector<llama_tensor_weights> weights;
  2479. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  2480. struct gguf_context * meta = NULL;
  2481. std::vector<ggml_context *> contexts;
  2482. std::string arch_name;
  2483. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  2484. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) {
  2485. int trace = 0;
  2486. if (getenv("LLAMA_TRACE")) {
  2487. trace = atoi(getenv("LLAMA_TRACE"));
  2488. }
  2489. if (param_overrides_p != nullptr) {
  2490. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  2491. kv_overrides.insert({std::string(p->key), *p});
  2492. }
  2493. }
  2494. struct ggml_context * ctx = NULL;
  2495. struct gguf_init_params params = {
  2496. /*.no_alloc = */ true,
  2497. /*.ctx = */ &ctx,
  2498. };
  2499. meta = gguf_init_from_file(fname.c_str(), params);
  2500. if (!meta) {
  2501. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  2502. }
  2503. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  2504. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  2505. // Save tensors data offset of the main file.
  2506. // For subsidiary files, `meta` tensor data offset must not be used,
  2507. // so we build a unified tensors index for weights.
  2508. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  2509. weights.emplace_back(llama_tensor_weights(0, cur->name, meta, cur));
  2510. }
  2511. files.emplace_back(new llama_file(fname.c_str(), "rb"));
  2512. contexts.emplace_back(ctx);
  2513. uint16_t n_split = 0;
  2514. get_key(llm_kv(LLM_KV_SPLIT_COUNT), n_split, false);
  2515. // Load additional GGML contexts
  2516. if (n_split > 1) {
  2517. uint16_t idx = 0;
  2518. get_key(llm_kv(LLM_KV_SPLIT_NO), idx);
  2519. if (idx != 0) {
  2520. throw std::runtime_error(format("illegal split file: %d, model must be loaded with the first split", idx));
  2521. }
  2522. char split_prefix[PATH_MAX] = {0};
  2523. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), fname.c_str(), idx, n_split)) {
  2524. throw std::runtime_error(format("invalid split file: %s", fname.c_str()));
  2525. }
  2526. if (trace > 0) {
  2527. LLAMA_LOG_INFO("%s: loading additional %d GGUFs\n", __func__, n_split);
  2528. }
  2529. char split_path[PATH_MAX] = {0};
  2530. for (idx = 1; idx < n_split; idx++) {
  2531. llama_split_path(split_path, sizeof(split_path), split_prefix, idx, n_split);
  2532. struct gguf_init_params split_params = {
  2533. /*.no_alloc = */ true,
  2534. /*.ctx = */ &ctx,
  2535. };
  2536. struct gguf_context * ctx_gguf = gguf_init_from_file(split_path, split_params);
  2537. if (!ctx_gguf) {
  2538. throw std::runtime_error(format("%s: failed to load GGUF split from %s\n", __func__, split_path));
  2539. }
  2540. // Save tensors data offset info of the shard.
  2541. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  2542. weights.emplace_back(llama_tensor_weights(idx, cur->name, ctx_gguf, cur));
  2543. }
  2544. files.emplace_back(new llama_file(split_path, "rb"));
  2545. contexts.emplace_back(ctx);
  2546. gguf_free(ctx_gguf);
  2547. }
  2548. get_key(llm_kv(LLM_KV_SPLIT_TENSORS_COUNT), n_tensors);
  2549. // sanity check
  2550. {
  2551. const int n_tensors_loaded = (int) weights.size();
  2552. if (n_tensors != n_tensors_loaded) {
  2553. throw std::runtime_error(format("corrupted model: %d tensors expected but %d found", n_tensors, n_tensors_loaded));
  2554. }
  2555. }
  2556. LLAMA_LOG_INFO("%s: additional %d GGUFs metadata loaded.\n", __func__, n_split);
  2557. }
  2558. n_kv = gguf_get_n_kv(meta);
  2559. n_tensors = weights.size();
  2560. fver = (enum llama_fver) gguf_get_version(meta);
  2561. for (auto & w : weights) {
  2562. n_elements += ggml_nelements(w.tensor);
  2563. n_bytes += ggml_nbytes(w.tensor);
  2564. }
  2565. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  2566. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  2567. // determine file type based on the number of tensors for each quantization and print meta data
  2568. // TODO: make optional
  2569. {
  2570. std::map<enum ggml_type, uint32_t> n_type;
  2571. uint32_t n_type_max = 0;
  2572. enum ggml_type type_max = GGML_TYPE_F32;
  2573. for (int i = 0; i < n_tensors; i++) {
  2574. const ggml_tensor * tensor = weights.at(i).tensor;
  2575. enum ggml_type type = tensor->type;
  2576. n_type[type]++;
  2577. if (n_type_max < n_type[type]) {
  2578. n_type_max = n_type[type];
  2579. type_max = type;
  2580. }
  2581. if (trace > 0) {
  2582. const uint16_t sid = weights.at(i).idx;
  2583. LLAMA_LOG_INFO("%s: - tensor %4d, split %2d: %32s %-8s [ %s ]\n", __func__, i, sid, ggml_get_name(tensor), ggml_type_name(type), llama_format_tensor_shape(tensor).c_str());
  2584. }
  2585. }
  2586. switch (type_max) {
  2587. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  2588. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  2589. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  2590. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  2591. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  2592. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  2593. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  2594. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  2595. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  2596. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  2597. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  2598. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  2599. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  2600. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  2601. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  2602. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  2603. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  2604. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  2605. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  2606. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  2607. default:
  2608. {
  2609. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  2610. ftype = LLAMA_FTYPE_ALL_F32;
  2611. } break;
  2612. }
  2613. // this is a way to mark that we have "guessed" the file type
  2614. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  2615. {
  2616. const int kid = gguf_find_key(meta, "general.file_type");
  2617. if (kid >= 0) {
  2618. ftype = (llama_ftype) gguf_get_val_u32(meta, kid);
  2619. }
  2620. }
  2621. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2622. for (int i = 0; i < n_kv; i++) {
  2623. const char * name = gguf_get_key(meta, i);
  2624. const enum gguf_type type = gguf_get_kv_type(meta, i);
  2625. const std::string type_name =
  2626. type == GGUF_TYPE_ARRAY
  2627. ? format("%s[%s,%d]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(meta, i)), gguf_get_arr_n(meta, i))
  2628. : gguf_type_name(type);
  2629. std::string value = gguf_kv_to_str(meta, i);
  2630. const size_t MAX_VALUE_LEN = 40;
  2631. if (value.size() > MAX_VALUE_LEN) {
  2632. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2633. }
  2634. replace_all(value, "\n", "\\n");
  2635. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2636. }
  2637. // print type counts
  2638. for (auto & kv : n_type) {
  2639. if (kv.second == 0) {
  2640. continue;
  2641. }
  2642. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2643. }
  2644. }
  2645. if (!llama_mmap::SUPPORTED) {
  2646. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2647. use_mmap = false;
  2648. }
  2649. this->use_mmap = use_mmap;
  2650. }
  2651. ~llama_model_loader() {
  2652. if (meta) {
  2653. gguf_free(meta);
  2654. }
  2655. for (auto * ctx : contexts) {
  2656. ggml_free(ctx);
  2657. }
  2658. }
  2659. template<typename T>
  2660. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2661. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2662. const int kid = gguf_find_key(meta, key.c_str());
  2663. if (kid < 0) {
  2664. if (required) {
  2665. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2666. }
  2667. return false;
  2668. }
  2669. struct GGUFMeta::ArrayInfo arr_info =
  2670. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  2671. result = arr_info.length;
  2672. return true;
  2673. }
  2674. template<typename T>
  2675. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2676. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2677. return get_arr_n(llm_kv(kid), result, required);
  2678. }
  2679. template<typename T>
  2680. bool get_key(const std::string & key, T & result, const bool required = true) {
  2681. auto it = kv_overrides.find(key);
  2682. const struct llama_model_kv_override * override =
  2683. it != kv_overrides.end() ? &it->second : nullptr;
  2684. const bool found = GGUFMeta::GKV<T>::set(meta, key, result, override);
  2685. if (required && !found) {
  2686. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2687. }
  2688. return found;
  2689. }
  2690. template<typename T>
  2691. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2692. return get_key(llm_kv(kid), result, required);
  2693. }
  2694. std::string get_arch_name() const {
  2695. return arch_name;
  2696. }
  2697. enum llm_arch get_arch() const {
  2698. return llm_kv.arch;
  2699. }
  2700. const char * get_tensor_name(int i) const {
  2701. return weights.at(i).tensor->name;
  2702. }
  2703. const llama_tensor_weights & get_weights(const char * name) const {
  2704. for (const auto & weight : weights) {
  2705. if (strcmp(name, weight.tensor->name) == 0) {
  2706. return weight;
  2707. }
  2708. }
  2709. throw std::runtime_error(format("tensor %s not found", name));
  2710. }
  2711. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2712. try {
  2713. return get_weights(name).tensor;
  2714. } catch (const std::runtime_error & e) {
  2715. return NULL;
  2716. }
  2717. }
  2718. struct ggml_tensor * get_tensor_meta(int i) const {
  2719. return get_tensor_meta(get_tensor_name(i));
  2720. }
  2721. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, const struct ggml_tensor * cur) {
  2722. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, cur);
  2723. ggml_set_name(tensor, ggml_get_name(cur));
  2724. n_created++;
  2725. return tensor;
  2726. }
  2727. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  2728. const struct ggml_tensor * cur = get_tensor_meta(name.c_str());
  2729. if (cur == NULL) {
  2730. if (!required) {
  2731. return NULL;
  2732. }
  2733. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2734. }
  2735. {
  2736. bool is_ok = true;
  2737. for (size_t i = 0; i < ne.size(); ++i) {
  2738. if (ne[i] != cur->ne[i]) {
  2739. is_ok = false;
  2740. break;
  2741. }
  2742. }
  2743. if (!is_ok) {
  2744. throw std::runtime_error(
  2745. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2746. __func__, name.c_str(),
  2747. llama_format_tensor_shape(ne).c_str(),
  2748. llama_format_tensor_shape(cur).c_str()));
  2749. }
  2750. }
  2751. return create_tensor_for(ctx, cur);
  2752. }
  2753. void done_getting_tensors() const {
  2754. if (n_created != n_tensors) {
  2755. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  2756. }
  2757. }
  2758. void init_mappings(bool prefetch = true, llama_mlocks * mlock_mmaps = nullptr) {
  2759. if (use_mmap) {
  2760. mappings.reserve(files.size());
  2761. mmaps_used.reserve(files.size());
  2762. for (const auto & file : files) {
  2763. std::unique_ptr<llama_mmap> mapping(new llama_mmap(file.get(), prefetch ? -1 : 0, ggml_is_numa()));
  2764. mmaps_used.emplace_back(std::make_pair(mapping->size, 0));
  2765. if (mlock_mmaps) {
  2766. std::unique_ptr<llama_mlock> mlock_mmap(new llama_mlock());
  2767. mlock_mmap->init(mapping->addr);
  2768. mlock_mmaps->emplace_back(std::move(mlock_mmap));
  2769. }
  2770. mappings.emplace_back(std::move(mapping));
  2771. }
  2772. }
  2773. // compute the total size of all tensors for progress reporting
  2774. for (auto & w : weights) {
  2775. size_data += ggml_nbytes(w.tensor);
  2776. }
  2777. }
  2778. void get_mapping_range(size_t * first, size_t * last, void ** addr, int idx, ggml_context * ctx) const {
  2779. GGML_ASSERT(!mappings.empty());
  2780. const auto & mapping = mappings.at(idx);
  2781. *first = mapping->size;
  2782. *last = 0;
  2783. *addr = mapping->addr;
  2784. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  2785. const auto & w = get_weights(ggml_get_name(tensor));
  2786. if (w.idx != idx) {
  2787. continue;
  2788. }
  2789. *first = std::min(*first, w.offs);
  2790. *last = std::max(*last, w.offs + ggml_nbytes(tensor));
  2791. }
  2792. }
  2793. // for backwards compatibility, does not support ggml-backend
  2794. void load_data_for(struct ggml_tensor * cur) const {
  2795. const auto & w = get_weights(ggml_get_name(cur));
  2796. if (use_mmap) {
  2797. const auto & mapping = mappings.at(w.idx);
  2798. if (cur->data == nullptr) {
  2799. cur->data = (uint8_t *)mapping->addr + w.offs;
  2800. } else {
  2801. memcpy(cur->data, (uint8_t *)mapping->addr + w.offs, ggml_nbytes(cur));
  2802. }
  2803. } else {
  2804. GGML_ASSERT(cur->data != nullptr);
  2805. GGML_ASSERT(w.idx < files.size());
  2806. const auto & file = files.at(w.idx);
  2807. file->seek(w.offs, SEEK_SET);
  2808. file->read_raw(cur->data, ggml_nbytes(cur));
  2809. }
  2810. }
  2811. size_t size_done = 0;
  2812. size_t size_data = 0;
  2813. std::vector<std::pair<size_t, size_t>> mmaps_used;
  2814. // Returns false if cancelled by progress_callback
  2815. bool load_all_data(
  2816. struct ggml_context * ctx,
  2817. llama_buf_map & bufs_mmap,
  2818. llama_mlocks * lmlocks,
  2819. llama_progress_callback progress_callback,
  2820. void * progress_callback_user_data) {
  2821. GGML_ASSERT(size_data != 0 && "call init_mappings() first");
  2822. std::vector<no_init<uint8_t>> read_buf;
  2823. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  2824. if (progress_callback) {
  2825. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2826. return false;
  2827. }
  2828. }
  2829. const auto & w = get_weights(ggml_get_name(cur));
  2830. size_t n_size = ggml_nbytes(cur);
  2831. if (use_mmap) {
  2832. const auto & mapping = mappings.at(w.idx);
  2833. ggml_backend_buffer_t buf_mmap = nullptr;
  2834. if (bufs_mmap.count(w.idx)) {
  2835. buf_mmap = bufs_mmap.at(w.idx);
  2836. }
  2837. GGML_ASSERT(buf_mmap || cur->data); // either we have a buffer to allocate the tensor in, or it is already allocated
  2838. if (buf_mmap && cur->data == nullptr) {
  2839. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + w.offs);
  2840. if (lmlocks) {
  2841. const auto & lmlock = lmlocks->at(w.idx);
  2842. lmlock->grow_to(w.offs + ggml_nbytes(cur));
  2843. }
  2844. auto & mmap_used = mmaps_used[w.idx];
  2845. mmap_used.first = std::min(mmap_used.first, w.offs);
  2846. mmap_used.second = std::max(mmap_used.second, w.offs + n_size);
  2847. } else {
  2848. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + w.offs, 0, n_size);
  2849. }
  2850. } else {
  2851. GGML_ASSERT(w.idx < files.size());
  2852. const auto & file = files.at(w.idx);
  2853. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2854. file->seek(w.offs, SEEK_SET);
  2855. file->read_raw(cur->data, ggml_nbytes(cur));
  2856. } else {
  2857. read_buf.resize(ggml_nbytes(cur));
  2858. file->seek(w.offs, SEEK_SET);
  2859. file->read_raw(read_buf.data(), ggml_nbytes(cur));
  2860. ggml_backend_tensor_set(cur, read_buf.data(), 0, n_size);
  2861. }
  2862. }
  2863. size_done += n_size;
  2864. }
  2865. // check if this is the last call and do final cleanup
  2866. if (size_done >= size_data) {
  2867. // unmap offloaded tensors and metadata
  2868. if (use_mmap) {
  2869. for (uint32_t idx = 0; idx < mappings.size(); idx++) {
  2870. const auto & mmap_used = mmaps_used.at(idx);
  2871. auto & mapping = mappings.at(idx);
  2872. mapping->unmap_fragment(0, mmap_used.first);
  2873. if (mmap_used.second != 0) {
  2874. mapping->unmap_fragment(mmap_used.second, mapping->size);
  2875. }
  2876. }
  2877. }
  2878. if (progress_callback) {
  2879. // Even though the model is done loading, we still honor
  2880. // cancellation since we need to free allocations.
  2881. return progress_callback(1.0f, progress_callback_user_data);
  2882. }
  2883. }
  2884. return true;
  2885. }
  2886. };
  2887. template<>
  2888. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  2889. uint32_t tmp;
  2890. const bool found = get_key(kid, tmp, required);
  2891. if (found) {
  2892. result = (enum llama_pooling_type) tmp;
  2893. } else {
  2894. result = LLAMA_POOLING_TYPE_UNSPECIFIED;
  2895. }
  2896. return found;
  2897. }
  2898. //
  2899. // load LLaMA models
  2900. //
  2901. static const char * llama_model_arch_name(llm_arch arch) {
  2902. auto it = LLM_ARCH_NAMES.find(arch);
  2903. if (it == LLM_ARCH_NAMES.end()) {
  2904. return "unknown";
  2905. }
  2906. return it->second;
  2907. }
  2908. static std::string llama_model_ftype_name(llama_ftype ftype) {
  2909. if (ftype & LLAMA_FTYPE_GUESSED) {
  2910. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  2911. }
  2912. switch (ftype) {
  2913. case LLAMA_FTYPE_ALL_F32: return "all F32";
  2914. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  2915. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  2916. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  2917. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  2918. return "Q4_1, some F16";
  2919. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  2920. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  2921. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  2922. // K-quants
  2923. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  2924. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  2925. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  2926. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  2927. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  2928. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  2929. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  2930. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  2931. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  2932. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  2933. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XXS - 2.0625 bpw";
  2934. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  2935. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  2936. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  2937. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  2938. case LLAMA_FTYPE_MOSTLY_IQ3_XXS:return "IQ3_XXS - 3.0625 bpw";
  2939. case LLAMA_FTYPE_MOSTLY_IQ1_S :return "IQ1_S - 1.5625 bpw";
  2940. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  2941. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  2942. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  2943. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  2944. default: return "unknown, may not work";
  2945. }
  2946. }
  2947. static const char * llama_model_type_name(e_model type) {
  2948. switch (type) {
  2949. case MODEL_22M: return "22M";
  2950. case MODEL_33M: return "33M";
  2951. case MODEL_109M: return "109M";
  2952. case MODEL_137M: return "137M";
  2953. case MODEL_0_5B: return "0.5B";
  2954. case MODEL_1B: return "1B";
  2955. case MODEL_2B: return "2B";
  2956. case MODEL_3B: return "3B";
  2957. case MODEL_7B: return "7B";
  2958. case MODEL_8B: return "8B";
  2959. case MODEL_13B: return "13B";
  2960. case MODEL_14B: return "14B";
  2961. case MODEL_15B: return "15B";
  2962. case MODEL_20B: return "20B";
  2963. case MODEL_30B: return "30B";
  2964. case MODEL_34B: return "34B";
  2965. case MODEL_35B: return "35B";
  2966. case MODEL_40B: return "40B";
  2967. case MODEL_65B: return "65B";
  2968. case MODEL_70B: return "70B";
  2969. case MODEL_SMALL: return "0.1B";
  2970. case MODEL_MEDIUM: return "0.4B";
  2971. case MODEL_LARGE: return "0.8B";
  2972. case MODEL_XL: return "1.5B";
  2973. default: return "?B";
  2974. }
  2975. }
  2976. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  2977. switch (type) {
  2978. case LLAMA_VOCAB_TYPE_NONE: return "no vocab";
  2979. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  2980. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  2981. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  2982. default: return "unknown";
  2983. }
  2984. }
  2985. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  2986. model.arch = ml.get_arch();
  2987. if (model.arch == LLM_ARCH_UNKNOWN) {
  2988. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  2989. }
  2990. }
  2991. static void llm_load_hparams(
  2992. llama_model_loader & ml,
  2993. llama_model & model) {
  2994. auto & hparams = model.hparams;
  2995. const gguf_context * ctx = ml.meta;
  2996. // get metadata as string
  2997. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  2998. enum gguf_type type = gguf_get_kv_type(ctx, i);
  2999. if (type == GGUF_TYPE_ARRAY) {
  3000. continue;
  3001. }
  3002. const char * name = gguf_get_key(ctx, i);
  3003. const std::string value = gguf_kv_to_str(ctx, i);
  3004. model.gguf_kv.emplace(name, value);
  3005. }
  3006. // get general kv
  3007. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  3008. // get hparams kv
  3009. ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab, false) || ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  3010. ml.get_key(LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  3011. ml.get_key(LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  3012. ml.get_key(LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  3013. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  3014. ml.get_key(LLM_KV_BLOCK_COUNT, hparams.n_layer);
  3015. ml.get_key(LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  3016. ml.get_key(LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  3017. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  3018. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  3019. if (hparams.n_expert > 0) {
  3020. GGML_ASSERT(hparams.n_expert_used > 0);
  3021. } else {
  3022. GGML_ASSERT(hparams.n_expert_used == 0);
  3023. }
  3024. // n_head_kv is optional, default to n_head
  3025. hparams.n_head_kv = hparams.n_head;
  3026. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  3027. bool rope_finetuned = false;
  3028. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  3029. hparams.rope_finetuned = rope_finetuned;
  3030. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  3031. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  3032. // rope_freq_base (optional)
  3033. hparams.rope_freq_base_train = 10000.0f;
  3034. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  3035. std::string rope_scaling("linear");
  3036. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  3037. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  3038. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  3039. // rope_freq_scale (inverse of the kv) is optional
  3040. float ropescale = 0.0f;
  3041. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  3042. // try the old key name
  3043. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  3044. }
  3045. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  3046. // sanity check for n_rot (optional)
  3047. {
  3048. hparams.n_rot = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3049. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  3050. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  3051. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  3052. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  3053. }
  3054. }
  3055. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  3056. // gpt-j n_rot = rotary_dim
  3057. }
  3058. hparams.n_embd_head_k = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3059. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  3060. hparams.n_embd_head_v = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3061. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  3062. // arch-specific KVs
  3063. switch (model.arch) {
  3064. case LLM_ARCH_LLAMA:
  3065. {
  3066. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3067. switch (hparams.n_layer) {
  3068. case 22: model.type = e_model::MODEL_1B; break;
  3069. case 26: model.type = e_model::MODEL_3B; break;
  3070. case 32: model.type = e_model::MODEL_7B; break;
  3071. case 40: model.type = e_model::MODEL_13B; break;
  3072. case 48: model.type = e_model::MODEL_34B; break;
  3073. case 60: model.type = e_model::MODEL_30B; break;
  3074. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  3075. default: model.type = e_model::MODEL_UNKNOWN;
  3076. }
  3077. } break;
  3078. case LLM_ARCH_MINICPM:
  3079. {
  3080. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3081. switch (hparams.n_layer) {
  3082. case 40: model.type = e_model::MODEL_2B; break;
  3083. default: model.type = e_model::MODEL_UNKNOWN;
  3084. }
  3085. } break;
  3086. case LLM_ARCH_FALCON:
  3087. {
  3088. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3089. switch (hparams.n_layer) {
  3090. case 32: model.type = e_model::MODEL_7B; break;
  3091. case 60: model.type = e_model::MODEL_40B; break;
  3092. default: model.type = e_model::MODEL_UNKNOWN;
  3093. }
  3094. } break;
  3095. case LLM_ARCH_BAICHUAN:
  3096. {
  3097. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3098. switch (hparams.n_layer) {
  3099. case 32: model.type = e_model::MODEL_7B; break;
  3100. case 40: model.type = e_model::MODEL_13B; break;
  3101. default: model.type = e_model::MODEL_UNKNOWN;
  3102. }
  3103. if (model.type == e_model::MODEL_13B) {
  3104. // TODO: become GGUF KV parameter
  3105. hparams.f_max_alibi_bias = 8.0f;
  3106. }
  3107. } break;
  3108. case LLM_ARCH_STARCODER:
  3109. {
  3110. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3111. switch (hparams.n_layer) {
  3112. case 24: model.type = e_model::MODEL_1B; break;
  3113. case 36: model.type = e_model::MODEL_3B; break;
  3114. case 42: model.type = e_model::MODEL_7B; break;
  3115. case 40: model.type = e_model::MODEL_15B; break;
  3116. default: model.type = e_model::MODEL_UNKNOWN;
  3117. }
  3118. } break;
  3119. case LLM_ARCH_PERSIMMON:
  3120. {
  3121. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3122. switch (hparams.n_layer) {
  3123. case 36: model.type = e_model::MODEL_8B; break;
  3124. default: model.type = e_model::MODEL_UNKNOWN;
  3125. }
  3126. } break;
  3127. case LLM_ARCH_REFACT:
  3128. {
  3129. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3130. switch (hparams.n_layer) {
  3131. case 32: model.type = e_model::MODEL_1B; break;
  3132. default: model.type = e_model::MODEL_UNKNOWN;
  3133. }
  3134. // TODO: become GGUF KV parameter
  3135. hparams.f_max_alibi_bias = 8.0f;
  3136. } break;
  3137. case LLM_ARCH_BERT:
  3138. {
  3139. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3140. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  3141. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  3142. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  3143. switch (hparams.n_layer) {
  3144. case 3:
  3145. model.type = e_model::MODEL_17M; break; // bge-micro
  3146. case 6:
  3147. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  3148. case 12:
  3149. switch (hparams.n_embd) {
  3150. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  3151. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  3152. } break;
  3153. case 24:
  3154. model.type = e_model::MODEL_335M; break; // bge-large
  3155. }
  3156. } break;
  3157. case LLM_ARCH_NOMIC_BERT:
  3158. {
  3159. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3160. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  3161. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  3162. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  3163. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  3164. model.type = e_model::MODEL_137M;
  3165. }
  3166. } break;
  3167. case LLM_ARCH_BLOOM:
  3168. {
  3169. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3170. switch (hparams.n_layer) {
  3171. case 24: model.type = e_model::MODEL_1B; break;
  3172. case 30:
  3173. switch (hparams.n_embd) {
  3174. case 2560: model.type = e_model::MODEL_3B; break;
  3175. case 4096: model.type = e_model::MODEL_7B; break;
  3176. } break;
  3177. }
  3178. // TODO: become GGUF KV parameter
  3179. hparams.f_max_alibi_bias = 8.0f;
  3180. } break;
  3181. case LLM_ARCH_MPT:
  3182. {
  3183. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3184. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  3185. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  3186. switch (hparams.n_layer) {
  3187. case 32: model.type = e_model::MODEL_7B; break;
  3188. case 48: model.type = e_model::MODEL_30B; break;
  3189. default: model.type = e_model::MODEL_UNKNOWN;
  3190. }
  3191. } break;
  3192. case LLM_ARCH_STABLELM:
  3193. {
  3194. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3195. switch (hparams.n_layer) {
  3196. case 24: model.type = e_model::MODEL_1B; break;
  3197. case 32: model.type = e_model::MODEL_3B; break;
  3198. default: model.type = e_model::MODEL_UNKNOWN;
  3199. }
  3200. } break;
  3201. case LLM_ARCH_QWEN:
  3202. {
  3203. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3204. switch (hparams.n_layer) {
  3205. case 32: model.type = e_model::MODEL_7B; break;
  3206. case 40: model.type = e_model::MODEL_13B; break;
  3207. default: model.type = e_model::MODEL_UNKNOWN;
  3208. }
  3209. } break;
  3210. case LLM_ARCH_QWEN2:
  3211. {
  3212. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3213. switch (hparams.n_layer) {
  3214. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  3215. case 32: model.type = e_model::MODEL_7B; break;
  3216. case 40: model.type = hparams.n_head == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  3217. case 80: model.type = e_model::MODEL_70B; break;
  3218. default: model.type = e_model::MODEL_UNKNOWN;
  3219. }
  3220. } break;
  3221. case LLM_ARCH_PHI2:
  3222. {
  3223. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3224. switch (hparams.n_layer) {
  3225. case 24: model.type = e_model::MODEL_1B; break;
  3226. case 32: model.type = e_model::MODEL_3B; break;
  3227. default: model.type = e_model::MODEL_UNKNOWN;
  3228. }
  3229. } break;
  3230. case LLM_ARCH_PLAMO:
  3231. {
  3232. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3233. switch (hparams.n_layer) {
  3234. case 40: model.type = e_model::MODEL_13B; break;
  3235. default: model.type = e_model::MODEL_UNKNOWN;
  3236. }
  3237. } break;
  3238. case LLM_ARCH_GPT2:
  3239. {
  3240. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3241. switch (hparams.n_layer) {
  3242. case 12: model.type = e_model::MODEL_SMALL; break;
  3243. case 24: model.type = e_model::MODEL_MEDIUM; break;
  3244. case 36: model.type = e_model::MODEL_LARGE; break;
  3245. case 48: model.type = e_model::MODEL_XL; break;
  3246. default: model.type = e_model::MODEL_UNKNOWN;
  3247. }
  3248. } break;
  3249. case LLM_ARCH_CODESHELL:
  3250. {
  3251. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3252. switch (hparams.n_layer) {
  3253. case 42: model.type = e_model::MODEL_SMALL; break;
  3254. default: model.type = e_model::MODEL_UNKNOWN;
  3255. }
  3256. } break;
  3257. case LLM_ARCH_ORION:
  3258. {
  3259. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3260. switch (hparams.n_layer) {
  3261. case 40: model.type = e_model::MODEL_14B; break;
  3262. default: model.type = e_model::MODEL_UNKNOWN;
  3263. }
  3264. } break;
  3265. case LLM_ARCH_INTERNLM2:
  3266. {
  3267. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3268. switch (hparams.n_layer) {
  3269. case 32: model.type = e_model::MODEL_7B; break;
  3270. case 48: model.type = e_model::MODEL_20B; break;
  3271. default: model.type = e_model::MODEL_UNKNOWN;
  3272. }
  3273. } break;
  3274. case LLM_ARCH_GEMMA:
  3275. {
  3276. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3277. switch (hparams.n_layer) {
  3278. case 18: model.type = e_model::MODEL_2B; break;
  3279. case 28: model.type = e_model::MODEL_7B; break;
  3280. default: model.type = e_model::MODEL_UNKNOWN;
  3281. }
  3282. } break;
  3283. case LLM_ARCH_STARCODER2:
  3284. {
  3285. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3286. switch (hparams.n_layer) {
  3287. case 30: model.type = e_model::MODEL_3B; break;
  3288. case 32: model.type = e_model::MODEL_7B; break;
  3289. case 40: model.type = e_model::MODEL_15B; break;
  3290. default: model.type = e_model::MODEL_UNKNOWN;
  3291. }
  3292. } break;
  3293. case LLM_ARCH_MAMBA:
  3294. {
  3295. ml.get_key(LLM_KV_SSM_CONV_KERNEL, hparams.ssm_d_conv);
  3296. ml.get_key(LLM_KV_SSM_INNER_SIZE, hparams.ssm_d_inner);
  3297. ml.get_key(LLM_KV_SSM_STATE_SIZE, hparams.ssm_d_state);
  3298. ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
  3299. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3300. switch (hparams.n_layer) {
  3301. case 24:
  3302. switch (hparams.n_embd) {
  3303. case 768: model.type = e_model::MODEL_SMALL; break;
  3304. default: model.type = e_model::MODEL_UNKNOWN;
  3305. } break;
  3306. case 48:
  3307. switch (hparams.n_embd) {
  3308. case 1024: model.type = e_model::MODEL_MEDIUM; break;
  3309. case 1536: model.type = e_model::MODEL_LARGE; break;
  3310. case 2048: model.type = e_model::MODEL_XL; break;
  3311. default: model.type = e_model::MODEL_UNKNOWN;
  3312. } break;
  3313. case 64:
  3314. switch (hparams.n_embd) {
  3315. case 2560: model.type = e_model::MODEL_3B; break;
  3316. default: model.type = e_model::MODEL_UNKNOWN;
  3317. } break;
  3318. default: model.type = e_model::MODEL_UNKNOWN;
  3319. }
  3320. } break;
  3321. case LLM_ARCH_COMMAND_R:
  3322. {
  3323. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  3324. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3325. switch (hparams.n_layer) {
  3326. case 40: model.type = e_model::MODEL_35B; break;
  3327. default: model.type = e_model::MODEL_UNKNOWN;
  3328. }
  3329. } break;
  3330. default: (void)0;
  3331. }
  3332. model.ftype = ml.ftype;
  3333. if (hparams.f_max_alibi_bias > 0.0f) {
  3334. hparams.need_kq_pos = true;
  3335. }
  3336. hparams.rope_type = llama_rope_type(&model);
  3337. }
  3338. // TODO: This should probably be in llama.h
  3339. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  3340. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  3341. static void llm_load_vocab(
  3342. llama_model_loader & ml,
  3343. llama_model & model) {
  3344. auto & vocab = model.vocab;
  3345. struct gguf_context * ctx = ml.meta;
  3346. const auto kv = LLM_KV(model.arch);
  3347. // determine vocab type
  3348. {
  3349. std::string tokenizer_name;
  3350. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  3351. if (tokenizer_name == "no_vocab") {
  3352. vocab.type = LLAMA_VOCAB_TYPE_NONE;
  3353. // default special tokens
  3354. vocab.special_bos_id = -1;
  3355. vocab.special_eos_id = -1;
  3356. vocab.special_unk_id = -1;
  3357. vocab.special_sep_id = -1;
  3358. vocab.special_pad_id = -1;
  3359. vocab.linefeed_id = -1;
  3360. return;
  3361. } else if (tokenizer_name == "llama") {
  3362. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  3363. // default special tokens
  3364. vocab.special_bos_id = 1;
  3365. vocab.special_eos_id = 2;
  3366. vocab.special_unk_id = 0;
  3367. vocab.special_sep_id = -1;
  3368. vocab.special_pad_id = -1;
  3369. const int add_space_prefix_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_ADD_PREFIX).c_str());
  3370. if (add_space_prefix_keyidx != -1) {
  3371. vocab.add_space_prefix = gguf_get_val_bool(ctx, add_space_prefix_keyidx);
  3372. } // The default value of add_space_prefix is true.
  3373. } else if (tokenizer_name == "gpt2") {
  3374. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  3375. // read bpe merges and populate bpe ranks
  3376. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  3377. if (merges_keyidx == -1) {
  3378. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  3379. }
  3380. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  3381. for (int i = 0; i < n_merges; i++) {
  3382. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  3383. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  3384. std::string first;
  3385. std::string second;
  3386. const size_t pos = word.find(' ', 1);
  3387. if (pos != std::string::npos) {
  3388. first = word.substr(0, pos);
  3389. second = word.substr(pos + 1);
  3390. }
  3391. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  3392. }
  3393. // default special tokens
  3394. vocab.special_bos_id = 11;
  3395. vocab.special_eos_id = 11;
  3396. vocab.special_unk_id = -1;
  3397. vocab.special_sep_id = -1;
  3398. vocab.special_pad_id = -1;
  3399. } else if (tokenizer_name == "bert") {
  3400. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  3401. // default special tokens
  3402. vocab.special_bos_id = 101;
  3403. vocab.special_eos_id = 102;
  3404. vocab.special_unk_id = 100;
  3405. vocab.special_sep_id = -1;
  3406. vocab.special_pad_id = -1;
  3407. vocab.add_space_prefix = false;
  3408. } else {
  3409. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  3410. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  3411. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  3412. }
  3413. }
  3414. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  3415. if (token_idx == -1) {
  3416. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  3417. }
  3418. const float * scores = nullptr;
  3419. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  3420. if (score_idx != -1) {
  3421. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  3422. }
  3423. const int * toktypes = nullptr;
  3424. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  3425. if (toktype_idx != -1) {
  3426. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  3427. }
  3428. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  3429. vocab.id_to_token.resize(n_vocab);
  3430. for (uint32_t i = 0; i < n_vocab; i++) {
  3431. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  3432. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  3433. vocab.token_to_id[word] = i;
  3434. auto & token_data = vocab.id_to_token[i];
  3435. token_data.text = std::move(word);
  3436. token_data.score = scores ? scores[i] : 0.0f;
  3437. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  3438. }
  3439. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  3440. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  3441. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  3442. try {
  3443. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  3444. } catch (const std::exception & e) {
  3445. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  3446. vocab.linefeed_id = vocab.special_pad_id;
  3447. }
  3448. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  3449. vocab.linefeed_id = vocab.special_pad_id;
  3450. } else {
  3451. const std::vector<int> ids = llama_tokenize_internal(vocab, "\u010A", false);
  3452. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  3453. vocab.linefeed_id = ids[0];
  3454. }
  3455. // special tokens
  3456. {
  3457. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  3458. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  3459. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  3460. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  3461. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  3462. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  3463. };
  3464. for (const auto & it : special_token_types) {
  3465. const std::string & key = kv(std::get<0>(it));
  3466. int32_t & id = std::get<1>(it);
  3467. uint32_t new_id;
  3468. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  3469. continue;
  3470. }
  3471. if (new_id >= vocab.id_to_token.size()) {
  3472. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  3473. __func__, key.c_str(), new_id, id);
  3474. } else {
  3475. id = new_id;
  3476. }
  3477. }
  3478. // Handle add_bos_token and add_eos_token
  3479. {
  3480. bool temp = true;
  3481. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  3482. vocab.special_add_bos = int(temp);
  3483. }
  3484. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  3485. vocab.special_add_eos = int(temp);
  3486. }
  3487. }
  3488. }
  3489. // build special tokens cache
  3490. {
  3491. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  3492. // and will always be correctly labeled in 'added_tokens.json' etc.
  3493. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  3494. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  3495. // are special tokens.
  3496. // From testing, this appears to correlate 1:1 with special tokens.
  3497. //
  3498. // Counting special tokens and verifying in only one direction
  3499. // is sufficient to detect difference in those two sets.
  3500. //
  3501. uint32_t special_tokens_count_by_type = 0;
  3502. uint32_t special_tokens_count_from_verification = 0;
  3503. bool special_tokens_definition_mismatch = false;
  3504. for (const auto & t : vocab.token_to_id) {
  3505. const auto & token = t.first;
  3506. const auto & id = t.second;
  3507. // Count all non-normal tokens in the vocab while iterating
  3508. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  3509. special_tokens_count_by_type++;
  3510. }
  3511. // Skip single character tokens
  3512. if (token.length() > 1) {
  3513. bool is_tokenizable = false;
  3514. // Split token string representation in two, in all possible ways
  3515. // and check if both halves can be matched to a valid token
  3516. for (unsigned i = 1; i < token.length();) {
  3517. const auto left = token.substr(0, i);
  3518. const auto right = token.substr(i);
  3519. // check if we didnt partition in the middle of a utf sequence
  3520. auto utf = utf8_len(left.at(left.length() - 1));
  3521. if (utf == 1) {
  3522. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  3523. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  3524. is_tokenizable = true;
  3525. break;
  3526. }
  3527. i++;
  3528. } else {
  3529. // skip over the rest of multibyte utf sequence
  3530. i += utf - 1;
  3531. }
  3532. }
  3533. if (!is_tokenizable) {
  3534. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  3535. // it's faster to re-filter them here, since there are way less candidates now
  3536. // Calculate a total "utf" length of a token string representation
  3537. size_t utf8_str_len = 0;
  3538. for (unsigned i = 0; i < token.length();) {
  3539. utf8_str_len++;
  3540. i += utf8_len(token.at(i));
  3541. }
  3542. // And skip the ones which are one character
  3543. if (utf8_str_len > 1) {
  3544. // At this point what we have left are special tokens only
  3545. vocab.special_tokens_cache[token] = id;
  3546. // Count manually found special tokens
  3547. special_tokens_count_from_verification++;
  3548. // If this manually found special token is not marked as such, flag a mismatch
  3549. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  3550. special_tokens_definition_mismatch = true;
  3551. }
  3552. }
  3553. }
  3554. }
  3555. }
  3556. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  3557. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  3558. __func__,
  3559. special_tokens_count_from_verification, vocab.id_to_token.size(),
  3560. special_tokens_count_by_type, vocab.id_to_token.size()
  3561. );
  3562. } else {
  3563. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  3564. __func__,
  3565. special_tokens_count_from_verification, vocab.id_to_token.size()
  3566. );
  3567. }
  3568. }
  3569. }
  3570. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  3571. const auto & hparams = model.hparams;
  3572. const auto & vocab = model.vocab;
  3573. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  3574. // hparams
  3575. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  3576. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  3577. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  3578. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  3579. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  3580. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  3581. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  3582. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  3583. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  3584. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  3585. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  3586. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  3587. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  3588. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  3589. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  3590. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  3591. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  3592. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  3593. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  3594. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  3595. LLAMA_LOG_INFO("%s: f_logit_scale = %.1e\n", __func__, hparams.f_logit_scale);
  3596. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  3597. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  3598. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  3599. LLAMA_LOG_INFO("%s: causal attn = %d\n", __func__, hparams.causal_attn);
  3600. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  3601. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  3602. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  3603. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  3604. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  3605. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  3606. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  3607. LLAMA_LOG_INFO("%s: ssm_d_conv = %u\n", __func__, hparams.ssm_d_conv);
  3608. LLAMA_LOG_INFO("%s: ssm_d_inner = %u\n", __func__, hparams.ssm_d_inner);
  3609. LLAMA_LOG_INFO("%s: ssm_d_state = %u\n", __func__, hparams.ssm_d_state);
  3610. LLAMA_LOG_INFO("%s: ssm_dt_rank = %u\n", __func__, hparams.ssm_dt_rank);
  3611. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  3612. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  3613. if (ml.n_elements >= 1e12) {
  3614. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  3615. } else if (ml.n_elements >= 1e9) {
  3616. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  3617. } else if (ml.n_elements >= 1e6) {
  3618. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  3619. } else {
  3620. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  3621. }
  3622. if (ml.n_bytes < GiB) {
  3623. 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);
  3624. } else {
  3625. 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);
  3626. }
  3627. // general kv
  3628. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  3629. // special tokens
  3630. 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() ); }
  3631. 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() ); }
  3632. 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() ); }
  3633. 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() ); }
  3634. 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() ); }
  3635. 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() ); }
  3636. }
  3637. // Returns false if cancelled by progress_callback
  3638. static bool llm_load_tensors(
  3639. llama_model_loader & ml,
  3640. llama_model & model,
  3641. int n_gpu_layers,
  3642. enum llama_split_mode split_mode,
  3643. int main_gpu,
  3644. const float * tensor_split,
  3645. bool use_mlock,
  3646. llama_progress_callback progress_callback,
  3647. void * progress_callback_user_data) {
  3648. model.t_start_us = ggml_time_us();
  3649. auto & hparams = model.hparams;
  3650. model.split_mode = split_mode;
  3651. model.main_gpu = main_gpu;
  3652. model.n_gpu_layers = n_gpu_layers;
  3653. const int64_t n_layer = hparams.n_layer;
  3654. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  3655. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  3656. model.buft_input = llama_default_buffer_type_cpu(true);
  3657. //model.buft_input = llama_default_buffer_type_offload(main_gpu);
  3658. model.buft_layer.resize(n_layer);
  3659. // assign cpu layers
  3660. for (int64_t i = 0; i < i_gpu_start; ++i) {
  3661. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  3662. }
  3663. if (split_mode == LLAMA_SPLIT_MODE_LAYER) {
  3664. // calculate the split points
  3665. int device_count = llama_get_device_count();
  3666. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  3667. std::vector<float> splits(device_count);
  3668. if (all_zero) {
  3669. // default split, by free memory
  3670. for (int i = 0; i < device_count; ++i) {
  3671. splits[i] = llama_get_device_memory(i);
  3672. }
  3673. } else {
  3674. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  3675. }
  3676. // sum and normalize the splits to get the split points
  3677. float split_sum = 0.0f;
  3678. for (int i = 0; i < device_count; ++i) {
  3679. split_sum += splits[i];
  3680. splits[i] = split_sum;
  3681. }
  3682. for (int i = 0; i < device_count; ++i) {
  3683. splits[i] /= split_sum;
  3684. }
  3685. // assign the repeating layers to the devices according to the splits
  3686. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  3687. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3688. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  3689. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  3690. }
  3691. // assign the output layer
  3692. if (n_gpu_layers > n_layer) {
  3693. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  3694. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  3695. } else {
  3696. model.buft_output = llama_default_buffer_type_cpu(true);
  3697. }
  3698. } else {
  3699. ggml_backend_buffer_type_t split_buft;
  3700. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  3701. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  3702. } else {
  3703. // LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_LAYER in backends where it is not supported
  3704. split_buft = llama_default_buffer_type_offload(main_gpu);
  3705. }
  3706. // assign the repeating layers
  3707. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3708. model.buft_layer[i] = {
  3709. split_buft,
  3710. llama_default_buffer_type_offload(main_gpu)
  3711. };
  3712. }
  3713. // assign the output layer
  3714. if (n_gpu_layers > n_layer) {
  3715. model.buft_output = {
  3716. split_buft,
  3717. llama_default_buffer_type_offload(main_gpu)
  3718. };
  3719. } else {
  3720. model.buft_output = llama_default_buffer_type_cpu(true);
  3721. }
  3722. }
  3723. // count used buffer types
  3724. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  3725. buft_layer_count[model.buft_input.buft]++;
  3726. buft_layer_count[model.buft_input.buft_matrix]++;
  3727. buft_layer_count[model.buft_output.buft]++;
  3728. buft_layer_count[model.buft_output.buft_matrix]++;
  3729. for (int64_t i = 0; i < n_layer; ++i) {
  3730. buft_layer_count[model.buft_layer[i].buft]++;
  3731. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  3732. }
  3733. // create one context per buffer type
  3734. size_t ctx_size = ggml_tensor_overhead()*(ml.n_tensors + 1); // +1 for models where tok_embd is duplicated as output
  3735. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3736. for (auto & it : buft_layer_count) {
  3737. struct ggml_init_params params = {
  3738. /*.mem_size =*/ ctx_size,
  3739. /*.mem_buffer =*/ NULL,
  3740. /*.no_alloc =*/ true,
  3741. };
  3742. ggml_context * ctx = ggml_init(params);
  3743. if (!ctx) {
  3744. throw std::runtime_error(format("failed to create context"));
  3745. }
  3746. ctx_map[it.first] = ctx;
  3747. model.ctxs.push_back(ctx);
  3748. }
  3749. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  3750. // create tensors for the weights
  3751. {
  3752. const int64_t n_embd = hparams.n_embd;
  3753. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3754. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3755. const int64_t n_embd_gqa = n_embd_v_gqa;
  3756. const int64_t n_vocab = hparams.n_vocab;
  3757. const int64_t n_vocab_type = hparams.n_vocab_type;
  3758. const int64_t n_ff = hparams.n_ff;
  3759. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  3760. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  3761. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  3762. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  3763. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  3764. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  3765. model.layers.resize(n_layer);
  3766. const auto tn = LLM_TN(model.arch);
  3767. switch (model.arch) {
  3768. case LLM_ARCH_LLAMA:
  3769. case LLM_ARCH_REFACT:
  3770. case LLM_ARCH_MINICPM:
  3771. {
  3772. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3773. // output
  3774. {
  3775. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3776. if (model.arch != LLM_ARCH_MINICPM){
  3777. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  3778. // if output is NULL, init from the input tok embed
  3779. if (model.output == NULL) {
  3780. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3781. ml.n_created--; // artificial tensor
  3782. ml.size_data += ggml_nbytes(model.output);
  3783. }
  3784. }
  3785. }
  3786. for (int i = 0; i < n_layer; ++i) {
  3787. ggml_context * ctx_layer = ctx_for_layer(i);
  3788. ggml_context * ctx_split = ctx_for_layer_split(i);
  3789. auto & layer = model.layers[i];
  3790. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3791. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3792. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3793. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3794. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3795. // optional bias tensors
  3796. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3797. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3798. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3799. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3800. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3801. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd}, false);
  3802. if (layer.ffn_gate_inp == nullptr) {
  3803. GGML_ASSERT(hparams.n_expert == 0);
  3804. GGML_ASSERT(hparams.n_expert_used == 0);
  3805. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3806. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3807. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3808. } else {
  3809. GGML_ASSERT(hparams.n_expert > 0);
  3810. GGML_ASSERT(hparams.n_expert_used > 0);
  3811. // MoE branch
  3812. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  3813. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  3814. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  3815. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  3816. }
  3817. }
  3818. }
  3819. } break;
  3820. case LLM_ARCH_BAICHUAN:
  3821. {
  3822. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3823. {
  3824. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3825. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3826. }
  3827. for (int i = 0; i < n_layer; ++i) {
  3828. ggml_context * ctx_layer = ctx_for_layer(i);
  3829. ggml_context * ctx_split = ctx_for_layer_split(i);
  3830. auto & layer = model.layers[i];
  3831. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3832. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3833. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3834. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3835. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3836. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3837. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3838. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3839. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3840. }
  3841. } break;
  3842. case LLM_ARCH_FALCON:
  3843. {
  3844. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3845. // output
  3846. {
  3847. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3848. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3849. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  3850. if (!model.output) {
  3851. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  3852. ml.n_created--; // artificial tensor
  3853. ml.size_data += ggml_nbytes(model.output);
  3854. }
  3855. }
  3856. for (int i = 0; i < n_layer; ++i) {
  3857. ggml_context * ctx_layer = ctx_for_layer(i);
  3858. ggml_context * ctx_split = ctx_for_layer_split(i);
  3859. auto & layer = model.layers[i];
  3860. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3861. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3862. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd}, false);
  3863. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd}, false);
  3864. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3865. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3866. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3867. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3868. }
  3869. } break;
  3870. case LLM_ARCH_STARCODER:
  3871. {
  3872. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3873. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3874. // output
  3875. {
  3876. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3877. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3878. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3879. }
  3880. for (int i = 0; i < n_layer; ++i) {
  3881. ggml_context * ctx_layer = ctx_for_layer(i);
  3882. ggml_context * ctx_split = ctx_for_layer_split(i);
  3883. auto & layer = model.layers[i];
  3884. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3885. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3886. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3887. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3888. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3889. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3890. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3891. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3892. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3893. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3894. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3895. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3896. }
  3897. } break;
  3898. case LLM_ARCH_PERSIMMON:
  3899. {
  3900. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3901. {
  3902. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3903. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3904. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3905. }
  3906. for (int i = 0; i < n_layer; ++i) {
  3907. ggml_context * ctx_layer = ctx_for_layer(i);
  3908. ggml_context * ctx_split = ctx_for_layer_split(i);
  3909. auto & layer = model.layers[i];
  3910. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3911. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3912. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3913. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3914. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3915. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3916. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3917. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3918. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3919. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3920. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3921. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3922. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  3923. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  3924. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  3925. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  3926. }
  3927. } break;
  3928. case LLM_ARCH_BERT:
  3929. case LLM_ARCH_NOMIC_BERT:
  3930. {
  3931. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3932. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  3933. if (model.arch == LLM_ARCH_BERT) {
  3934. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3935. }
  3936. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3937. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3938. for (int i = 0; i < n_layer; ++i) {
  3939. ggml_context * ctx_layer = ctx_for_layer(i);
  3940. ggml_context * ctx_split = ctx_for_layer_split(i);
  3941. auto & layer = model.layers[i];
  3942. if (model.arch == LLM_ARCH_BERT) {
  3943. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3944. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3945. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3946. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3947. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3948. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3949. } else {
  3950. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3951. }
  3952. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3953. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  3954. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  3955. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3956. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3957. if (model.arch == LLM_ARCH_BERT) {
  3958. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3959. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3960. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3961. } else {
  3962. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3963. }
  3964. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  3965. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  3966. }
  3967. } break;
  3968. case LLM_ARCH_BLOOM:
  3969. {
  3970. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3971. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3972. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3973. // output
  3974. {
  3975. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3976. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3977. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3978. }
  3979. for (int i = 0; i < n_layer; ++i) {
  3980. ggml_context * ctx_layer = ctx_for_layer(i);
  3981. ggml_context * ctx_split = ctx_for_layer_split(i);
  3982. auto & layer = model.layers[i];
  3983. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3984. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3985. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3986. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3987. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3988. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3989. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3990. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3991. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3992. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3993. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3994. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3995. }
  3996. } break;
  3997. case LLM_ARCH_MPT:
  3998. {
  3999. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4000. // output
  4001. {
  4002. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4003. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, false);
  4004. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4005. if (!model.output) {
  4006. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  4007. ml.n_created--; // artificial tensor
  4008. ml.size_data += ggml_nbytes(model.output);
  4009. }
  4010. }
  4011. for (int i = 0; i < n_layer; ++i) {
  4012. ggml_context * ctx_layer = ctx_for_layer(i);
  4013. ggml_context * ctx_split = ctx_for_layer_split(i);
  4014. auto & layer = model.layers[i];
  4015. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4016. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, false);
  4017. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4018. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  4019. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4020. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  4021. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4022. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, false);
  4023. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4024. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, false);
  4025. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4026. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, false);
  4027. // AWQ ScaleActivation layer
  4028. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  4029. }
  4030. } break;
  4031. case LLM_ARCH_STABLELM:
  4032. {
  4033. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4034. // output
  4035. {
  4036. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4037. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4038. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4039. }
  4040. for (int i = 0; i < n_layer; ++i) {
  4041. ggml_context * ctx_layer = ctx_for_layer(i);
  4042. ggml_context * ctx_split = ctx_for_layer_split(i);
  4043. auto & layer = model.layers[i];
  4044. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4045. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4046. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4047. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4048. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4049. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4050. // optional bias tensors, present in Stable LM 2 1.6B
  4051. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  4052. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  4053. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  4054. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4055. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4056. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4057. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4058. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4059. }
  4060. } break;
  4061. case LLM_ARCH_QWEN:
  4062. {
  4063. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4064. // output
  4065. {
  4066. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4067. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4068. }
  4069. for (int i = 0; i < n_layer; ++i) {
  4070. ggml_context * ctx_layer = ctx_for_layer(i);
  4071. ggml_context * ctx_split = ctx_for_layer_split(i);
  4072. auto & layer = model.layers[i];
  4073. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4074. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  4075. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  4076. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4077. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4078. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  4079. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  4080. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  4081. }
  4082. } break;
  4083. case LLM_ARCH_QWEN2:
  4084. {
  4085. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4086. // output
  4087. {
  4088. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4089. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4090. }
  4091. for (int i = 0; i < n_layer; ++i) {
  4092. ggml_context * ctx_layer = ctx_for_layer(i);
  4093. ggml_context * ctx_split = ctx_for_layer_split(i);
  4094. auto & layer = model.layers[i];
  4095. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4096. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4097. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4098. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4099. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4100. // optional bias tensors
  4101. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4102. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4103. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4104. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4105. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4106. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4107. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4108. }
  4109. } break;
  4110. case LLM_ARCH_PHI2:
  4111. {
  4112. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4113. // output
  4114. {
  4115. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4116. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4117. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4118. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  4119. }
  4120. for (int i = 0; i < n_layer; ++i) {
  4121. ggml_context * ctx_layer = ctx_for_layer(i);
  4122. ggml_context * ctx_split = ctx_for_layer_split(i);
  4123. auto & layer = model.layers[i];
  4124. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4125. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4126. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  4127. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  4128. if (layer.wqkv == nullptr) {
  4129. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4130. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4131. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4132. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4133. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4134. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4135. }
  4136. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4137. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4138. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4139. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4140. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4141. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4142. }
  4143. } break;
  4144. case LLM_ARCH_PLAMO:
  4145. {
  4146. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4147. // output
  4148. {
  4149. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4150. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4151. }
  4152. for (int i = 0; i < n_layer; ++i) {
  4153. ggml_context * ctx_layer = ctx_for_layer(i);
  4154. ggml_context * ctx_split = ctx_for_layer_split(i);
  4155. auto & layer = model.layers[i];
  4156. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4157. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4158. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4159. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4160. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4161. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4162. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4163. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4164. }
  4165. } break;
  4166. case LLM_ARCH_GPT2:
  4167. {
  4168. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4169. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  4170. // output
  4171. {
  4172. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4173. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4174. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4175. }
  4176. for (int i = 0; i < n_layer; ++i) {
  4177. ggml_context * ctx_layer = ctx_for_layer(i);
  4178. ggml_context * ctx_split = ctx_for_layer_split(i);
  4179. auto & layer = model.layers[i];
  4180. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4181. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4182. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4183. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4184. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4185. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4186. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4187. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4188. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4189. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4190. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4191. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4192. }
  4193. } break;
  4194. case LLM_ARCH_CODESHELL:
  4195. {
  4196. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4197. // output
  4198. {
  4199. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4200. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4201. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4202. }
  4203. for (int i = 0; i < n_layer; ++i) {
  4204. ggml_context * ctx_layer = ctx_for_layer(i);
  4205. ggml_context * ctx_split = ctx_for_layer_split(i);
  4206. auto & layer = model.layers[i];
  4207. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4208. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4209. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4210. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4211. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4212. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4213. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4214. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4215. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4216. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4217. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4218. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4219. }
  4220. } break;
  4221. case LLM_ARCH_ORION:
  4222. {
  4223. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4224. {
  4225. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4226. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4227. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4228. }
  4229. for (int i = 0; i < n_layer; ++i) {
  4230. ggml_context * ctx_layer = ctx_for_layer(i);
  4231. ggml_context * ctx_split = ctx_for_layer_split(i);
  4232. auto & layer = model.layers[i];
  4233. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4234. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4235. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4236. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4237. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4238. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4239. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4240. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4241. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4242. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4243. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4244. }
  4245. } break;
  4246. case LLM_ARCH_INTERNLM2:
  4247. {
  4248. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4249. // output
  4250. {
  4251. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4252. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4253. }
  4254. for (int i = 0; i < n_layer; ++i) {
  4255. ggml_context * ctx_layer = ctx_for_layer(i);
  4256. ggml_context * ctx_split = ctx_for_layer_split(i);
  4257. auto & layer = model.layers[i];
  4258. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4259. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4260. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4261. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4262. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4263. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4264. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4265. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4266. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4267. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4268. }
  4269. } break;
  4270. case LLM_ARCH_GEMMA:
  4271. {
  4272. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4273. // output
  4274. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4275. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // same as tok_embd, duplicated to allow offloading
  4276. ml.n_created--; // artificial tensor
  4277. ml.size_data += ggml_nbytes(model.output);
  4278. const int64_t n_ff = hparams.n_ff;
  4279. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  4280. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4281. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4282. for (uint32_t i = 0; i < n_layer; ++i) {
  4283. ggml_context * ctx_layer = ctx_for_layer(i);
  4284. ggml_context * ctx_split = ctx_for_layer_split(i);
  4285. auto & layer = model.layers[i];
  4286. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4287. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * hparams.n_head});
  4288. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  4289. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  4290. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * hparams.n_head, n_embd});
  4291. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4292. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4293. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4294. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4295. }
  4296. } break;
  4297. case LLM_ARCH_STARCODER2:
  4298. {
  4299. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4300. // output
  4301. {
  4302. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4303. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4304. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4305. // if output is NULL, init from the input tok embed
  4306. if (model.output == NULL) {
  4307. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4308. ml.n_created--; // artificial tensor
  4309. ml.size_data += ggml_nbytes(model.output);
  4310. }
  4311. }
  4312. for (int i = 0; i < n_layer; ++i) {
  4313. ggml_context * ctx_layer = ctx_for_layer(i);
  4314. ggml_context * ctx_split = ctx_for_layer_split(i);
  4315. auto & layer = model.layers[i];
  4316. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4317. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4318. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4319. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4320. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4321. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4322. // optional bias tensors
  4323. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4324. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4325. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4326. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4327. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4328. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4329. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4330. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4331. // optional bias tensors
  4332. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4333. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP , "bias", i), { n_ff});
  4334. }
  4335. } break;
  4336. case LLM_ARCH_MAMBA:
  4337. {
  4338. const int64_t d_conv = hparams.ssm_d_conv;
  4339. const int64_t d_inner = hparams.ssm_d_inner;
  4340. const int64_t d_state = hparams.ssm_d_state;
  4341. const int64_t dt_rank = hparams.ssm_dt_rank;
  4342. // only an expansion factor of 2 is supported for now
  4343. GGML_ASSERT(2 * n_embd == d_inner);
  4344. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4345. // output
  4346. {
  4347. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4348. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4349. // if output is NULL, init from the input tok embed, duplicated to allow offloading
  4350. if (model.output == NULL) {
  4351. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4352. ml.n_created--; // artificial tensor
  4353. ml.size_data += ggml_nbytes(model.output);
  4354. }
  4355. }
  4356. for (int i = 0; i < n_layer; ++i) {
  4357. ggml_context * ctx_layer = ctx_for_layer(i);
  4358. ggml_context * ctx_split = ctx_for_layer_split(i);
  4359. auto & layer = model.layers[i];
  4360. // norm
  4361. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4362. layer.ssm_in = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_IN, "weight", i), {n_embd, 2*d_inner});
  4363. layer.ssm_conv1d = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_CONV1D, "weight", i), {d_conv, d_inner});
  4364. layer.ssm_conv1d_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_CONV1D, "bias", i), {d_inner});
  4365. layer.ssm_x = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_X, "weight", i), {d_inner, dt_rank + 2*d_state});
  4366. layer.ssm_dt = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_DT, "weight", i), {dt_rank, d_inner});
  4367. layer.ssm_dt_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_DT, "bias", i), {d_inner});
  4368. // no "weight" suffix for these
  4369. layer.ssm_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_A, i), {d_state, d_inner});
  4370. layer.ssm_d = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_D, i), {d_inner});
  4371. // out_proj
  4372. layer.ssm_out = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_OUT, "weight", i), {d_inner, n_embd});
  4373. }
  4374. } break;
  4375. case LLM_ARCH_COMMAND_R:
  4376. {
  4377. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4378. // output
  4379. {
  4380. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4381. // init output from the input tok embed
  4382. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4383. ml.n_created--; // artificial tensor
  4384. ml.size_data += ggml_nbytes(model.output);
  4385. }
  4386. for (int i = 0; i < n_layer; ++i) {
  4387. ggml_context * ctx_layer = ctx_for_layer(i);
  4388. ggml_context * ctx_split = ctx_for_layer_split(i);
  4389. auto & layer = model.layers[i];
  4390. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4391. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4392. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4393. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4394. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4395. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4396. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4397. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4398. }
  4399. } break;
  4400. default:
  4401. throw std::runtime_error("unknown architecture");
  4402. }
  4403. }
  4404. ml.done_getting_tensors();
  4405. ml.init_mappings(true, &model.mlock_mmaps);
  4406. model.mappings.reserve(ml.mappings.size());
  4407. // create the backend buffers
  4408. std::vector<std::pair<ggml_context *, llama_buf_map>> ctx_bufs;
  4409. ctx_bufs.reserve(ctx_map.size());
  4410. // Ensure we have enough capacity for the maximum backend buffer we will potentially create
  4411. size_t n_max_backend_buffer = ctx_map.size() * ml.files.size();
  4412. model.bufs.reserve(n_max_backend_buffer);
  4413. for (auto & it : ctx_map) {
  4414. ggml_backend_buffer_type_t buft = it.first;
  4415. ggml_context * ctx = it.second;
  4416. llama_buf_map bufs;
  4417. bufs.reserve(n_max_backend_buffer);
  4418. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  4419. // this is important for metal with apple silicon: if the entire model could be mapped to a metal buffer, then we could just use metal for all layers
  4420. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  4421. if (ml.use_mmap && buft == llama_default_buffer_type_cpu(true)) {
  4422. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  4423. void * addr = nullptr;
  4424. size_t first, last;
  4425. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  4426. if (first >= last) {
  4427. continue;
  4428. }
  4429. ggml_backend_buffer_t buf = ggml_backend_cpu_buffer_from_ptr((char *) addr + first, last - first);
  4430. if (buf == nullptr) {
  4431. throw std::runtime_error("unable to allocate backend CPU buffer");
  4432. }
  4433. model.bufs.push_back(buf);
  4434. bufs.emplace(idx, buf);
  4435. #ifdef GGML_USE_CUBLAS
  4436. if (n_layer >= n_gpu_layers) {
  4437. ggml_backend_cuda_register_host_buffer(
  4438. ggml_backend_buffer_get_base(buf),
  4439. ggml_backend_buffer_get_size(buf));
  4440. }
  4441. #endif
  4442. }
  4443. }
  4444. #ifdef GGML_USE_METAL
  4445. else if (ml.use_mmap && buft == ggml_backend_metal_buffer_type()) {
  4446. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  4447. const size_t max_size = ggml_get_max_tensor_size(ctx);
  4448. void * addr = nullptr;
  4449. size_t first, last;
  4450. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  4451. if (first >= last) {
  4452. continue;
  4453. }
  4454. ggml_backend_buffer_t buf = ggml_backend_metal_buffer_from_ptr((char *) addr + first, last - first, max_size);
  4455. if (buf == nullptr) {
  4456. throw std::runtime_error("unable to allocate backend metal buffer");
  4457. }
  4458. model.bufs.push_back(buf);
  4459. bufs.emplace(idx, buf);
  4460. }
  4461. }
  4462. #endif
  4463. else {
  4464. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  4465. if (buf == nullptr) {
  4466. throw std::runtime_error("unable to allocate backend buffer");
  4467. }
  4468. model.bufs.push_back(buf);
  4469. if (use_mlock && ggml_backend_buffer_is_host(buf)) {
  4470. model.mlock_bufs.emplace_back(new llama_mlock);
  4471. auto & mlock_buf = model.mlock_bufs.back();
  4472. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  4473. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  4474. }
  4475. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  4476. bufs.emplace(idx, buf);
  4477. }
  4478. }
  4479. if (bufs.empty()) {
  4480. throw std::runtime_error("failed to allocate buffer");
  4481. }
  4482. for (auto & buf : bufs) {
  4483. // indicate that this buffer contains weights
  4484. // this is used by ggml_backend_sched to improve op scheduling -> ops that use a weight are preferably scheduled to the backend that contains the weight
  4485. ggml_backend_buffer_set_usage(buf.second, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  4486. }
  4487. ctx_bufs.emplace_back(ctx, bufs);
  4488. }
  4489. if (llama_supports_gpu_offload()) {
  4490. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  4491. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  4492. if (n_gpu_layers > (int) hparams.n_layer) {
  4493. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  4494. }
  4495. const int max_backend_supported_layers = hparams.n_layer + 1;
  4496. const int max_offloadable_layers = hparams.n_layer + 1;
  4497. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  4498. }
  4499. // print memory requirements
  4500. for (ggml_backend_buffer_t buf : model.bufs) {
  4501. LLAMA_LOG_INFO("%s: %10s buffer size = %8.2f MiB\n", __func__, ggml_backend_buffer_name(buf), ggml_backend_buffer_get_size(buf) / 1024.0 / 1024.0);
  4502. }
  4503. // populate tensors_by_name
  4504. for (ggml_context * ctx : model.ctxs) {
  4505. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  4506. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  4507. }
  4508. }
  4509. // load tensor data
  4510. for (auto & it : ctx_bufs) {
  4511. ggml_context * ctx = it.first;
  4512. auto & bufs = it.second;
  4513. if (!ml.load_all_data(ctx, bufs, use_mlock ? &model.mlock_mmaps : NULL, progress_callback, progress_callback_user_data)) {
  4514. return false;
  4515. }
  4516. }
  4517. for (auto & mapping : ml.mappings) {
  4518. model.mappings.emplace_back(std::move(mapping));
  4519. }
  4520. // loading time will be recalculate after the first eval, so
  4521. // we take page faults deferred by mmap() into consideration
  4522. model.t_load_us = ggml_time_us() - model.t_start_us;
  4523. return true;
  4524. }
  4525. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  4526. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  4527. try {
  4528. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  4529. model.hparams.vocab_only = params.vocab_only;
  4530. try {
  4531. llm_load_arch(ml, model);
  4532. } catch(const std::exception & e) {
  4533. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  4534. }
  4535. try {
  4536. llm_load_hparams(ml, model);
  4537. } catch(const std::exception & e) {
  4538. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  4539. }
  4540. try {
  4541. llm_load_vocab(ml, model);
  4542. } catch(const std::exception & e) {
  4543. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  4544. }
  4545. llm_load_print_meta(ml, model);
  4546. if (model.vocab.type != LLAMA_VOCAB_TYPE_NONE &&
  4547. model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  4548. throw std::runtime_error("vocab size mismatch");
  4549. }
  4550. if (params.vocab_only) {
  4551. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  4552. return 0;
  4553. }
  4554. #ifdef GGML_USE_KOMPUTE
  4555. if (params.n_gpu_layers > 0 && (
  4556. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  4557. || !(
  4558. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  4559. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  4560. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  4561. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  4562. )
  4563. )) {
  4564. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  4565. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  4566. params.n_gpu_layers = 0;
  4567. }
  4568. #endif
  4569. #ifdef GGML_USE_SYCL
  4570. if (params.split_mode == LLAMA_SPLIT_MODE_NONE) {
  4571. ggml_backend_sycl_set_single_device_mode(params.main_gpu);
  4572. //SYCL use device index (0, 1, 2) directly, uer input device id, then convert to device index.
  4573. params.main_gpu = ggml_backend_sycl_get_device_index(params.main_gpu);
  4574. } else {
  4575. ggml_backend_sycl_set_mul_device_mode();
  4576. }
  4577. #endif
  4578. if (!llm_load_tensors(
  4579. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  4580. params.progress_callback, params.progress_callback_user_data
  4581. )) {
  4582. return -2;
  4583. }
  4584. } catch (const std::exception & err) {
  4585. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  4586. return -1;
  4587. }
  4588. return 0;
  4589. }
  4590. //
  4591. // llm_build
  4592. //
  4593. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  4594. enum llm_ffn_op_type {
  4595. LLM_FFN_SILU,
  4596. LLM_FFN_GELU,
  4597. LLM_FFN_RELU,
  4598. LLM_FFN_RELU_SQR,
  4599. };
  4600. enum llm_ffn_gate_type {
  4601. LLM_FFN_SEQ,
  4602. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  4603. };
  4604. enum llm_norm_type {
  4605. LLM_NORM,
  4606. LLM_NORM_RMS,
  4607. };
  4608. static struct ggml_tensor * llm_build_inp_embd(
  4609. struct ggml_context * ctx,
  4610. struct llama_context & lctx,
  4611. const llama_hparams & hparams,
  4612. const llama_batch & batch,
  4613. struct ggml_tensor * tok_embd,
  4614. const llm_build_cb & cb) {
  4615. const int64_t n_embd = hparams.n_embd;
  4616. struct ggml_tensor * inpL;
  4617. if (batch.token) {
  4618. lctx.inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  4619. cb(lctx.inp_tokens, "inp_tokens", -1);
  4620. ggml_set_input(lctx.inp_tokens);
  4621. inpL = ggml_get_rows(ctx, tok_embd, lctx.inp_tokens);
  4622. } else {
  4623. #ifdef GGML_USE_MPI
  4624. GGML_ASSERT(false && "not implemented");
  4625. #endif
  4626. lctx.inp_embd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  4627. inpL = lctx.inp_embd;
  4628. ggml_set_input(lctx.inp_embd);
  4629. }
  4630. cb(inpL, "inp_embd", -1);
  4631. return inpL;
  4632. }
  4633. static void llm_build_kv_store(
  4634. struct ggml_context * ctx,
  4635. const llama_hparams & hparams,
  4636. const llama_kv_cache & kv,
  4637. struct ggml_cgraph * graph,
  4638. struct ggml_tensor * k_cur,
  4639. struct ggml_tensor * v_cur,
  4640. int64_t n_ctx,
  4641. int32_t n_tokens,
  4642. int32_t kv_head,
  4643. const llm_build_cb & cb,
  4644. int64_t il) {
  4645. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4646. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4647. GGML_ASSERT(kv.size == n_ctx);
  4648. // compute the transposed [n_tokens, n_embd] V matrix
  4649. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, ggml_reshape_2d(ctx, v_cur, n_embd_v_gqa, n_tokens));
  4650. //struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur); // TODO: reshape above is likely not needed
  4651. cb(v_cur_t, "v_cur_t", il);
  4652. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  4653. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  4654. cb(k_cache_view, "k_cache_view", il);
  4655. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  4656. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  4657. (kv_head)*ggml_element_size(kv.v_l[il]));
  4658. cb(v_cache_view, "v_cache_view", il);
  4659. // important: storing RoPE-ed version of K in the KV cache!
  4660. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  4661. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  4662. }
  4663. static struct ggml_tensor * llm_build_norm(
  4664. struct ggml_context * ctx,
  4665. struct ggml_tensor * cur,
  4666. const llama_hparams & hparams,
  4667. struct ggml_tensor * mw,
  4668. struct ggml_tensor * mb,
  4669. llm_norm_type type,
  4670. const llm_build_cb & cb,
  4671. int il) {
  4672. switch (type) {
  4673. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  4674. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  4675. }
  4676. if (mw || mb) {
  4677. cb(cur, "norm", il);
  4678. }
  4679. if (mw) {
  4680. cur = ggml_mul(ctx, cur, mw);
  4681. if (mb) {
  4682. cb(cur, "norm_w", il);
  4683. }
  4684. }
  4685. if (mb) {
  4686. cur = ggml_add(ctx, cur, mb);
  4687. }
  4688. return cur;
  4689. }
  4690. static struct ggml_tensor * llm_build_ffn(
  4691. struct ggml_context * ctx,
  4692. struct ggml_tensor * cur,
  4693. struct ggml_tensor * up,
  4694. struct ggml_tensor * up_b,
  4695. struct ggml_tensor * gate,
  4696. struct ggml_tensor * gate_b,
  4697. struct ggml_tensor * down,
  4698. struct ggml_tensor * down_b,
  4699. struct ggml_tensor * act_scales,
  4700. llm_ffn_op_type type_op,
  4701. llm_ffn_gate_type type_gate,
  4702. const llm_build_cb & cb,
  4703. int il) {
  4704. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  4705. cb(tmp, "ffn_up", il);
  4706. if (up_b) {
  4707. tmp = ggml_add(ctx, tmp, up_b);
  4708. cb(tmp, "ffn_up_b", il);
  4709. }
  4710. if (gate) {
  4711. switch (type_gate) {
  4712. case LLM_FFN_SEQ:
  4713. {
  4714. cur = ggml_mul_mat(ctx, gate, tmp);
  4715. cb(cur, "ffn_gate", il);
  4716. } break;
  4717. case LLM_FFN_PAR:
  4718. {
  4719. cur = ggml_mul_mat(ctx, gate, cur);
  4720. cb(cur, "ffn_gate", il);
  4721. } break;
  4722. }
  4723. if (gate_b) {
  4724. cur = ggml_add(ctx, cur, gate_b);
  4725. cb(cur, "ffn_gate_b", il);
  4726. }
  4727. } else {
  4728. cur = tmp;
  4729. }
  4730. switch (type_op) {
  4731. case LLM_FFN_SILU:
  4732. {
  4733. cur = ggml_silu(ctx, cur);
  4734. cb(cur, "ffn_silu", il);
  4735. } break;
  4736. case LLM_FFN_GELU:
  4737. {
  4738. cur = ggml_gelu(ctx, cur);
  4739. cb(cur, "ffn_gelu", il);
  4740. if (act_scales != NULL) {
  4741. cur = ggml_div(ctx, cur, act_scales);
  4742. cb(cur, "ffn_act", il);
  4743. }
  4744. } break;
  4745. case LLM_FFN_RELU:
  4746. {
  4747. cur = ggml_relu(ctx, cur);
  4748. cb(cur, "ffn_relu", il);
  4749. } break;
  4750. case LLM_FFN_RELU_SQR:
  4751. {
  4752. cur = ggml_relu(ctx, cur);
  4753. cb(cur, "ffn_relu", il);
  4754. cur = ggml_sqr(ctx, cur);
  4755. cb(cur, "ffn_sqr(relu)", il);
  4756. } break;
  4757. }
  4758. if (type_gate == LLM_FFN_PAR) {
  4759. cur = ggml_mul(ctx, cur, tmp);
  4760. cb(cur, "ffn_gate_par", il);
  4761. }
  4762. cur = ggml_mul_mat(ctx, down, cur);
  4763. if (down_b) {
  4764. cb(cur, "ffn_down", il);
  4765. }
  4766. if (down_b) {
  4767. cur = ggml_add(ctx, cur, down_b);
  4768. }
  4769. return cur;
  4770. }
  4771. // if max_alibi_bias > 0 then apply ALiBi
  4772. static struct ggml_tensor * llm_build_kqv(
  4773. struct ggml_context * ctx,
  4774. const llama_model & model,
  4775. const llama_hparams & hparams,
  4776. const llama_kv_cache & kv,
  4777. struct ggml_cgraph * graph,
  4778. struct ggml_tensor * wo,
  4779. struct ggml_tensor * wo_b,
  4780. struct ggml_tensor * q_cur,
  4781. struct ggml_tensor * kq_mask,
  4782. struct ggml_tensor * kq_pos,
  4783. int64_t n_ctx,
  4784. int32_t n_tokens,
  4785. int32_t n_kv,
  4786. float kq_scale,
  4787. const llm_build_cb & cb,
  4788. int il) {
  4789. const int64_t n_head = hparams.n_head;
  4790. const int64_t n_head_kv = hparams.n_head_kv;
  4791. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  4792. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4793. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  4794. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  4795. cb(q, "q", il);
  4796. struct ggml_tensor * k =
  4797. ggml_view_3d(ctx, kv.k_l[il],
  4798. n_embd_head_k, n_kv, n_head_kv,
  4799. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  4800. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  4801. 0);
  4802. cb(k, "k", il);
  4803. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  4804. cb(kq, "kq", il);
  4805. if (model.arch == LLM_ARCH_PHI2) {
  4806. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  4807. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  4808. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  4809. }
  4810. #if defined(GGML_USE_KOMPUTE)
  4811. #pragma message("TODO: ALiBi support in ggml_soft_max_ext is not implemented for Kompute")
  4812. #pragma message(" Falling back to ggml_alibi(). Will become an error in Mar 2024")
  4813. #pragma message("ref: https://github.com/ggerganov/llama.cpp/pull/5488")
  4814. if (hparams.f_max_alibi_bias > 0.0f) {
  4815. kq = ggml_scale(ctx, kq, kq_scale);
  4816. cb(kq, "kq_scaled", il);
  4817. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, hparams.f_max_alibi_bias);
  4818. cb(kq, "kq_scaled_alibi", il);
  4819. kq = ggml_add(ctx, kq, kq_mask);
  4820. cb(kq, "kq_masked", il);
  4821. kq = ggml_soft_max(ctx, kq);
  4822. cb(kq, "kq_soft_max", il);
  4823. } else
  4824. #endif
  4825. {
  4826. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_pos, kq_scale, hparams.f_max_alibi_bias);
  4827. cb(kq, "kq_soft_max_ext", il);
  4828. }
  4829. GGML_ASSERT(kv.size == n_ctx);
  4830. // split cached v into n_head heads
  4831. struct ggml_tensor * v =
  4832. ggml_view_3d(ctx, kv.v_l[il],
  4833. n_kv, n_embd_head_v, n_head_kv,
  4834. ggml_element_size(kv.v_l[il])*n_ctx,
  4835. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  4836. 0);
  4837. cb(v, "v", il);
  4838. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  4839. cb(kqv, "kqv", il);
  4840. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  4841. cb(kqv_merged, "kqv_merged", il);
  4842. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  4843. cb(cur, "kqv_merged_cont", il);
  4844. ggml_build_forward_expand(graph, cur);
  4845. cur = ggml_mul_mat(ctx, wo, cur);
  4846. if (wo_b) {
  4847. cb(cur, "kqv_wo", il);
  4848. }
  4849. if (wo_b) {
  4850. cur = ggml_add(ctx, cur, wo_b);
  4851. }
  4852. return cur;
  4853. }
  4854. static struct ggml_tensor * llm_build_kv(
  4855. struct ggml_context * ctx,
  4856. const llama_model & model,
  4857. const llama_hparams & hparams,
  4858. const llama_kv_cache & kv,
  4859. struct ggml_cgraph * graph,
  4860. struct ggml_tensor * wo,
  4861. struct ggml_tensor * wo_b,
  4862. struct ggml_tensor * k_cur,
  4863. struct ggml_tensor * v_cur,
  4864. struct ggml_tensor * q_cur,
  4865. struct ggml_tensor * kq_mask,
  4866. struct ggml_tensor * kq_pos,
  4867. int64_t n_ctx,
  4868. int32_t n_tokens,
  4869. int32_t kv_head,
  4870. int32_t n_kv,
  4871. float kq_scale,
  4872. const llm_build_cb & cb,
  4873. int il) {
  4874. // these nodes are added to the graph together so that they are not reordered
  4875. // by doing so, the number of splits in the graph is reduced
  4876. ggml_build_forward_expand(graph, q_cur);
  4877. ggml_build_forward_expand(graph, k_cur);
  4878. ggml_build_forward_expand(graph, v_cur);
  4879. llm_build_kv_store(ctx, hparams, kv, graph, k_cur, v_cur, n_ctx, n_tokens, kv_head, cb, il);
  4880. struct ggml_tensor * cur;
  4881. cur = llm_build_kqv(ctx, model, hparams, kv, graph, wo, wo_b,
  4882. q_cur, kq_mask, kq_pos, n_ctx, n_tokens, n_kv, kq_scale, cb, il);
  4883. cb(cur, "kqv_out", il);
  4884. return cur;
  4885. }
  4886. struct llm_build_context {
  4887. const llama_model & model;
  4888. llama_context & lctx;
  4889. const llama_hparams & hparams;
  4890. const llama_cparams & cparams;
  4891. const llama_batch & batch;
  4892. const llama_kv_cache & kv_self;
  4893. const int64_t n_embd;
  4894. const int64_t n_layer;
  4895. const int64_t n_rot;
  4896. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  4897. const int64_t n_head;
  4898. const int64_t n_head_kv;
  4899. const int64_t n_embd_head_k;
  4900. const int64_t n_embd_k_gqa;
  4901. const int64_t n_embd_head_v;
  4902. const int64_t n_embd_v_gqa;
  4903. const int64_t n_expert;
  4904. const int64_t n_expert_used;
  4905. const float freq_base;
  4906. const float freq_scale;
  4907. const float ext_factor;
  4908. const float attn_factor;
  4909. const float beta_fast;
  4910. const float beta_slow;
  4911. const float norm_eps;
  4912. const float norm_rms_eps;
  4913. const int32_t n_tokens;
  4914. const int32_t n_kv; // size of KV cache to consider (n_kv <= n_ctx)
  4915. const int32_t kv_head; // index of where we store new KV data in the cache
  4916. const int32_t n_orig_ctx;
  4917. const enum llama_pooling_type pooling_type;
  4918. const enum llama_rope_type rope_type;
  4919. const llm_build_cb & cb;
  4920. std::vector<uint8_t> & buf_compute_meta;
  4921. struct ggml_context * ctx0 = nullptr;
  4922. // TODO: consider making the entire interface noexcept
  4923. llm_build_context(
  4924. llama_context & lctx,
  4925. const llama_batch & batch,
  4926. const llm_build_cb & cb,
  4927. bool worst_case) :
  4928. model (lctx.model),
  4929. lctx (lctx),
  4930. hparams (model.hparams),
  4931. cparams (lctx.cparams),
  4932. batch (batch),
  4933. kv_self (lctx.kv_self),
  4934. n_embd (hparams.n_embd),
  4935. n_layer (hparams.n_layer),
  4936. n_rot (hparams.n_rot),
  4937. n_ctx (cparams.n_ctx),
  4938. n_head (hparams.n_head),
  4939. n_head_kv (hparams.n_head_kv),
  4940. n_embd_head_k (hparams.n_embd_head_k),
  4941. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  4942. n_embd_head_v (hparams.n_embd_head_v),
  4943. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  4944. n_expert (hparams.n_expert),
  4945. n_expert_used (hparams.n_expert_used),
  4946. freq_base (cparams.rope_freq_base),
  4947. freq_scale (cparams.rope_freq_scale),
  4948. ext_factor (cparams.yarn_ext_factor),
  4949. attn_factor (cparams.yarn_attn_factor),
  4950. beta_fast (cparams.yarn_beta_fast),
  4951. beta_slow (cparams.yarn_beta_slow),
  4952. norm_eps (hparams.f_norm_eps),
  4953. norm_rms_eps (hparams.f_norm_rms_eps),
  4954. n_tokens (batch.n_tokens),
  4955. n_kv (worst_case ? kv_self.size : kv_self.n),
  4956. kv_head (worst_case ? (kv_self.recurrent ? 0 : kv_self.size - n_tokens) : kv_self.head),
  4957. n_orig_ctx (cparams.n_yarn_orig_ctx),
  4958. pooling_type (cparams.pooling_type),
  4959. rope_type (hparams.rope_type),
  4960. cb (cb),
  4961. buf_compute_meta (lctx.buf_compute_meta) {
  4962. // all initializations should be done in init()
  4963. }
  4964. void init() {
  4965. struct ggml_init_params params = {
  4966. /*.mem_size =*/ buf_compute_meta.size(),
  4967. /*.mem_buffer =*/ buf_compute_meta.data(),
  4968. /*.no_alloc =*/ true,
  4969. };
  4970. ctx0 = ggml_init(params);
  4971. lctx.inp_tokens = nullptr;
  4972. lctx.inp_embd = nullptr;
  4973. lctx.inp_pos = nullptr;
  4974. lctx.inp_KQ_mask = nullptr;
  4975. lctx.inp_KQ_pos = nullptr;
  4976. lctx.inp_K_shift = nullptr;
  4977. lctx.inp_mean = nullptr;
  4978. lctx.inp_cls = nullptr;
  4979. lctx.inp_s_copy = nullptr;
  4980. lctx.inp_s_mask = nullptr;
  4981. lctx.inp_s_seq = nullptr;
  4982. }
  4983. void free() {
  4984. if (ctx0) {
  4985. ggml_free(ctx0);
  4986. ctx0 = nullptr;
  4987. }
  4988. }
  4989. struct ggml_cgraph * build_k_shift() {
  4990. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4991. GGML_ASSERT(kv_self.size == n_ctx);
  4992. lctx.inp_K_shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_ctx);
  4993. cb(lctx.inp_K_shift, "K_shift", -1);
  4994. ggml_set_input(lctx.inp_K_shift);
  4995. for (int il = 0; il < n_layer; ++il) {
  4996. struct ggml_tensor * tmp =
  4997. // we rotate only the first n_rot dimensions
  4998. ggml_rope_custom_inplace(ctx0,
  4999. ggml_view_3d(ctx0, kv_self.k_l[il],
  5000. n_embd_head_k, n_head_kv, n_ctx,
  5001. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  5002. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5003. 0),
  5004. lctx.inp_K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5005. ext_factor, attn_factor, beta_fast, beta_slow);
  5006. cb(tmp, "K_shifted", il);
  5007. ggml_build_forward_expand(gf, tmp);
  5008. }
  5009. return gf;
  5010. }
  5011. struct ggml_cgraph * build_s_copy() {
  5012. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5013. GGML_ASSERT(kv_self.recurrent);
  5014. struct ggml_tensor * state_copy = build_inp_s_copy();
  5015. for (int il = 0; il < n_layer; ++il) {
  5016. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  5017. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  5018. conv_states = ggml_get_rows(ctx0, conv_states, state_copy);
  5019. ssm_states = ggml_get_rows(ctx0, ssm_states, state_copy);
  5020. // TODO: name the intermediate tensors with cb()
  5021. ggml_build_forward_expand(gf, ggml_cpy(ctx0, conv_states, kv_self.k_l[il]));
  5022. ggml_build_forward_expand(gf, ggml_cpy(ctx0, ssm_states, kv_self.v_l[il]));
  5023. }
  5024. return gf;
  5025. }
  5026. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  5027. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5028. for (uint32_t i = 0; i < ids.size(); ++i) {
  5029. const uint32_t id = ids[i];
  5030. if (i == id || id == ids.size()) {
  5031. continue;
  5032. }
  5033. uint32_t nm = 1;
  5034. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  5035. nm++;
  5036. }
  5037. for (int il = 0; il < n_layer; ++il) {
  5038. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  5039. n_embd_k_gqa, nm,
  5040. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5041. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  5042. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  5043. n_embd_k_gqa, nm,
  5044. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5045. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  5046. ggml_tensor * view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  5047. nm, n_embd_v_gqa,
  5048. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  5049. ggml_row_size(kv_self.v_l[il]->type, i));
  5050. ggml_tensor * view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  5051. nm, n_embd_v_gqa,
  5052. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  5053. ggml_row_size(kv_self.v_l[il]->type, id));
  5054. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  5055. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  5056. }
  5057. i += nm - 1;
  5058. }
  5059. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  5060. return gf;
  5061. }
  5062. struct ggml_tensor * build_inp_pos() {
  5063. lctx.inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  5064. cb(lctx.inp_pos, "inp_pos", -1);
  5065. ggml_set_input(lctx.inp_pos);
  5066. return lctx.inp_pos;
  5067. }
  5068. struct ggml_tensor * build_inp_KQ_mask(bool causal = true) {
  5069. if (causal) {
  5070. lctx.inp_KQ_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, n_tokens);
  5071. } else {
  5072. lctx.inp_KQ_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  5073. }
  5074. cb(lctx.inp_KQ_mask, "KQ_mask", -1);
  5075. ggml_set_input(lctx.inp_KQ_mask);
  5076. return lctx.inp_KQ_mask;
  5077. }
  5078. struct ggml_tensor * build_inp_KQ_pos() {
  5079. lctx.inp_KQ_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_kv);
  5080. cb(lctx.inp_KQ_pos, "KQ_pos", -1);
  5081. ggml_set_input(lctx.inp_KQ_pos);
  5082. return lctx.inp_KQ_pos;
  5083. }
  5084. struct ggml_tensor * build_inp_mean() {
  5085. lctx.inp_mean = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  5086. cb(lctx.inp_mean, "inp_mean", -1);
  5087. ggml_set_input(lctx.inp_mean);
  5088. return lctx.inp_mean;
  5089. }
  5090. struct ggml_tensor * build_inp_cls() {
  5091. lctx.inp_cls = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  5092. cb(lctx.inp_cls, "inp_cls", -1);
  5093. ggml_set_input(lctx.inp_cls);
  5094. return lctx.inp_cls;
  5095. }
  5096. struct ggml_tensor * build_inp_s_copy() {
  5097. lctx.inp_s_copy = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, kv_self.size);
  5098. cb(lctx.inp_s_copy, "inp_s_copy", -1);
  5099. ggml_set_input(lctx.inp_s_copy);
  5100. return lctx.inp_s_copy;
  5101. }
  5102. struct ggml_tensor * build_inp_s_mask() {
  5103. lctx.inp_s_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_kv);
  5104. cb(lctx.inp_s_mask, "inp_s_mask", -1);
  5105. ggml_set_input(lctx.inp_s_mask);
  5106. return lctx.inp_s_mask;
  5107. }
  5108. struct ggml_tensor * build_inp_s_seq() {
  5109. lctx.inp_s_seq = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  5110. cb(lctx.inp_s_seq, "inp_s_seq", -1);
  5111. ggml_set_input(lctx.inp_s_seq);
  5112. return lctx.inp_s_seq;
  5113. }
  5114. struct ggml_cgraph * build_llama() {
  5115. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5116. const int64_t n_embd_head = hparams.n_embd_head_v;
  5117. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5118. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5119. struct ggml_tensor * cur;
  5120. struct ggml_tensor * inpL;
  5121. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5122. // inp_pos - contains the positions
  5123. struct ggml_tensor * inp_pos = build_inp_pos();
  5124. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5125. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5126. for (int il = 0; il < n_layer; ++il) {
  5127. struct ggml_tensor * inpSA = inpL;
  5128. // norm
  5129. cur = llm_build_norm(ctx0, inpL, hparams,
  5130. model.layers[il].attn_norm, NULL,
  5131. LLM_NORM_RMS, cb, il);
  5132. cb(cur, "attn_norm", il);
  5133. // self-attention
  5134. {
  5135. // compute Q and K and RoPE them
  5136. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5137. cb(Qcur, "Qcur", il);
  5138. if (model.layers[il].bq) {
  5139. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5140. cb(Qcur, "Qcur", il);
  5141. }
  5142. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5143. cb(Kcur, "Kcur", il);
  5144. if (model.layers[il].bk) {
  5145. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5146. cb(Kcur, "Kcur", il);
  5147. }
  5148. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5149. cb(Vcur, "Vcur", il);
  5150. if (model.layers[il].bv) {
  5151. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5152. cb(Vcur, "Vcur", il);
  5153. }
  5154. Qcur = ggml_rope_custom(
  5155. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5156. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5157. ext_factor, attn_factor, beta_fast, beta_slow
  5158. );
  5159. cb(Qcur, "Qcur", il);
  5160. Kcur = ggml_rope_custom(
  5161. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5162. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5163. ext_factor, attn_factor, beta_fast, beta_slow
  5164. );
  5165. cb(Kcur, "Kcur", il);
  5166. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5167. model.layers[il].wo, model.layers[il].bo,
  5168. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5169. }
  5170. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5171. cb(ffn_inp, "ffn_inp", il);
  5172. // feed-forward network
  5173. if (model.layers[il].ffn_gate_inp == nullptr) {
  5174. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5175. model.layers[il].ffn_norm, NULL,
  5176. LLM_NORM_RMS, cb, il);
  5177. cb(cur, "ffn_norm", il);
  5178. cur = llm_build_ffn(ctx0, cur,
  5179. model.layers[il].ffn_up, NULL,
  5180. model.layers[il].ffn_gate, NULL,
  5181. model.layers[il].ffn_down, NULL,
  5182. NULL,
  5183. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5184. cb(cur, "ffn_out", il);
  5185. } else {
  5186. // MoE branch
  5187. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5188. model.layers[il].ffn_norm, NULL,
  5189. LLM_NORM_RMS, cb, il);
  5190. cb(cur, "ffn_norm", il);
  5191. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  5192. cb(logits, "ffn_moe_logits", il);
  5193. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  5194. cb(probs, "ffn_moe_probs", il);
  5195. // select experts
  5196. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  5197. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  5198. ggml_tensor * weights = ggml_get_rows(ctx0,
  5199. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  5200. cb(weights, "ffn_moe_weights", il);
  5201. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  5202. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  5203. cb(weights_sum, "ffn_moe_weights_sum", il);
  5204. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  5205. cb(weights, "ffn_moe_weights_norm", il);
  5206. // compute expert outputs
  5207. ggml_tensor * moe_out = nullptr;
  5208. for (int i = 0; i < n_expert_used; ++i) {
  5209. ggml_tensor * cur_expert;
  5210. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  5211. cb(cur_up, "ffn_moe_up", il);
  5212. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  5213. cb(cur_gate, "ffn_moe_gate", il);
  5214. cur_gate = ggml_silu(ctx0, cur_gate);
  5215. cb(cur_gate, "ffn_moe_silu", il);
  5216. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  5217. cb(cur_expert, "ffn_moe_gate_par", il);
  5218. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  5219. cb(cur_expert, "ffn_moe_down", il);
  5220. cur_expert = ggml_mul(ctx0, cur_expert,
  5221. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  5222. cb(cur_expert, "ffn_moe_weighted", il);
  5223. if (i == 0) {
  5224. moe_out = cur_expert;
  5225. } else {
  5226. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  5227. cb(moe_out, "ffn_moe_out", il);
  5228. }
  5229. }
  5230. cur = moe_out;
  5231. }
  5232. cur = ggml_add(ctx0, cur, ffn_inp);
  5233. cb(cur, "ffn_out", il);
  5234. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  5235. if (layer_dir != nullptr) {
  5236. cur = ggml_add(ctx0, cur, layer_dir);
  5237. }
  5238. cb(cur, "l_out", il);
  5239. // input for next layer
  5240. inpL = cur;
  5241. }
  5242. cur = inpL;
  5243. cur = llm_build_norm(ctx0, cur, hparams,
  5244. model.output_norm, NULL,
  5245. LLM_NORM_RMS, cb, -1);
  5246. cb(cur, "result_norm", -1);
  5247. // lm_head
  5248. cur = ggml_mul_mat(ctx0, model.output, cur);
  5249. cb(cur, "result_output", -1);
  5250. ggml_build_forward_expand(gf, cur);
  5251. return gf;
  5252. }
  5253. struct ggml_cgraph * build_baichuan() {
  5254. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5255. const int64_t n_embd_head = hparams.n_embd_head_v;
  5256. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5257. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5258. struct ggml_tensor * cur;
  5259. struct ggml_tensor * inpL;
  5260. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5261. // inp_pos - contains the positions
  5262. struct ggml_tensor * inp_pos = model.type == MODEL_7B ? build_inp_pos() : nullptr;
  5263. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5264. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5265. // positions of the tokens in the KV cache
  5266. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  5267. for (int il = 0; il < n_layer; ++il) {
  5268. struct ggml_tensor * inpSA = inpL;
  5269. cur = llm_build_norm(ctx0, inpL, hparams,
  5270. model.layers[il].attn_norm, NULL,
  5271. LLM_NORM_RMS, cb, il);
  5272. cb(cur, "attn_norm", il);
  5273. // self-attention
  5274. {
  5275. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5276. cb(Qcur, "Qcur", il);
  5277. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5278. cb(Kcur, "Kcur", il);
  5279. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5280. cb(Vcur, "Vcur", il);
  5281. switch (model.type) {
  5282. case MODEL_7B:
  5283. Qcur = ggml_rope_custom(
  5284. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5285. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5286. ext_factor, attn_factor, beta_fast, beta_slow
  5287. );
  5288. Kcur = ggml_rope_custom(
  5289. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5290. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5291. ext_factor, attn_factor, beta_fast, beta_slow
  5292. );
  5293. break;
  5294. case MODEL_13B:
  5295. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  5296. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  5297. break;
  5298. default:
  5299. GGML_ASSERT(false);
  5300. }
  5301. cb(Qcur, "Qcur", il);
  5302. cb(Kcur, "Kcur", il);
  5303. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5304. model.layers[il].wo, NULL,
  5305. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5306. }
  5307. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5308. cb(ffn_inp, "ffn_inp", il);
  5309. // feed-forward network
  5310. {
  5311. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5312. model.layers[il].ffn_norm, NULL,
  5313. LLM_NORM_RMS, cb, il);
  5314. cb(cur, "ffn_norm", il);
  5315. cur = llm_build_ffn(ctx0, cur,
  5316. model.layers[il].ffn_up, NULL,
  5317. model.layers[il].ffn_gate, NULL,
  5318. model.layers[il].ffn_down, NULL,
  5319. NULL,
  5320. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5321. cb(cur, "ffn_out", il);
  5322. }
  5323. cur = ggml_add(ctx0, cur, ffn_inp);
  5324. cb(cur, "l_out", il);
  5325. // input for next layer
  5326. inpL = cur;
  5327. }
  5328. cur = inpL;
  5329. cur = llm_build_norm(ctx0, cur, hparams,
  5330. model.output_norm, NULL,
  5331. LLM_NORM_RMS, cb, -1);
  5332. cb(cur, "result_norm", -1);
  5333. // lm_head
  5334. cur = ggml_mul_mat(ctx0, model.output, cur);
  5335. cb(cur, "result_output", -1);
  5336. ggml_build_forward_expand(gf, cur);
  5337. return gf;
  5338. }
  5339. struct ggml_cgraph * build_falcon() {
  5340. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5341. const int64_t n_embd_head = hparams.n_embd_head_v;
  5342. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5343. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5344. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5345. struct ggml_tensor * cur;
  5346. struct ggml_tensor * inpL;
  5347. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5348. // inp_pos - contains the positions
  5349. struct ggml_tensor * inp_pos = build_inp_pos();
  5350. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5351. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5352. for (int il = 0; il < n_layer; ++il) {
  5353. struct ggml_tensor * attn_norm;
  5354. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  5355. model.layers[il].attn_norm,
  5356. model.layers[il].attn_norm_b,
  5357. LLM_NORM, cb, il);
  5358. cb(attn_norm, "attn_norm", il);
  5359. // self-attention
  5360. {
  5361. if (model.layers[il].attn_norm_2) {
  5362. // Falcon-40B
  5363. cur = llm_build_norm(ctx0, inpL, hparams,
  5364. model.layers[il].attn_norm_2,
  5365. model.layers[il].attn_norm_2_b,
  5366. LLM_NORM, cb, il);
  5367. cb(cur, "attn_norm_2", il);
  5368. } else {
  5369. cur = attn_norm;
  5370. }
  5371. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5372. cb(cur, "wqkv", il);
  5373. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5374. 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)));
  5375. 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)));
  5376. cb(Qcur, "Qcur", il);
  5377. cb(Kcur, "Kcur", il);
  5378. cb(Vcur, "Vcur", il);
  5379. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5380. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5381. // using mode = 2 for neox mode
  5382. Qcur = ggml_rope_custom(
  5383. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5384. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5385. );
  5386. cb(Qcur, "Qcur", il);
  5387. Kcur = ggml_rope_custom(
  5388. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5389. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5390. );
  5391. cb(Kcur, "Kcur", il);
  5392. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5393. model.layers[il].wo, NULL,
  5394. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5395. }
  5396. struct ggml_tensor * ffn_inp = cur;
  5397. // feed forward
  5398. {
  5399. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  5400. model.layers[il].ffn_up, NULL,
  5401. NULL, NULL,
  5402. model.layers[il].ffn_down, NULL,
  5403. NULL,
  5404. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5405. cb(cur, "ffn_out", il);
  5406. }
  5407. cur = ggml_add(ctx0, cur, ffn_inp);
  5408. cb(cur, "l_out", il);
  5409. cur = ggml_add(ctx0, cur, inpL);
  5410. cb(cur, "l_out", il);
  5411. // input for next layer
  5412. inpL = cur;
  5413. }
  5414. cur = inpL;
  5415. // norm
  5416. cur = llm_build_norm(ctx0, cur, hparams,
  5417. model.output_norm,
  5418. model.output_norm_b,
  5419. LLM_NORM, cb, -1);
  5420. cb(cur, "result_norm", -1);
  5421. cur = ggml_mul_mat(ctx0, model.output, cur);
  5422. cb(cur, "result_output", -1);
  5423. ggml_build_forward_expand(gf, cur);
  5424. return gf;
  5425. }
  5426. struct ggml_cgraph * build_starcoder() {
  5427. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5428. const int64_t n_embd_head = hparams.n_embd_head_v;
  5429. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5430. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5431. struct ggml_tensor * cur;
  5432. struct ggml_tensor * inpL;
  5433. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5434. // inp_pos - contains the positions
  5435. struct ggml_tensor * inp_pos = build_inp_pos();
  5436. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5437. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5438. struct ggml_tensor * pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  5439. cb(pos, "pos_embd", -1);
  5440. inpL = ggml_add(ctx0, inpL, pos);
  5441. cb(inpL, "inpL", -1);
  5442. for (int il = 0; il < n_layer; ++il) {
  5443. cur = llm_build_norm(ctx0, inpL, hparams,
  5444. model.layers[il].attn_norm,
  5445. model.layers[il].attn_norm_b,
  5446. LLM_NORM, cb, il);
  5447. cb(cur, "attn_norm", il);
  5448. // self-attention
  5449. {
  5450. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5451. cb(cur, "wqkv", il);
  5452. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5453. cb(cur, "bqkv", il);
  5454. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5455. 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)));
  5456. 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)));
  5457. cb(Qcur, "Qcur", il);
  5458. cb(Kcur, "Kcur", il);
  5459. cb(Vcur, "Vcur", il);
  5460. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5461. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5462. model.layers[il].wo, model.layers[il].bo,
  5463. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5464. }
  5465. // add the input
  5466. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5467. cb(ffn_inp, "ffn_inp", il);
  5468. // FF
  5469. {
  5470. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5471. model.layers[il].ffn_norm,
  5472. model.layers[il].ffn_norm_b,
  5473. LLM_NORM, cb, il);
  5474. cb(cur, "ffn_norm", il);
  5475. cur = llm_build_ffn(ctx0, cur,
  5476. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5477. NULL, NULL,
  5478. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5479. NULL,
  5480. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5481. cb(cur, "ffn_out", il);
  5482. }
  5483. inpL = ggml_add(ctx0, cur, ffn_inp);
  5484. cb(inpL, "l_out", il);
  5485. }
  5486. cur = llm_build_norm(ctx0, inpL, hparams,
  5487. model.output_norm,
  5488. model.output_norm_b,
  5489. LLM_NORM, cb, -1);
  5490. cb(cur, "result_norm", -1);
  5491. cur = ggml_mul_mat(ctx0, model.output, cur);
  5492. cb(cur, "result_output", -1);
  5493. ggml_build_forward_expand(gf, cur);
  5494. return gf;
  5495. }
  5496. struct ggml_cgraph * build_persimmon() {
  5497. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5498. const int64_t n_embd_head = hparams.n_embd_head_v;
  5499. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5500. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  5501. struct ggml_tensor * cur;
  5502. struct ggml_tensor * inpL;
  5503. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5504. // inp_pos - contains the positions
  5505. struct ggml_tensor * inp_pos = build_inp_pos();
  5506. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5507. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5508. for (int il = 0; il < n_layer; ++il) {
  5509. struct ggml_tensor * residual = inpL;
  5510. cur = llm_build_norm(ctx0, inpL, hparams,
  5511. model.layers[il].attn_norm,
  5512. model.layers[il].attn_norm_b,
  5513. LLM_NORM, cb, il);
  5514. cb(cur, "attn_norm", il);
  5515. // self attention
  5516. {
  5517. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5518. cb(cur, "wqkv", il);
  5519. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5520. cb(cur, "bqkv", il);
  5521. // split qkv
  5522. GGML_ASSERT(n_head_kv == n_head);
  5523. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  5524. cb(tmpqkv, "tmpqkv", il);
  5525. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  5526. cb(tmpqkv_perm, "tmpqkv", il);
  5527. struct ggml_tensor * tmpq = ggml_view_3d(
  5528. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  5529. ggml_element_size(tmpqkv_perm) * n_embd_head,
  5530. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  5531. 0
  5532. );
  5533. cb(tmpq, "tmpq", il);
  5534. struct ggml_tensor * tmpk = ggml_view_3d(
  5535. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  5536. ggml_element_size(tmpqkv_perm) * n_embd_head,
  5537. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  5538. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  5539. );
  5540. cb(tmpk, "tmpk", il);
  5541. // Q/K Layernorm
  5542. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  5543. model.layers[il].attn_q_norm,
  5544. model.layers[il].attn_q_norm_b,
  5545. LLM_NORM, cb, il);
  5546. cb(tmpq, "tmpq", il);
  5547. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  5548. model.layers[il].attn_k_norm,
  5549. model.layers[il].attn_k_norm_b,
  5550. LLM_NORM, cb, il);
  5551. cb(tmpk, "tmpk", il);
  5552. // RoPE the first n_rot of q/k, pass the other half, and concat.
  5553. struct ggml_tensor * qrot = ggml_view_3d(
  5554. ctx0, tmpq, n_rot, n_head, n_tokens,
  5555. ggml_element_size(tmpq) * n_embd_head,
  5556. ggml_element_size(tmpq) * n_embd_head * n_head,
  5557. 0
  5558. );
  5559. cb(qrot, "qrot", il);
  5560. struct ggml_tensor * krot = ggml_view_3d(
  5561. ctx0, tmpk, n_rot, n_head, n_tokens,
  5562. ggml_element_size(tmpk) * n_embd_head,
  5563. ggml_element_size(tmpk) * n_embd_head * n_head,
  5564. 0
  5565. );
  5566. cb(krot, "krot", il);
  5567. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  5568. struct ggml_tensor * qpass = ggml_view_3d(
  5569. ctx0, tmpq, n_rot, n_head, n_tokens,
  5570. ggml_element_size(tmpq) * n_embd_head,
  5571. ggml_element_size(tmpq) * n_embd_head * n_head,
  5572. ggml_element_size(tmpq) * n_rot
  5573. );
  5574. cb(qpass, "qpass", il);
  5575. struct ggml_tensor * kpass = ggml_view_3d(
  5576. ctx0, tmpk, n_rot, n_head, n_tokens,
  5577. ggml_element_size(tmpk) * n_embd_head,
  5578. ggml_element_size(tmpk) * n_embd_head * n_head,
  5579. ggml_element_size(tmpk) * n_rot
  5580. );
  5581. cb(kpass, "kpass", il);
  5582. struct ggml_tensor * qrotated = ggml_rope_custom(
  5583. ctx0, qrot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5584. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5585. );
  5586. cb(qrotated, "qrotated", il);
  5587. struct ggml_tensor * krotated = ggml_rope_custom(
  5588. ctx0, krot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5589. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5590. );
  5591. cb(krotated, "krotated", il);
  5592. // ggml currently only supports concatenation on dim=2
  5593. // so we need to permute qrot, qpass, concat, then permute back.
  5594. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  5595. cb(qrotated, "qrotated", il);
  5596. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  5597. cb(krotated, "krotated", il);
  5598. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  5599. cb(qpass, "qpass", il);
  5600. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  5601. cb(kpass, "kpass", il);
  5602. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  5603. cb(Qcur, "Qcur", il);
  5604. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  5605. cb(Kcur, "Kcur", il);
  5606. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  5607. cb(Q, "Q", il);
  5608. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  5609. cb(Kcur, "Kcur", il);
  5610. struct ggml_tensor * Vcur = ggml_view_3d(
  5611. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  5612. ggml_element_size(tmpqkv_perm) * n_embd_head,
  5613. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  5614. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  5615. );
  5616. cb(Vcur, "Vcur", il);
  5617. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5618. model.layers[il].wo, model.layers[il].bo,
  5619. Kcur, Vcur, Q, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5620. }
  5621. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  5622. cb(ffn_inp, "ffn_inp", il);
  5623. // feed-forward network
  5624. {
  5625. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5626. model.layers[il].ffn_norm,
  5627. model.layers[il].ffn_norm_b,
  5628. LLM_NORM, cb, il);
  5629. cb(cur, "ffn_norm", il);
  5630. cur = llm_build_ffn(ctx0, cur,
  5631. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5632. NULL, NULL,
  5633. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5634. NULL,
  5635. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  5636. cb(cur, "ffn_out", il);
  5637. }
  5638. cur = ggml_add(ctx0, cur, ffn_inp);
  5639. cb(cur, "l_out", il);
  5640. inpL = cur;
  5641. }
  5642. cur = inpL;
  5643. cur = llm_build_norm(ctx0, cur, hparams,
  5644. model.output_norm,
  5645. model.output_norm_b,
  5646. LLM_NORM, cb, -1);
  5647. cb(cur, "result_norm", -1);
  5648. cur = ggml_mul_mat(ctx0, model.output, cur);
  5649. cb(cur, "result_output", -1);
  5650. ggml_build_forward_expand(gf, cur);
  5651. return gf;
  5652. }
  5653. struct ggml_cgraph * build_refact() {
  5654. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5655. const int64_t n_embd_head = hparams.n_embd_head_v;
  5656. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5657. struct ggml_tensor * cur;
  5658. struct ggml_tensor * inpL;
  5659. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5660. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5661. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5662. // positions of the tokens in the KV cache
  5663. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  5664. for (int il = 0; il < n_layer; ++il) {
  5665. struct ggml_tensor * inpSA = inpL;
  5666. cur = llm_build_norm(ctx0, inpL, hparams,
  5667. model.layers[il].attn_norm, NULL,
  5668. LLM_NORM_RMS, cb, il);
  5669. cb(cur, "attn_norm", il);
  5670. // self-attention
  5671. {
  5672. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5673. cb(Qcur, "Qcur", il);
  5674. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5675. cb(Kcur, "Kcur", il);
  5676. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5677. cb(Vcur, "Vcur", il);
  5678. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5679. cb(Kcur, "Kcur", il);
  5680. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5681. cb(Qcur, "Qcur", il);
  5682. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5683. model.layers[il].wo, NULL,
  5684. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5685. }
  5686. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5687. cb(ffn_inp, "ffn_inp", il);
  5688. // feed-forward network
  5689. {
  5690. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5691. model.layers[il].ffn_norm, NULL,
  5692. LLM_NORM_RMS, cb, il);
  5693. cb(cur, "ffn_norm", il);
  5694. cur = llm_build_ffn(ctx0, cur,
  5695. model.layers[il].ffn_up, NULL,
  5696. model.layers[il].ffn_gate, NULL,
  5697. model.layers[il].ffn_down, NULL,
  5698. NULL,
  5699. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5700. cb(cur, "ffn_out", il);
  5701. }
  5702. cur = ggml_add(ctx0, cur, ffn_inp);
  5703. cb(cur, "l_out", il);
  5704. // input for next layer
  5705. inpL = cur;
  5706. }
  5707. cur = inpL;
  5708. cur = llm_build_norm(ctx0, cur, hparams,
  5709. model.output_norm, NULL,
  5710. LLM_NORM_RMS, cb, -1);
  5711. cb(cur, "result_norm", -1);
  5712. // lm_head
  5713. cur = ggml_mul_mat(ctx0, model.output, cur);
  5714. cb(cur, "result_output", -1);
  5715. ggml_build_forward_expand(gf, cur);
  5716. return gf;
  5717. }
  5718. struct ggml_cgraph * build_bert() {
  5719. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5720. const int64_t n_embd_head = hparams.n_embd_head_v;
  5721. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5722. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5723. struct ggml_tensor * cur;
  5724. struct ggml_tensor * inpL;
  5725. struct ggml_tensor * inp_pos = build_inp_pos();
  5726. struct ggml_tensor * inp_mean = build_inp_mean();
  5727. struct ggml_tensor * inp_cls = build_inp_cls();
  5728. // construct input embeddings (token, type, position)
  5729. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5730. // token types are hardcoded to zero ("Sentence A")
  5731. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  5732. inpL = ggml_add(ctx0, inpL, type_row0);
  5733. if (model.arch == LLM_ARCH_BERT) {
  5734. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  5735. }
  5736. cb(inpL, "inp_embd", -1);
  5737. // embed layer norm
  5738. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  5739. cb(inpL, "inp_norm", -1);
  5740. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5741. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(false);
  5742. // iterate layers
  5743. for (int il = 0; il < n_layer; ++il) {
  5744. struct ggml_tensor * cur = inpL;
  5745. struct ggml_tensor * Qcur;
  5746. struct ggml_tensor * Kcur;
  5747. struct ggml_tensor * Vcur;
  5748. // self-attention
  5749. if (model.arch == LLM_ARCH_BERT) {
  5750. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  5751. cb(Qcur, "Qcur", il);
  5752. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  5753. cb(Kcur, "Kcur", il);
  5754. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  5755. cb(Vcur, "Vcur", il);
  5756. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5757. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5758. } else {
  5759. // compute Q and K and RoPE them
  5760. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5761. cb(cur, "wqkv", il);
  5762. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5763. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5764. 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)));
  5765. cb(Qcur, "Qcur", il);
  5766. cb(Kcur, "Kcur", il);
  5767. cb(Vcur, "Vcur", il);
  5768. Qcur = ggml_rope_custom(
  5769. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5770. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5771. ext_factor, attn_factor, beta_fast, beta_slow
  5772. );
  5773. cb(Qcur, "Qcur", il);
  5774. Kcur = ggml_rope_custom(
  5775. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5776. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5777. ext_factor, attn_factor, beta_fast, beta_slow
  5778. );
  5779. cb(Kcur, "Kcur", il);
  5780. }
  5781. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  5782. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  5783. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  5784. cb(kq, "kq", il);
  5785. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask, nullptr, 1.0f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  5786. cb(kq, "kq_soft_max_ext", il);
  5787. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  5788. cb(v, "v", il);
  5789. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  5790. cb(kqv, "kqv", il);
  5791. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  5792. cb(kqv_merged, "kqv_merged", il);
  5793. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  5794. cb(cur, "kqv_merged_cont", il);
  5795. ggml_build_forward_expand(gf, cur);
  5796. cur = ggml_mul_mat(ctx0, model.layers[il].wo, cur);
  5797. if (model.layers[il].bo) {
  5798. cb(cur, "kqv_wo", il);
  5799. }
  5800. if (model.layers[il].bo) {
  5801. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  5802. }
  5803. cb(cur, "kqv_out", il);
  5804. // re-add the layer input
  5805. cur = ggml_add(ctx0, cur, inpL);
  5806. // attention layer norm
  5807. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  5808. struct ggml_tensor * ffn_inp = cur;
  5809. cb(ffn_inp, "ffn_inp", il);
  5810. // feed-forward network
  5811. if (model.arch == LLM_ARCH_BERT) {
  5812. cur = llm_build_ffn(ctx0, cur,
  5813. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5814. NULL, NULL,
  5815. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5816. NULL,
  5817. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5818. } else {
  5819. cur = llm_build_ffn(ctx0, cur,
  5820. model.layers[il].ffn_up, NULL,
  5821. model.layers[il].ffn_gate, NULL,
  5822. model.layers[il].ffn_down, NULL,
  5823. NULL,
  5824. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5825. }
  5826. cb(cur, "ffn_out", il);
  5827. // attentions bypass the intermediate layer
  5828. cur = ggml_add(ctx0, cur, ffn_inp);
  5829. // output layer norm
  5830. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  5831. // input for next layer
  5832. inpL = cur;
  5833. }
  5834. // final output
  5835. cur = inpL;
  5836. cb(cur, "result_embd", -1);
  5837. // pooling layer
  5838. switch (pooling_type) {
  5839. case LLAMA_POOLING_TYPE_NONE:
  5840. {
  5841. // nop
  5842. } break;
  5843. case LLAMA_POOLING_TYPE_MEAN:
  5844. {
  5845. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, cur)), inp_mean);
  5846. cb(cur, "result_embd_pooled", -1);
  5847. } break;
  5848. case LLAMA_POOLING_TYPE_CLS:
  5849. {
  5850. cur = ggml_get_rows(ctx0, cur, inp_cls);
  5851. cb(cur, "result_embd_pooled", -1);
  5852. } break;
  5853. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  5854. {
  5855. GGML_ASSERT(false && "Invalid pooling type");
  5856. } break;
  5857. }
  5858. ggml_build_forward_expand(gf, cur);
  5859. return gf;
  5860. }
  5861. struct ggml_cgraph * build_bloom() {
  5862. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5863. const int64_t n_embd_head = hparams.n_embd_head_v;
  5864. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5865. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5866. struct ggml_tensor * cur;
  5867. struct ggml_tensor * inpL;
  5868. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5869. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5870. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5871. // positions of the tokens in the KV cache
  5872. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  5873. inpL = llm_build_norm(ctx0, inpL, hparams,
  5874. model.tok_norm,
  5875. model.tok_norm_b,
  5876. LLM_NORM, cb, -1);
  5877. cb(inpL, "inp_norm", -1);
  5878. for (int il = 0; il < n_layer; ++il) {
  5879. cur = llm_build_norm(ctx0, inpL, hparams,
  5880. model.layers[il].attn_norm,
  5881. model.layers[il].attn_norm_b,
  5882. LLM_NORM, cb, il);
  5883. cb(cur, "attn_norm", il);
  5884. // self-attention
  5885. {
  5886. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5887. cb(cur, "wqkv", il);
  5888. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5889. cb(cur, "bqkv", il);
  5890. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5891. 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)));
  5892. 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)));
  5893. cb(Qcur, "Qcur", il);
  5894. cb(Kcur, "Kcur", il);
  5895. cb(Vcur, "Vcur", il);
  5896. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5897. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5898. model.layers[il].wo, model.layers[il].bo,
  5899. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5900. }
  5901. // Add the input
  5902. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5903. cb(ffn_inp, "ffn_inp", il);
  5904. // FF
  5905. {
  5906. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5907. model.layers[il].ffn_norm,
  5908. model.layers[il].ffn_norm_b,
  5909. LLM_NORM, cb, il);
  5910. cb(cur, "ffn_norm", il);
  5911. cur = llm_build_ffn(ctx0, cur,
  5912. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5913. NULL, NULL,
  5914. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5915. NULL,
  5916. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5917. cb(cur, "ffn_out", il);
  5918. }
  5919. inpL = ggml_add(ctx0, cur, ffn_inp);
  5920. cb(inpL, "l_out", il);
  5921. }
  5922. cur = llm_build_norm(ctx0, inpL, hparams,
  5923. model.output_norm,
  5924. model.output_norm_b,
  5925. LLM_NORM, cb, -1);
  5926. cb(cur, "result_norm", -1);
  5927. cur = ggml_mul_mat(ctx0, model.output, cur);
  5928. cb(cur, "result_output", -1);
  5929. ggml_build_forward_expand(gf, cur);
  5930. return gf;
  5931. }
  5932. struct ggml_cgraph * build_mpt() {
  5933. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5934. const int64_t n_embd_head = hparams.n_embd_head_v;
  5935. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5936. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5937. struct ggml_tensor * cur;
  5938. struct ggml_tensor * inpL;
  5939. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5940. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5941. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5942. // positions of the tokens in the KV cache
  5943. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  5944. for (int il = 0; il < n_layer; ++il) {
  5945. struct ggml_tensor * attn_norm;
  5946. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  5947. model.layers[il].attn_norm,
  5948. model.layers[il].attn_norm_b,
  5949. LLM_NORM, cb, il);
  5950. cb(attn_norm, "attn_norm", il);
  5951. // self-attention
  5952. {
  5953. cur = attn_norm;
  5954. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5955. cb(cur, "wqkv", il);
  5956. if (model.layers[il].bqkv){
  5957. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5958. cb(cur, "bqkv", il);
  5959. }
  5960. if (hparams.f_clamp_kqv > 0.0f) {
  5961. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  5962. cb(cur, "wqkv_clamped", il);
  5963. }
  5964. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5965. 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)));
  5966. 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)));
  5967. cb(Qcur, "Qcur", il);
  5968. cb(Kcur, "Kcur", il);
  5969. cb(Vcur, "Vcur", il);
  5970. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5971. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5972. model.layers[il].wo, model.layers[il].bo,
  5973. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5974. }
  5975. // Add the input
  5976. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5977. cb(ffn_inp, "ffn_inp", il);
  5978. // feed forward
  5979. {
  5980. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5981. model.layers[il].ffn_norm,
  5982. model.layers[il].ffn_norm_b,
  5983. LLM_NORM, cb, il);
  5984. cb(cur, "ffn_norm", il);
  5985. cur = llm_build_ffn(ctx0, cur,
  5986. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5987. NULL, NULL,
  5988. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5989. model.layers[il].ffn_act,
  5990. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5991. cb(cur, "ffn_out", il);
  5992. }
  5993. cur = ggml_add(ctx0, cur, ffn_inp);
  5994. cb(cur, "l_out", il);
  5995. // input for next layer
  5996. inpL = cur;
  5997. }
  5998. cur = inpL;
  5999. cur = llm_build_norm(ctx0, cur, hparams,
  6000. model.output_norm,
  6001. model.output_norm_b,
  6002. LLM_NORM, cb, -1);
  6003. cb(cur, "result_norm", -1);
  6004. cur = ggml_mul_mat(ctx0, model.output, cur);
  6005. cb(cur, "result_output", -1);
  6006. ggml_build_forward_expand(gf, cur);
  6007. return gf;
  6008. }
  6009. struct ggml_cgraph * build_stablelm() {
  6010. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  6011. const int64_t n_embd_head = hparams.n_embd_head_v;
  6012. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6013. struct ggml_tensor * cur;
  6014. struct ggml_tensor * inpL;
  6015. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6016. // inp_pos - contains the positions
  6017. struct ggml_tensor * inp_pos = build_inp_pos();
  6018. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6019. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6020. for (int il = 0; il < n_layer; ++il) {
  6021. struct ggml_tensor * inpSA = inpL;
  6022. // norm
  6023. cur = llm_build_norm(ctx0, inpL, hparams,
  6024. model.layers[il].attn_norm,
  6025. model.layers[il].attn_norm_b,
  6026. LLM_NORM, cb, il);
  6027. cb(cur, "attn_norm", il);
  6028. // self-attention
  6029. {
  6030. // compute Q and K and RoPE them
  6031. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6032. cb(Qcur, "Qcur", il);
  6033. if (model.layers[il].bq) {
  6034. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6035. cb(Qcur, "Qcur", il);
  6036. }
  6037. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6038. cb(Kcur, "Kcur", il);
  6039. if (model.layers[il].bk) {
  6040. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6041. cb(Kcur, "Kcur", il);
  6042. }
  6043. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6044. cb(Vcur, "Vcur", il);
  6045. if (model.layers[il].bv) {
  6046. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6047. cb(Vcur, "Vcur", il);
  6048. }
  6049. Qcur = ggml_rope_custom(
  6050. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6051. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6052. ext_factor, attn_factor, beta_fast, beta_slow
  6053. );
  6054. cb(Qcur, "Qcur", il);
  6055. Kcur = ggml_rope_custom(
  6056. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6057. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6058. ext_factor, attn_factor, beta_fast, beta_slow
  6059. );
  6060. cb(Kcur, "Kcur", il);
  6061. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6062. model.layers[il].wo, NULL,
  6063. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6064. }
  6065. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6066. cb(ffn_inp, "ffn_inp", il);
  6067. // feed-forward network
  6068. {
  6069. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6070. model.layers[il].ffn_norm,
  6071. model.layers[il].ffn_norm_b,
  6072. LLM_NORM, cb, il);
  6073. cb(cur, "ffn_norm", il);
  6074. cur = llm_build_ffn(ctx0, cur,
  6075. model.layers[il].ffn_up, NULL,
  6076. model.layers[il].ffn_gate, NULL,
  6077. model.layers[il].ffn_down, NULL,
  6078. NULL,
  6079. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6080. cb(cur, "ffn_out", il);
  6081. }
  6082. cur = ggml_add(ctx0, cur, ffn_inp);
  6083. cb(cur, "l_out", il);
  6084. // input for next layer
  6085. inpL = cur;
  6086. }
  6087. cur = inpL;
  6088. cur = llm_build_norm(ctx0, cur, hparams,
  6089. model.output_norm,
  6090. model.output_norm_b,
  6091. LLM_NORM, cb, -1);
  6092. cb(cur, "result_norm", -1);
  6093. // lm_head
  6094. cur = ggml_mul_mat(ctx0, model.output, cur);
  6095. cb(cur, "result_output", -1);
  6096. ggml_build_forward_expand(gf, cur);
  6097. return gf;
  6098. }
  6099. struct ggml_cgraph * build_qwen() {
  6100. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6101. const int64_t n_embd_head = hparams.n_embd_head_v;
  6102. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6103. struct ggml_tensor * cur;
  6104. struct ggml_tensor * inpL;
  6105. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6106. // inp_pos - contains the positions
  6107. struct ggml_tensor * inp_pos = build_inp_pos();
  6108. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6109. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6110. for (int il = 0; il < n_layer; ++il) {
  6111. struct ggml_tensor * inpSA = inpL;
  6112. cur = llm_build_norm(ctx0, inpL, hparams,
  6113. model.layers[il].attn_norm, NULL,
  6114. LLM_NORM_RMS, cb, il);
  6115. cb(cur, "attn_norm", il);
  6116. // self-attention
  6117. {
  6118. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6119. cb(cur, "wqkv", il);
  6120. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6121. cb(cur, "bqkv", il);
  6122. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6123. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6124. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  6125. cb(Qcur, "Qcur", il);
  6126. cb(Kcur, "Kcur", il);
  6127. cb(Vcur, "Vcur", il);
  6128. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6129. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6130. // using mode = 2 for neox mode
  6131. Qcur = ggml_rope_custom(
  6132. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6133. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6134. );
  6135. cb(Qcur, "Qcur", il);
  6136. Kcur = ggml_rope_custom(
  6137. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6138. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6139. );
  6140. cb(Kcur, "Kcur", il);
  6141. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6142. model.layers[il].wo, NULL,
  6143. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6144. }
  6145. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6146. cb(ffn_inp, "ffn_inp", il);
  6147. // feed-forward forward
  6148. {
  6149. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6150. model.layers[il].ffn_norm, NULL,
  6151. LLM_NORM_RMS, cb, il);
  6152. cb(cur, "ffn_norm", il);
  6153. cur = llm_build_ffn(ctx0, cur,
  6154. model.layers[il].ffn_up, NULL,
  6155. model.layers[il].ffn_gate, NULL,
  6156. model.layers[il].ffn_down, NULL,
  6157. NULL,
  6158. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6159. cb(cur, "ffn_out", il);
  6160. }
  6161. cur = ggml_add(ctx0, cur, ffn_inp);
  6162. cb(cur, "l_out", il);
  6163. // input for next layer
  6164. inpL = cur;
  6165. }
  6166. cur = inpL;
  6167. cur = llm_build_norm(ctx0, cur, hparams,
  6168. model.output_norm, NULL,
  6169. LLM_NORM_RMS, cb, -1);
  6170. cb(cur, "result_norm", -1);
  6171. // lm_head
  6172. cur = ggml_mul_mat(ctx0, model.output, cur);
  6173. cb(cur, "result_output", -1);
  6174. ggml_build_forward_expand(gf, cur);
  6175. return gf;
  6176. }
  6177. struct ggml_cgraph * build_qwen2() {
  6178. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6179. const int64_t n_embd_head = hparams.n_embd_head_v;
  6180. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6181. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6182. struct ggml_tensor * cur;
  6183. struct ggml_tensor * inpL;
  6184. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6185. // inp_pos - contains the positions
  6186. struct ggml_tensor * inp_pos = build_inp_pos();
  6187. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6188. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6189. for (int il = 0; il < n_layer; ++il) {
  6190. struct ggml_tensor * inpSA = inpL;
  6191. // norm
  6192. cur = llm_build_norm(ctx0, inpL, hparams,
  6193. model.layers[il].attn_norm, NULL,
  6194. LLM_NORM_RMS, cb, il);
  6195. cb(cur, "attn_norm", il);
  6196. // self-attention
  6197. {
  6198. // compute Q and K and RoPE them
  6199. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6200. cb(Qcur, "Qcur", il);
  6201. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6202. cb(Qcur, "Qcur", il);
  6203. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6204. cb(Kcur, "Kcur", il);
  6205. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6206. cb(Kcur, "Kcur", il);
  6207. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6208. cb(Vcur, "Vcur", il);
  6209. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6210. cb(Vcur, "Vcur", il);
  6211. // these nodes are added to the graph together so that they are not reordered
  6212. // by doing so, the number of splits in the graph is reduced
  6213. ggml_build_forward_expand(gf, Qcur);
  6214. ggml_build_forward_expand(gf, Kcur);
  6215. ggml_build_forward_expand(gf, Vcur);
  6216. Qcur = ggml_rope_custom(
  6217. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6218. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6219. ext_factor, attn_factor, beta_fast, beta_slow
  6220. );
  6221. cb(Qcur, "Qcur", il);
  6222. Kcur = ggml_rope_custom(
  6223. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6224. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6225. ext_factor, attn_factor, beta_fast, beta_slow
  6226. );
  6227. cb(Kcur, "Kcur", il);
  6228. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6229. model.layers[il].wo, model.layers[il].bo,
  6230. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6231. }
  6232. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6233. cb(ffn_inp, "ffn_inp", il);
  6234. // feed-forward network
  6235. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6236. model.layers[il].ffn_norm, NULL,
  6237. LLM_NORM_RMS, cb, il);
  6238. cb(cur, "ffn_norm", il);
  6239. cur = llm_build_ffn(ctx0, cur,
  6240. model.layers[il].ffn_up, NULL,
  6241. model.layers[il].ffn_gate, NULL,
  6242. model.layers[il].ffn_down, NULL,
  6243. NULL,
  6244. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6245. cb(cur, "ffn_out", il);
  6246. cur = ggml_add(ctx0, cur, ffn_inp);
  6247. cb(cur, "l_out", il);
  6248. // input for next layer
  6249. inpL = cur;
  6250. }
  6251. cur = inpL;
  6252. cur = llm_build_norm(ctx0, cur, hparams,
  6253. model.output_norm, NULL,
  6254. LLM_NORM_RMS, cb, -1);
  6255. cb(cur, "result_norm", -1);
  6256. // lm_head
  6257. cur = ggml_mul_mat(ctx0, model.output, cur);
  6258. cb(cur, "result_output", -1);
  6259. ggml_build_forward_expand(gf, cur);
  6260. return gf;
  6261. }
  6262. struct ggml_cgraph * build_phi2() {
  6263. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6264. const int64_t n_embd_head = hparams.n_embd_head_v;
  6265. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6266. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6267. struct ggml_tensor * cur;
  6268. struct ggml_tensor * attn_norm_output;
  6269. struct ggml_tensor * ffn_output;
  6270. struct ggml_tensor * inpL;
  6271. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6272. // inp_pos - contains the positions
  6273. struct ggml_tensor * inp_pos = build_inp_pos();
  6274. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6275. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6276. for (int il = 0; il < n_layer; ++il) {
  6277. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  6278. model.layers[il].attn_norm,
  6279. model.layers[il].attn_norm_b,
  6280. LLM_NORM, cb, il);
  6281. cb(attn_norm_output, "attn_norm", il);
  6282. // self-attention
  6283. {
  6284. struct ggml_tensor * Qcur = nullptr;
  6285. struct ggml_tensor * Kcur = nullptr;
  6286. struct ggml_tensor * Vcur = nullptr;
  6287. if (model.layers[il].wqkv) {
  6288. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  6289. cb(cur, "wqkv", il);
  6290. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6291. cb(cur, "bqkv", il);
  6292. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6293. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6294. 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)));
  6295. } else {
  6296. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  6297. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  6298. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  6299. }
  6300. cb(Qcur, "Qcur", il);
  6301. cb(Kcur, "Kcur", il);
  6302. cb(Vcur, "Vcur", il);
  6303. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6304. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6305. Qcur = ggml_rope_custom(
  6306. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6307. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6308. );
  6309. cb(Qcur, "Qcur", il);
  6310. // with phi2, we scale the Q to avoid precision issues
  6311. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  6312. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  6313. cb(Qcur, "Qcur", il);
  6314. Kcur = ggml_rope_custom(
  6315. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6316. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6317. );
  6318. cb(Kcur, "Kcur", il);
  6319. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6320. model.layers[il].wo, model.layers[il].bo,
  6321. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  6322. }
  6323. // FF
  6324. {
  6325. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  6326. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6327. NULL, NULL,
  6328. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6329. NULL,
  6330. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6331. cb(ffn_output, "ffn_out", il);
  6332. }
  6333. cur = ggml_add(ctx0, cur, ffn_output);
  6334. cb(cur, "l_out", il);
  6335. cur = ggml_add(ctx0, cur, inpL);
  6336. cb(cur, "l_out", il);
  6337. inpL = cur;
  6338. }
  6339. cur = llm_build_norm(ctx0, inpL, hparams,
  6340. model.output_norm,
  6341. model.output_norm_b,
  6342. LLM_NORM, cb, -1);
  6343. cb(cur, "result_norm", -1);
  6344. cur = ggml_mul_mat(ctx0, model.output, cur);
  6345. cb(cur, "result_output_no_bias", -1);
  6346. cur = ggml_add(ctx0, cur, model.output_b);
  6347. cb(cur, "result_output", -1);
  6348. ggml_build_forward_expand(gf, cur);
  6349. return gf;
  6350. }
  6351. struct ggml_cgraph * build_plamo() {
  6352. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  6353. const int64_t n_embd_head = hparams.n_embd_head_v;
  6354. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6355. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6356. struct ggml_tensor * cur;
  6357. struct ggml_tensor * inpL;
  6358. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6359. // inp_pos - contains the positions
  6360. struct ggml_tensor * inp_pos = build_inp_pos();
  6361. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6362. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6363. for (int il = 0; il < n_layer; ++il) {
  6364. // norm
  6365. cur = llm_build_norm(ctx0, inpL, hparams,
  6366. model.layers[il].attn_norm, NULL,
  6367. LLM_NORM_RMS, cb, il);
  6368. cb(cur, "attn_norm", il);
  6369. struct ggml_tensor * attention_norm = cur;
  6370. // self-attention
  6371. {
  6372. // compute Q and K and RoPE them
  6373. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6374. cb(Qcur, "Qcur", il);
  6375. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6376. cb(Kcur, "Kcur", il);
  6377. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6378. cb(Vcur, "Vcur", il);
  6379. Qcur = ggml_rope_custom(
  6380. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos,
  6381. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6382. ext_factor, attn_factor, beta_fast, beta_slow);
  6383. cb(Qcur, "Qcur", il);
  6384. Kcur = ggml_rope_custom(
  6385. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos,
  6386. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6387. ext_factor, attn_factor, beta_fast, beta_slow);
  6388. cb(Kcur, "Kcur", il);
  6389. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6390. model.layers[il].wo, NULL,
  6391. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6392. }
  6393. struct ggml_tensor * sa_out = cur;
  6394. cur = attention_norm;
  6395. // feed-forward network
  6396. {
  6397. cur = llm_build_ffn(ctx0, cur,
  6398. model.layers[il].ffn_up, NULL,
  6399. model.layers[il].ffn_gate, NULL,
  6400. model.layers[il].ffn_down, NULL,
  6401. NULL,
  6402. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6403. cb(cur, "ffn_out", il);
  6404. }
  6405. cur = ggml_add(ctx0, cur, sa_out);
  6406. cb(cur, "l_out", il);
  6407. cur = ggml_add(ctx0, cur, inpL);
  6408. cb(cur, "l_out", il);
  6409. // input for next layer
  6410. inpL = cur;
  6411. }
  6412. cur = inpL;
  6413. cur = llm_build_norm(ctx0, cur, hparams,
  6414. model.output_norm, NULL,
  6415. LLM_NORM_RMS, cb, -1);
  6416. cb(cur, "result_norm", -1);
  6417. // lm_head
  6418. cur = ggml_mul_mat(ctx0, model.output, cur);
  6419. cb(cur, "result_output", -1);
  6420. ggml_build_forward_expand(gf, cur);
  6421. return gf;
  6422. }
  6423. struct ggml_cgraph * build_gpt2() {
  6424. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6425. const int64_t n_embd_head = hparams.n_embd_head_v;
  6426. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6427. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6428. struct ggml_tensor * cur;
  6429. struct ggml_tensor * pos;
  6430. struct ggml_tensor * inpL;
  6431. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6432. // inp_pos - contains the positions
  6433. struct ggml_tensor * inp_pos = build_inp_pos();
  6434. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6435. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6436. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  6437. cb(pos, "pos_embd", -1);
  6438. inpL = ggml_add(ctx0, inpL, pos);
  6439. cb(inpL, "inpL", -1);
  6440. for (int il = 0; il < n_layer; ++il) {
  6441. cur = llm_build_norm(ctx0, inpL, hparams,
  6442. model.layers[il].attn_norm,
  6443. model.layers[il].attn_norm_b,
  6444. LLM_NORM, cb, il);
  6445. cb(cur, "attn_norm", il);
  6446. // self-attention
  6447. {
  6448. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6449. cb(cur, "wqkv", il);
  6450. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6451. cb(cur, "bqkv", il);
  6452. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6453. 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)));
  6454. 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)));
  6455. cb(Qcur, "Qcur", il);
  6456. cb(Kcur, "Kcur", il);
  6457. cb(Vcur, "Vcur", il);
  6458. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6459. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6460. model.layers[il].wo, model.layers[il].bo,
  6461. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6462. }
  6463. // add the input
  6464. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6465. cb(ffn_inp, "ffn_inp", il);
  6466. // FF
  6467. {
  6468. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6469. model.layers[il].ffn_norm,
  6470. model.layers[il].ffn_norm_b,
  6471. LLM_NORM, cb, il);
  6472. cb(cur, "ffn_norm", il);
  6473. cur = llm_build_ffn(ctx0, cur,
  6474. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6475. NULL, NULL,
  6476. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6477. NULL,
  6478. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6479. cb(cur, "ffn_out", il);
  6480. }
  6481. inpL = ggml_add(ctx0, cur, ffn_inp);
  6482. cb(inpL, "l_out", il);
  6483. }
  6484. cur = llm_build_norm(ctx0, inpL, hparams,
  6485. model.output_norm,
  6486. model.output_norm_b,
  6487. LLM_NORM, cb, -1);
  6488. cb(cur, "result_norm", -1);
  6489. cur = ggml_mul_mat(ctx0, model.output, cur);
  6490. cb(cur, "result_output", -1);
  6491. ggml_build_forward_expand(gf, cur);
  6492. return gf;
  6493. }
  6494. struct ggml_cgraph * build_codeshell() {
  6495. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6496. const int64_t n_embd_head = hparams.n_embd_head_v;
  6497. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6498. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6499. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6500. struct ggml_tensor * cur;
  6501. struct ggml_tensor * inpL;
  6502. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6503. // inp_pos - contains the positions
  6504. struct ggml_tensor * inp_pos = build_inp_pos();
  6505. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6506. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6507. for (int il = 0; il < n_layer; ++il) {
  6508. cur = llm_build_norm(ctx0, inpL, hparams,
  6509. model.layers[il].attn_norm,
  6510. model.layers[il].attn_norm_b,
  6511. LLM_NORM, cb, il);
  6512. cb(cur, "attn_norm", il);
  6513. // self-attention
  6514. {
  6515. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6516. cb(cur, "wqkv", il);
  6517. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6518. cb(cur, "bqkv", il);
  6519. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6520. struct ggml_tensor * tmpk = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6521. 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)));
  6522. cb(tmpq, "tmpq", il);
  6523. cb(tmpk, "tmpk", il);
  6524. cb(Vcur, "Vcur", il);
  6525. struct ggml_tensor * Qcur = ggml_rope_custom(
  6526. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  6527. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6528. ext_factor, attn_factor, beta_fast, beta_slow
  6529. );
  6530. cb(Qcur, "Qcur", il);
  6531. struct ggml_tensor * Kcur = ggml_rope_custom(
  6532. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6533. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6534. ext_factor, attn_factor, beta_fast, beta_slow
  6535. );
  6536. cb(Kcur, "Kcur", il);
  6537. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6538. model.layers[il].wo, model.layers[il].bo,
  6539. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6540. }
  6541. // add the input
  6542. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6543. cb(ffn_inp, "ffn_inp", il);
  6544. // FF
  6545. {
  6546. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6547. model.layers[il].ffn_norm,
  6548. model.layers[il].ffn_norm_b,
  6549. LLM_NORM, cb, il);
  6550. cb(cur, "ffn_norm", il);
  6551. cur = llm_build_ffn(ctx0, cur,
  6552. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6553. NULL, NULL,
  6554. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6555. NULL,
  6556. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6557. cb(cur, "ffn_out", il);
  6558. }
  6559. inpL = ggml_add(ctx0, cur, ffn_inp);
  6560. cb(inpL, "l_out", il);
  6561. }
  6562. cur = llm_build_norm(ctx0, inpL, hparams,
  6563. model.output_norm,
  6564. model.output_norm_b,
  6565. LLM_NORM, cb, -1);
  6566. cb(cur, "result_norm", -1);
  6567. cur = ggml_mul_mat(ctx0, model.output, cur);
  6568. cb(cur, "result_output", -1);
  6569. ggml_build_forward_expand(gf, cur);
  6570. return gf;
  6571. }
  6572. struct ggml_cgraph * build_orion() {
  6573. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6574. const int64_t n_embd_head = hparams.n_embd_head_v;
  6575. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6576. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6577. struct ggml_tensor * cur;
  6578. struct ggml_tensor * inpL;
  6579. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6580. // inp_pos - contains the positions
  6581. struct ggml_tensor * inp_pos = build_inp_pos();
  6582. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6583. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6584. for (int il = 0; il < n_layer; ++il) {
  6585. struct ggml_tensor * inpSA = inpL;
  6586. // norm
  6587. cur = llm_build_norm(ctx0, inpL, hparams,
  6588. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  6589. LLM_NORM, cb, il);
  6590. cb(cur, "attn_norm", il);
  6591. // self-attention
  6592. {
  6593. // compute Q and K and RoPE them
  6594. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6595. cb(Qcur, "Qcur", il);
  6596. // if (model.layers[il].bq) {
  6597. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6598. // cb(Qcur, "Qcur", il);
  6599. // }
  6600. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6601. cb(Kcur, "Kcur", il);
  6602. // if (model.layers[il].bk) {
  6603. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6604. // cb(Kcur, "Kcur", il);
  6605. // }
  6606. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6607. cb(Vcur, "Vcur", il);
  6608. // if (model.layers[il].bv) {
  6609. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6610. // cb(Vcur, "Vcur", il);
  6611. // }
  6612. Qcur = ggml_rope_custom(
  6613. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6614. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6615. ext_factor, attn_factor, beta_fast, beta_slow
  6616. );
  6617. cb(Qcur, "Qcur", il);
  6618. Kcur = ggml_rope_custom(
  6619. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6620. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6621. ext_factor, attn_factor, beta_fast, beta_slow
  6622. );
  6623. cb(Kcur, "Kcur", il);
  6624. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6625. model.layers[il].wo, NULL,
  6626. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6627. }
  6628. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6629. cb(ffn_inp, "ffn_inp", il);
  6630. // feed-forward network
  6631. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6632. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  6633. LLM_NORM, cb, il);
  6634. cb(cur, "ffn_norm", il);
  6635. cur = llm_build_ffn(ctx0, cur,
  6636. model.layers[il].ffn_up, NULL,
  6637. model.layers[il].ffn_gate, NULL,
  6638. model.layers[il].ffn_down, NULL,
  6639. NULL,
  6640. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6641. cb(cur, "ffn_out", il);
  6642. cur = ggml_add(ctx0, cur, ffn_inp);
  6643. cb(cur, "l_out", il);
  6644. // input for next layer
  6645. inpL = cur;
  6646. }
  6647. cur = inpL;
  6648. cur = llm_build_norm(ctx0, cur, hparams,
  6649. model.output_norm, model.output_norm_b,
  6650. LLM_NORM, cb, -1);
  6651. cb(cur, "result_norm", -1);
  6652. // lm_head
  6653. cur = ggml_mul_mat(ctx0, model.output, cur);
  6654. cb(cur, "result_output", -1);
  6655. ggml_build_forward_expand(gf, cur);
  6656. return gf;
  6657. }
  6658. struct ggml_cgraph * build_internlm2() {
  6659. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6660. const int64_t n_embd_head = hparams.n_embd_head_v;
  6661. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6662. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6663. struct ggml_tensor * cur;
  6664. struct ggml_tensor * inpL;
  6665. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6666. // inp_pos - contains the positions
  6667. struct ggml_tensor * inp_pos = build_inp_pos();
  6668. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6669. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6670. for (int il = 0; il < n_layer; ++il) {
  6671. struct ggml_tensor * inpSA = inpL;
  6672. // norm
  6673. cur = llm_build_norm(ctx0, inpL, hparams,
  6674. model.layers[il].attn_norm, NULL,
  6675. LLM_NORM_RMS, cb, il);
  6676. cb(cur, "attn_norm", il);
  6677. // self-attention
  6678. {
  6679. // compute Q and K and RoPE them
  6680. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6681. cb(Qcur, "Qcur", il);
  6682. if (model.layers[il].bq) {
  6683. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6684. cb(Qcur, "Qcur", il);
  6685. }
  6686. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6687. cb(Kcur, "Kcur", il);
  6688. if (model.layers[il].bk) {
  6689. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6690. cb(Kcur, "Kcur", il);
  6691. }
  6692. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6693. cb(Vcur, "Vcur", il);
  6694. if (model.layers[il].bv) {
  6695. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6696. cb(Vcur, "Vcur", il);
  6697. }
  6698. Qcur = ggml_rope_custom(
  6699. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6700. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6701. ext_factor, attn_factor, beta_fast, beta_slow
  6702. );
  6703. cb(Qcur, "Qcur", il);
  6704. Kcur = ggml_rope_custom(
  6705. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6706. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6707. ext_factor, attn_factor, beta_fast, beta_slow
  6708. );
  6709. cb(Kcur, "Kcur", il);
  6710. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6711. model.layers[il].wo, model.layers[il].bo,
  6712. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6713. }
  6714. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6715. cb(ffn_inp, "ffn_inp", il);
  6716. // feed-forward network
  6717. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6718. model.layers[il].ffn_norm, NULL,
  6719. LLM_NORM_RMS, cb, il);
  6720. cb(cur, "ffn_norm", il);
  6721. cur = llm_build_ffn(ctx0, cur,
  6722. model.layers[il].ffn_up, NULL,
  6723. model.layers[il].ffn_gate, NULL,
  6724. model.layers[il].ffn_down, NULL,
  6725. NULL,
  6726. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6727. cb(cur, "ffn_out", il);
  6728. cur = ggml_add(ctx0, cur, ffn_inp);
  6729. cb(cur, "l_out", il);
  6730. // input for next layer
  6731. inpL = cur;
  6732. }
  6733. cur = inpL;
  6734. cur = llm_build_norm(ctx0, cur, hparams,
  6735. model.output_norm, NULL,
  6736. LLM_NORM_RMS, cb, -1);
  6737. cb(cur, "result_norm", -1);
  6738. // lm_head
  6739. cur = ggml_mul_mat(ctx0, model.output, cur);
  6740. cb(cur, "result_output", -1);
  6741. ggml_build_forward_expand(gf, cur);
  6742. return gf;
  6743. }
  6744. // ref: https://arxiv.org/abs/2203.03466
  6745. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  6746. // based on the original build_llama() function
  6747. struct ggml_cgraph * build_minicpm() {
  6748. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6749. const int64_t n_embd_head = hparams.n_embd_head_v;
  6750. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6751. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6752. const int64_t n_embd = hparams.n_embd;
  6753. //TODO: if the model varies, these parameters need to be read from the model
  6754. const int64_t n_embd_base = 256;
  6755. const float scale_embd = 12.0f;
  6756. const float scale_depth = 1.4f;
  6757. struct ggml_tensor * cur;
  6758. struct ggml_tensor * inpL;
  6759. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6760. // scale the input embeddings
  6761. inpL = ggml_scale(ctx0, inpL, scale_embd);
  6762. cb(inpL, "inp_scaled", -1);
  6763. // inp_pos - contains the positions
  6764. struct ggml_tensor * inp_pos = build_inp_pos();
  6765. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6766. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6767. for (int il = 0; il < n_layer; ++il) {
  6768. struct ggml_tensor * inpSA = inpL;
  6769. // norm
  6770. cur = llm_build_norm(ctx0, inpL, hparams,
  6771. model.layers[il].attn_norm, NULL,
  6772. LLM_NORM_RMS, cb, il);
  6773. cb(cur, "attn_norm", il);
  6774. // self-attention
  6775. {
  6776. // compute Q and K and RoPE them
  6777. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6778. cb(Qcur, "Qcur", il);
  6779. if (model.layers[il].bq) {
  6780. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6781. cb(Qcur, "Qcur", il);
  6782. }
  6783. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6784. cb(Kcur, "Kcur", il);
  6785. if (model.layers[il].bk) {
  6786. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6787. cb(Kcur, "Kcur", il);
  6788. }
  6789. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6790. cb(Vcur, "Vcur", il);
  6791. if (model.layers[il].bv) {
  6792. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6793. cb(Vcur, "Vcur", il);
  6794. }
  6795. Qcur = ggml_rope_custom(
  6796. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6797. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6798. ext_factor, attn_factor, beta_fast, beta_slow
  6799. );
  6800. cb(Qcur, "Qcur", il);
  6801. Kcur = ggml_rope_custom(
  6802. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6803. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6804. ext_factor, attn_factor, beta_fast, beta_slow
  6805. );
  6806. cb(Kcur, "Kcur", il);
  6807. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6808. model.layers[il].wo, model.layers[il].bo,
  6809. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6810. }
  6811. // scale_res - scale the hidden states for residual connection
  6812. const float scale_res = scale_depth/sqrtf(float(n_layer));
  6813. cur = ggml_scale(ctx0, cur, scale_res);
  6814. cb(cur, "hidden_scaled", -1);
  6815. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6816. cb(ffn_inp, "ffn_inp", il);
  6817. // feed-forward network
  6818. {
  6819. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6820. model.layers[il].ffn_norm, NULL,
  6821. LLM_NORM_RMS, cb, il);
  6822. cb(cur, "ffn_norm", il);
  6823. cur = llm_build_ffn(ctx0, cur,
  6824. model.layers[il].ffn_up, NULL,
  6825. model.layers[il].ffn_gate, NULL,
  6826. model.layers[il].ffn_down, NULL,
  6827. NULL,
  6828. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6829. cb(cur, "ffn_out", il);
  6830. }
  6831. // scale the hidden states for residual connection
  6832. cur = ggml_scale(ctx0, cur, scale_res);
  6833. cb(cur, "hidden_scaled_ffn", -1);
  6834. cur = ggml_add(ctx0, cur, ffn_inp);
  6835. cb(cur, "l_out", il);
  6836. // input for next layer
  6837. inpL = cur;
  6838. }
  6839. cur = inpL;
  6840. cur = llm_build_norm(ctx0, cur, hparams,
  6841. model.output_norm, NULL,
  6842. LLM_NORM_RMS, cb, -1);
  6843. cb(cur, "result_norm", -1);
  6844. // lm_head scaling
  6845. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  6846. cur = ggml_scale(ctx0, cur, scale_lmhead);
  6847. cb(cur, "lmhead_scaling", -1);
  6848. // lm_head
  6849. cur = ggml_mul_mat(ctx0, model.tok_embd, cur);
  6850. cb(cur, "result_output", -1);
  6851. ggml_build_forward_expand(gf, cur);
  6852. return gf;
  6853. }
  6854. struct ggml_cgraph * build_gemma() {
  6855. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6856. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  6857. struct ggml_tensor * cur;
  6858. struct ggml_tensor * inpL;
  6859. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6860. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  6861. cb(inpL, "inp_scaled", -1);
  6862. // inp_pos - contains the positions
  6863. struct ggml_tensor * inp_pos = build_inp_pos();
  6864. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6865. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6866. for (int il = 0; il < n_layer; ++il) {
  6867. // norm
  6868. cur = llm_build_norm(ctx0, inpL, hparams,
  6869. model.layers[il].attn_norm, NULL,
  6870. LLM_NORM_RMS, cb, il);
  6871. cb(cur, "attn_norm", il);
  6872. // self-attention
  6873. {
  6874. // compute Q and K and RoPE them
  6875. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6876. cb(Qcur, "Qcur", il);
  6877. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6878. cb(Kcur, "Kcur", il);
  6879. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6880. cb(Vcur, "Vcur", il);
  6881. Qcur = ggml_rope_custom(
  6882. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos,
  6883. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6884. ext_factor, attn_factor, beta_fast, beta_slow);
  6885. cb(Qcur, "Qcur", il);
  6886. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  6887. cb(Qcur, "Qcur_scaled", il);
  6888. Kcur = ggml_rope_custom(
  6889. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos,
  6890. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6891. ext_factor, attn_factor, beta_fast, beta_slow);
  6892. cb(Kcur, "Kcur", il);
  6893. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6894. model.layers[il].wo, NULL,
  6895. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  6896. }
  6897. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  6898. cb(sa_out, "sa_out", il);
  6899. cur = llm_build_norm(ctx0, sa_out, hparams,
  6900. model.layers[il].ffn_norm, NULL,
  6901. LLM_NORM_RMS, cb, il);
  6902. cb(cur, "ffn_norm", il);
  6903. // feed-forward network
  6904. {
  6905. cur = llm_build_ffn(ctx0, cur,
  6906. model.layers[il].ffn_up, NULL,
  6907. model.layers[il].ffn_gate, NULL,
  6908. model.layers[il].ffn_down, NULL,
  6909. NULL,
  6910. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  6911. cb(cur, "ffn_out", il);
  6912. }
  6913. cur = ggml_add(ctx0, cur, sa_out);
  6914. cb(cur, "l_out", il);
  6915. // input for next layer
  6916. inpL = cur;
  6917. }
  6918. cur = inpL;
  6919. cur = llm_build_norm(ctx0, cur, hparams,
  6920. model.output_norm, NULL,
  6921. LLM_NORM_RMS, cb, -1);
  6922. cb(cur, "result_norm", -1);
  6923. // lm_head
  6924. cur = ggml_mul_mat(ctx0, model.output, cur);
  6925. cb(cur, "result_output", -1);
  6926. ggml_build_forward_expand(gf, cur);
  6927. return gf;
  6928. }
  6929. struct ggml_cgraph * build_starcoder2() {
  6930. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6931. const int64_t n_embd_head = hparams.n_embd_head_v;
  6932. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6933. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6934. struct ggml_tensor * cur;
  6935. struct ggml_tensor * inpL;
  6936. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6937. // inp_pos - contains the positions
  6938. struct ggml_tensor * inp_pos = build_inp_pos();
  6939. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6940. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6941. for (int il = 0; il < n_layer; ++il) {
  6942. struct ggml_tensor * inpSA = inpL;
  6943. // norm
  6944. cur = llm_build_norm(ctx0, inpL, hparams,
  6945. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  6946. LLM_NORM, cb, il);
  6947. cb(cur, "attn_norm", il);
  6948. // self-attention
  6949. {
  6950. // compute Q and K and RoPE them
  6951. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6952. cb(Qcur, "Qcur", il);
  6953. if (model.layers[il].bq) {
  6954. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6955. cb(Qcur, "Qcur", il);
  6956. }
  6957. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6958. cb(Kcur, "Kcur", il);
  6959. if (model.layers[il].bk) {
  6960. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6961. cb(Kcur, "Kcur", il);
  6962. }
  6963. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6964. cb(Vcur, "Vcur", il);
  6965. if (model.layers[il].bv) {
  6966. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6967. cb(Vcur, "Vcur", il);
  6968. }
  6969. Qcur = ggml_rope_custom(
  6970. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6971. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6972. ext_factor, attn_factor, beta_fast, beta_slow
  6973. );
  6974. cb(Qcur, "Qcur", il);
  6975. Kcur = ggml_rope_custom(
  6976. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6977. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6978. ext_factor, attn_factor, beta_fast, beta_slow
  6979. );
  6980. cb(Kcur, "Kcur", il);
  6981. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6982. model.layers[il].wo, model.layers[il].bo,
  6983. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6984. }
  6985. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6986. cb(ffn_inp, "ffn_inp", il);
  6987. // feed-forward network
  6988. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6989. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  6990. LLM_NORM, cb, il);
  6991. cb(cur, "ffn_norm", il);
  6992. cur = llm_build_ffn(ctx0, cur,
  6993. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6994. NULL, NULL,
  6995. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6996. NULL,
  6997. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6998. cb(cur, "ffn_out", il);
  6999. cur = ggml_add(ctx0, cur, ffn_inp);
  7000. cb(cur, "l_out", il);
  7001. // input for next layer
  7002. inpL = cur;
  7003. }
  7004. cur = inpL;
  7005. cur = llm_build_norm(ctx0, cur, hparams,
  7006. model.output_norm, model.output_norm_b,
  7007. LLM_NORM, cb, -1);
  7008. cb(cur, "result_norm", -1);
  7009. // lm_head
  7010. cur = ggml_mul_mat(ctx0, model.output, cur);
  7011. cb(cur, "result_output", -1);
  7012. ggml_build_forward_expand(gf, cur);
  7013. return gf;
  7014. }
  7015. struct ggml_cgraph * build_mamba() {
  7016. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7017. const int64_t d_model = n_embd;
  7018. const int64_t d_conv = hparams.ssm_d_conv;
  7019. const int64_t d_inner = hparams.ssm_d_inner;
  7020. GGML_ASSERT(2 * d_model == d_inner);
  7021. const int64_t d_state = hparams.ssm_d_state;
  7022. const int64_t dt_rank = hparams.ssm_dt_rank;
  7023. struct ggml_tensor * cur;
  7024. struct ggml_tensor * inpL;
  7025. // {n_embd, n_tokens}
  7026. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7027. struct ggml_tensor * state_mask = build_inp_s_mask();
  7028. struct ggml_tensor * state_seq = build_inp_s_seq();
  7029. for (int il = 0; il < n_layer; ++il) {
  7030. // (ab)using the KV cache to store the states
  7031. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  7032. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  7033. // clear states of sequences which are starting at the beginning of this batch
  7034. {
  7035. conv_states = ggml_mul(ctx0,
  7036. ggml_view_2d(ctx0, conv_states, conv_states->ne[0], n_kv, conv_states->nb[1], kv_head*conv_states->nb[1]),
  7037. state_mask);
  7038. ssm_states = ggml_mul(ctx0,
  7039. ggml_view_2d(ctx0, ssm_states, ssm_states->ne[0], n_kv, ssm_states->nb[1], kv_head*ssm_states->nb[1]),
  7040. state_mask);
  7041. }
  7042. conv_states = ggml_reshape_3d(ctx0, conv_states, d_conv - 1, d_inner, n_kv);
  7043. ssm_states = ggml_reshape_3d(ctx0, ssm_states, d_state, d_inner, n_kv);
  7044. // norm
  7045. cur = llm_build_norm(ctx0, inpL, hparams,
  7046. model.layers[il].attn_norm, NULL,
  7047. LLM_NORM_RMS, cb, il);
  7048. cb(cur, "attn_norm", il);
  7049. // {n_embd, 2*d_inner} * {n_embd, n_tokens} => {2*d_inner, n_tokens}
  7050. struct ggml_tensor * xz = ggml_mul_mat(ctx0, model.layers[il].ssm_in, cur);
  7051. // split the above in two
  7052. // => {d_inner, n_tokens}
  7053. struct ggml_tensor * x = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], 0);
  7054. struct ggml_tensor * z = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], ggml_element_size(xz)*d_inner);
  7055. // conv
  7056. {
  7057. // Custom operator which is needed only to ease simultaneous sequence processing.
  7058. // For a single sequence, the equivalent is to concatenate the columns of conv_states and x,
  7059. // then make a self-overlapping view of that over d_conv columns at each stride in the 3rd dimension,
  7060. // then element-wise multiply that with the conv1d weigth,
  7061. // then sum the elements of each row,
  7062. // (the last two steps are a dot product over rows (also doable with mul_mat))
  7063. // then permute away the ne[0] dimension,
  7064. // and then you're left with the resulting x tensor.
  7065. // The new conv_states is the last (d_conv - 1) columns
  7066. // of the last 3rd dimensional "layer" of the self-overlapping view.
  7067. // For simultaneous sequences, it's more complicated.
  7068. struct ggml_tensor * x_conv = ggml_ssm_conv(ctx0, conv_states, x, model.layers[il].ssm_conv1d, state_seq);
  7069. // store last (d_conv - 1) columns of the conv_state part of x_conv back into the KV cache
  7070. ggml_build_forward_expand(gf,
  7071. ggml_cpy(ctx0,
  7072. ggml_view_2d(ctx0, x_conv, d_conv - 1, d_inner*n_kv, d_conv*ggml_element_size(x_conv), (1+d_inner*n_tokens)*ggml_element_size(x_conv)),
  7073. ggml_view_1d(ctx0, kv_self.k_l[il], (d_conv - 1)*(d_inner)*(n_kv), kv_head*(d_conv - 1)*(d_inner)*ggml_element_size(x_conv))));
  7074. // extract x from x_conv
  7075. x = ggml_view_2d(ctx0, x_conv, d_inner, n_tokens, d_inner*ggml_element_size(x_conv), 0);
  7076. // bias
  7077. x = ggml_add(ctx0, x, model.layers[il].ssm_conv1d_b);
  7078. x = ggml_silu(ctx0, x);
  7079. }
  7080. // ssm
  7081. {
  7082. // {d_inner, dt_rank + 2*d_state} * {d_inner, n_tokens} => {dt_rank + 2*d_state, n_tokens}
  7083. struct ggml_tensor * x_db = ggml_mul_mat(ctx0, model.layers[il].ssm_x, x);
  7084. // split
  7085. struct ggml_tensor * dt = ggml_view_2d(ctx0, x_db, dt_rank, n_tokens, x_db->nb[1], 0);
  7086. struct ggml_tensor * B = ggml_view_2d(ctx0, x_db, d_state, n_tokens, x_db->nb[1], ggml_element_size(x_db)*dt_rank);
  7087. struct ggml_tensor * C = ggml_view_2d(ctx0, x_db, d_state, n_tokens, x_db->nb[1], ggml_element_size(x_db)*(dt_rank+d_state));
  7088. // {dt_rank, d_inner} * {dt_rank, n_tokens} => {d_inner, n_tokens}
  7089. dt = ggml_mul_mat(ctx0, model.layers[il].ssm_dt, dt);
  7090. dt = ggml_add(ctx0, dt, model.layers[il].ssm_dt_b);
  7091. // Custom operator to optimize the parallel associative scan
  7092. // as described in the Annex D of the Mamba paper.
  7093. // => {d_inner, n_tokens} and {d_state, d_inner, n_kv} combined,
  7094. // because only a single tensor can be returned.
  7095. struct ggml_tensor * y_ssm_states = ggml_ssm_scan(ctx0, ssm_states, x, dt, model.layers[il].ssm_a, B, C, state_seq);
  7096. // store last states (the second part of y_ssm_states)
  7097. ggml_build_forward_expand(gf,
  7098. ggml_cpy(ctx0,
  7099. ggml_view_1d(ctx0, y_ssm_states, d_state*d_inner*n_kv, d_inner*n_tokens*ggml_element_size(y_ssm_states)),
  7100. ggml_view_1d(ctx0, kv_self.v_l[il], d_state*d_inner*n_kv, kv_head*d_state*d_inner*ggml_element_size(ssm_states))));
  7101. struct ggml_tensor * y = ggml_view_2d(ctx0, y_ssm_states, d_inner, n_tokens, d_inner*ggml_element_size(y_ssm_states), 0);
  7102. // {d_inner, n_tokens} * {d_inner} => {d_inner, n_tokens}
  7103. y = ggml_add(ctx0, y, ggml_mul(ctx0, x, model.layers[il].ssm_d));
  7104. y = ggml_mul(ctx0, y, ggml_silu(ctx0, z));
  7105. // {d_inner, n_embd} * {d_inner, n_tokens} => {n_embd, n_tokens}
  7106. cur = ggml_mul_mat(ctx0, model.layers[il].ssm_out, y);
  7107. }
  7108. // residual
  7109. cur = ggml_add(ctx0, cur, inpL);
  7110. cb(cur, "l_out", il);
  7111. // input for next layer
  7112. inpL = cur;
  7113. }
  7114. // final rmsnorm
  7115. cur = llm_build_norm(ctx0, inpL, hparams,
  7116. model.output_norm, NULL,
  7117. LLM_NORM_RMS, cb, -1);
  7118. cb(cur, "result_norm", -1);
  7119. // lm_head
  7120. cur = ggml_mul_mat(ctx0, model.output, cur);
  7121. cb(cur, "result_output", -1);
  7122. ggml_build_forward_expand(gf, cur);
  7123. return gf;
  7124. }
  7125. struct ggml_cgraph * build_command_r() {
  7126. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7127. const int64_t n_embd_head = hparams.n_embd_head_v;
  7128. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7129. const float f_logit_scale = hparams.f_logit_scale;
  7130. struct ggml_tensor * cur;
  7131. struct ggml_tensor * inpL;
  7132. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7133. // inp_pos - contains the positions
  7134. struct ggml_tensor * inp_pos = build_inp_pos();
  7135. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7136. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7137. for (int il = 0; il < n_layer; ++il) {
  7138. // norm
  7139. cur = llm_build_norm(ctx0, inpL, hparams,
  7140. model.layers[il].attn_norm, NULL,
  7141. LLM_NORM, cb, il);
  7142. cb(cur, "attn_norm", il);
  7143. struct ggml_tensor * ffn_inp = cur;
  7144. // self-attention
  7145. {
  7146. // compute Q and K and RoPE them
  7147. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7148. cb(Qcur, "Qcur", il);
  7149. if (model.layers[il].bq) {
  7150. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7151. cb(Qcur, "Qcur", il);
  7152. }
  7153. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7154. cb(Kcur, "Kcur", il);
  7155. if (model.layers[il].bk) {
  7156. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7157. cb(Kcur, "Kcur", il);
  7158. }
  7159. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7160. cb(Vcur, "Vcur", il);
  7161. if (model.layers[il].bv) {
  7162. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7163. cb(Vcur, "Vcur", il);
  7164. }
  7165. Qcur = ggml_rope_custom(
  7166. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7167. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7168. ext_factor, attn_factor, beta_fast, beta_slow
  7169. );
  7170. cb(Qcur, "Qcur", il);
  7171. Kcur = ggml_rope_custom(
  7172. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7173. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7174. ext_factor, attn_factor, beta_fast, beta_slow
  7175. );
  7176. cb(Kcur, "Kcur", il);
  7177. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7178. model.layers[il].wo, model.layers[il].bo,
  7179. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7180. }
  7181. struct ggml_tensor * attn_out = cur;
  7182. // feed-forward network
  7183. {
  7184. cur = llm_build_ffn(ctx0, ffn_inp,
  7185. model.layers[il].ffn_up, NULL,
  7186. model.layers[il].ffn_gate, NULL,
  7187. model.layers[il].ffn_down, NULL,
  7188. NULL,
  7189. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7190. cb(cur, "ffn_out", il);
  7191. }
  7192. // add together residual + FFN + self-attention
  7193. cur = ggml_add(ctx0, cur, inpL);
  7194. cur = ggml_add(ctx0, cur, attn_out);
  7195. cb(cur, "l_out", il);
  7196. // input for next layer
  7197. inpL = cur;
  7198. }
  7199. cur = inpL;
  7200. cur = llm_build_norm(ctx0, cur, hparams,
  7201. model.output_norm, NULL,
  7202. LLM_NORM, cb, -1);
  7203. cb(cur, "result_norm", -1);
  7204. // lm_head
  7205. cur = ggml_mul_mat(ctx0, model.output, cur);
  7206. if (f_logit_scale) {
  7207. cur = ggml_scale(ctx0, cur, f_logit_scale);
  7208. }
  7209. cb(cur, "result_output", -1);
  7210. ggml_build_forward_expand(gf, cur);
  7211. return gf;
  7212. }
  7213. };
  7214. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  7215. llama_batch dummy;
  7216. dummy.n_tokens = 0;
  7217. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  7218. struct llm_build_context llm(lctx, dummy, cb, false);
  7219. llm.init();
  7220. struct ggml_cgraph * result = llm.build_defrag(ids);
  7221. llm.free();
  7222. return result;
  7223. }
  7224. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  7225. llama_batch dummy;
  7226. dummy.n_tokens = 0;
  7227. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  7228. struct llm_build_context llm(lctx, dummy, cb, false);
  7229. llm.init();
  7230. struct ggml_cgraph * result = llm.build_k_shift();
  7231. llm.free();
  7232. return result;
  7233. }
  7234. static struct ggml_cgraph * llama_build_graph_s_copy(llama_context & lctx) {
  7235. llama_batch dummy;
  7236. dummy.n_tokens = 0;
  7237. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  7238. struct llm_build_context llm(lctx, dummy, cb, false);
  7239. llm.init();
  7240. struct ggml_cgraph * result = llm.build_s_copy();
  7241. llm.free();
  7242. return result;
  7243. }
  7244. static struct ggml_cgraph * llama_build_graph(
  7245. llama_context & lctx,
  7246. const llama_batch & batch,
  7247. bool worst_case) {
  7248. const auto & model = lctx.model;
  7249. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  7250. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  7251. if (il >= 0) {
  7252. ggml_format_name(cur, "%s-%d", name, il);
  7253. } else {
  7254. ggml_set_name(cur, name);
  7255. }
  7256. if (!lctx.cparams.offload_kqv) {
  7257. if (strcmp(name, "kqv_merged_cont") == 0) {
  7258. // all nodes between the KV store and the attention output are run on the CPU
  7259. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, lctx.backend_cpu);
  7260. }
  7261. }
  7262. // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
  7263. // FIXME: fix in ggml_backend_sched
  7264. const bool full_offload = lctx.model.n_gpu_layers > (int)lctx.model.hparams.n_layer;
  7265. if (batch.n_tokens < 32 || full_offload) {
  7266. if (il != -1 && strcmp(name, "norm") == 0) {
  7267. for (auto * backend : lctx.backends) {
  7268. if (ggml_backend_buft_supports_backend(lctx.model.buft_layer[il].buft, backend)) {
  7269. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, backend);
  7270. break;
  7271. }
  7272. }
  7273. }
  7274. }
  7275. };
  7276. struct ggml_cgraph * result = NULL;
  7277. struct llm_build_context llm(lctx, batch, cb, worst_case);
  7278. llm.init();
  7279. switch (model.arch) {
  7280. case LLM_ARCH_LLAMA:
  7281. {
  7282. result = llm.build_llama();
  7283. } break;
  7284. case LLM_ARCH_BAICHUAN:
  7285. {
  7286. result = llm.build_baichuan();
  7287. } break;
  7288. case LLM_ARCH_FALCON:
  7289. {
  7290. result = llm.build_falcon();
  7291. } break;
  7292. case LLM_ARCH_STARCODER:
  7293. {
  7294. result = llm.build_starcoder();
  7295. } break;
  7296. case LLM_ARCH_PERSIMMON:
  7297. {
  7298. result = llm.build_persimmon();
  7299. } break;
  7300. case LLM_ARCH_REFACT:
  7301. {
  7302. result = llm.build_refact();
  7303. } break;
  7304. case LLM_ARCH_BERT:
  7305. case LLM_ARCH_NOMIC_BERT:
  7306. {
  7307. result = llm.build_bert();
  7308. } break;
  7309. case LLM_ARCH_BLOOM:
  7310. {
  7311. result = llm.build_bloom();
  7312. } break;
  7313. case LLM_ARCH_MPT:
  7314. {
  7315. result = llm.build_mpt();
  7316. } break;
  7317. case LLM_ARCH_STABLELM:
  7318. {
  7319. result = llm.build_stablelm();
  7320. } break;
  7321. case LLM_ARCH_QWEN:
  7322. {
  7323. result = llm.build_qwen();
  7324. } break;
  7325. case LLM_ARCH_QWEN2:
  7326. {
  7327. result = llm.build_qwen2();
  7328. } break;
  7329. case LLM_ARCH_PHI2:
  7330. {
  7331. result = llm.build_phi2();
  7332. } break;
  7333. case LLM_ARCH_PLAMO:
  7334. {
  7335. result = llm.build_plamo();
  7336. } break;
  7337. case LLM_ARCH_GPT2:
  7338. {
  7339. result = llm.build_gpt2();
  7340. } break;
  7341. case LLM_ARCH_CODESHELL:
  7342. {
  7343. result = llm.build_codeshell();
  7344. } break;
  7345. case LLM_ARCH_ORION:
  7346. {
  7347. result = llm.build_orion();
  7348. } break;
  7349. case LLM_ARCH_INTERNLM2:
  7350. {
  7351. result = llm.build_internlm2();
  7352. } break;
  7353. case LLM_ARCH_MINICPM:
  7354. {
  7355. result = llm.build_minicpm();
  7356. } break;
  7357. case LLM_ARCH_GEMMA:
  7358. {
  7359. result = llm.build_gemma();
  7360. } break;
  7361. case LLM_ARCH_STARCODER2:
  7362. {
  7363. result = llm.build_starcoder2();
  7364. } break;
  7365. case LLM_ARCH_MAMBA:
  7366. {
  7367. result = llm.build_mamba();
  7368. } break;
  7369. case LLM_ARCH_COMMAND_R:
  7370. {
  7371. result = llm.build_command_r();
  7372. } break;
  7373. default:
  7374. GGML_ASSERT(false);
  7375. }
  7376. llm.free();
  7377. return result;
  7378. }
  7379. static void llama_set_k_shift(llama_context & lctx) {
  7380. const int64_t kv_size = lctx.kv_self.size;
  7381. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  7382. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  7383. for (int i = 0; i < kv_size; ++i) {
  7384. data[i] = lctx.kv_self.cells[i].delta;
  7385. }
  7386. }
  7387. static void llama_set_s_copy(llama_context & lctx) {
  7388. const int64_t kv_size = lctx.kv_self.size;
  7389. assert(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  7390. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  7391. for (int i = 0; i < kv_size; ++i) {
  7392. data[i] = lctx.kv_self.cells[i].src;
  7393. }
  7394. }
  7395. static void llama_set_inputs(llama_context & lctx, const llama_batch & batch) {
  7396. //
  7397. // set input data
  7398. //
  7399. const auto & hparams = lctx.model.hparams;
  7400. const auto & cparams = lctx.cparams;
  7401. const auto & kv_self = lctx.kv_self;
  7402. if (batch.token) {
  7403. const int64_t n_tokens = batch.n_tokens;
  7404. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  7405. }
  7406. if (batch.embd) {
  7407. const int64_t n_embd = hparams.n_embd;
  7408. const int64_t n_tokens = batch.n_tokens;
  7409. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  7410. }
  7411. if (batch.pos && lctx.inp_pos) {
  7412. const int64_t n_tokens = batch.n_tokens;
  7413. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  7414. }
  7415. GGML_ASSERT(
  7416. (hparams.causal_attn || !cparams.causal_attn) &&
  7417. "non-causal attention with generative models is not supported"
  7418. );
  7419. if (lctx.inp_KQ_mask) {
  7420. // NOTE: hparams.causal_attn indicates the model is capable of generation and uses the kv cache.
  7421. if (cparams.causal_attn) {
  7422. const int64_t n_kv = kv_self.n;
  7423. const int64_t n_tokens = batch.n_tokens;
  7424. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  7425. float * data = (float *) lctx.inp_KQ_mask->data;
  7426. // For causal attention, use only the previous KV cells
  7427. // of the correct sequence for each token of the batch.
  7428. // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
  7429. for (int h = 0; h < 1; ++h) {
  7430. for (int j = 0; j < n_tokens; ++j) {
  7431. const llama_pos pos = batch.pos[j];
  7432. const llama_seq_id seq_id = batch.seq_id[j][0];
  7433. for (int i = 0; i < n_kv; ++i) {
  7434. float f;
  7435. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  7436. f = -INFINITY;
  7437. } else {
  7438. f = 0.0f;
  7439. }
  7440. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  7441. }
  7442. }
  7443. }
  7444. } else {
  7445. // when using kv cache, the mask needs to match the kv cache size
  7446. const int64_t n_tokens = batch.n_tokens;
  7447. const int64_t n_stride = hparams.causal_attn ? kv_self.n : n_tokens;
  7448. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  7449. float * data = (float *) lctx.inp_KQ_mask->data;
  7450. for (int h = 0; h < 1; ++h) {
  7451. for (int j = 0; j < n_tokens; ++j) {
  7452. const llama_seq_id seq_id = batch.seq_id[j][0];
  7453. for (int i = 0; i < n_tokens; ++i) {
  7454. float f = -INFINITY;
  7455. for (int s = 0; s < batch.n_seq_id[i]; ++s) {
  7456. if (batch.seq_id[i][s] == seq_id) {
  7457. f = 0.0f;
  7458. break;
  7459. }
  7460. }
  7461. data[h*(n_tokens*n_tokens) + j*n_stride + i] = f;
  7462. }
  7463. for (int i = n_tokens; i < n_stride; ++i) {
  7464. data[h*(n_tokens*n_tokens) + j*n_stride + i] = -INFINITY;
  7465. }
  7466. }
  7467. }
  7468. }
  7469. }
  7470. if (hparams.need_kq_pos) {
  7471. const int64_t n_kv = kv_self.n;
  7472. GGML_ASSERT(lctx.inp_KQ_pos);
  7473. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_pos->buffer));
  7474. float * data = (float *) lctx.inp_KQ_pos->data;
  7475. for (int i = 0; i < n_kv; ++i) {
  7476. data[i] = float(lctx.kv_self.cells[i].pos);
  7477. }
  7478. }
  7479. if (cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  7480. const int64_t n_tokens = batch.n_tokens;
  7481. GGML_ASSERT(lctx.inp_mean);
  7482. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  7483. float * data = (float *) lctx.inp_mean->data;
  7484. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  7485. std::vector<uint64_t> sum(n_tokens, 0);
  7486. for (int i = 0; i < n_tokens; ++i) {
  7487. const llama_seq_id seq_id = batch.seq_id[i][0];
  7488. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
  7489. sum[seq_id] += 1;
  7490. }
  7491. std::vector<float> div(n_tokens, 0.0f);
  7492. for (int i = 0; i < n_tokens; ++i) {
  7493. const uint64_t s = sum[i];
  7494. if (s > 0) {
  7495. div[i] = 1.0f/float(s);
  7496. }
  7497. }
  7498. for (int i = 0; i < n_tokens; ++i) {
  7499. const llama_seq_id seq_id = batch.seq_id[i][0];
  7500. data[seq_id*n_tokens + i] = div[seq_id];
  7501. }
  7502. }
  7503. if (cparams.pooling_type == LLAMA_POOLING_TYPE_CLS) {
  7504. const int64_t n_tokens = batch.n_tokens;
  7505. GGML_ASSERT(lctx.inp_cls);
  7506. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  7507. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  7508. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  7509. for (int i = 0; i < n_tokens; ++i) {
  7510. const llama_seq_id seq_id = batch.seq_id[i][0];
  7511. const llama_pos pos = batch.pos[i];
  7512. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS");
  7513. if (pos == 0) {
  7514. data[seq_id] = i;
  7515. }
  7516. }
  7517. }
  7518. if (kv_self.recurrent) {
  7519. const int64_t n_kv = kv_self.n;
  7520. if (lctx.inp_s_mask) {
  7521. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_mask->buffer));
  7522. float * data = (float *) lctx.inp_s_mask->data;
  7523. // states which are not affected by the current batch are left untouched
  7524. for (int i = 0; i < n_kv; ++i) {
  7525. llama_seq_id seq_id = i + lctx.kv_self.head;
  7526. llama_kv_cell & kv_cell = lctx.kv_self.cells[seq_id];
  7527. bool has_self_seq = kv_cell.has_seq_id(seq_id);
  7528. data[i] = (float) has_self_seq;
  7529. // ensure current sequences will be kept
  7530. if (!has_self_seq && kv_cell.pos >= 0) {
  7531. kv_cell.seq_id.insert(seq_id);
  7532. }
  7533. }
  7534. }
  7535. // For Mamba (and other recurrent architectures),
  7536. // update the correct state(s)/sequence(s) for each token of the batch.
  7537. // Like with the KQ_mask, if a token in the batch has multiple sequences,
  7538. // they are assumed to be equivalent (not here, but in ggml_ssm_scan and ggml_ssm_conv).
  7539. if (lctx.inp_s_seq) {
  7540. const int64_t n_tokens = batch.n_tokens;
  7541. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_seq->buffer));
  7542. int32_t * data = (int32_t *) lctx.inp_s_seq->data;
  7543. for (int j = 0; j < n_tokens; ++j) {
  7544. const int32_t n_seq = batch.n_seq_id[j];
  7545. GGML_ASSERT(0 < n_seq); // a token should be part of at least 1 sequence
  7546. for (int i = 0; i < n_kv; ++i) {
  7547. if (i < n_seq) {
  7548. // for this type of model, the head is the minimum seq_id of the batch
  7549. data[j*n_kv + i] = batch.seq_id[j][i] - kv_self.head;
  7550. } else {
  7551. data[j*n_kv + i] = -1;
  7552. }
  7553. }
  7554. }
  7555. }
  7556. }
  7557. }
  7558. static void llama_graph_compute(
  7559. llama_context & lctx,
  7560. ggml_cgraph * gf,
  7561. int n_threads) {
  7562. #ifdef GGML_USE_MPI
  7563. const int64_t n_layer = lctx.model.hparams.n_layer;
  7564. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  7565. #endif
  7566. #ifdef GGML_USE_METAL
  7567. if (ggml_backend_is_metal(lctx.backend_metal)) {
  7568. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  7569. }
  7570. #endif
  7571. if (lctx.backend_cpu != nullptr) {
  7572. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  7573. ggml_backend_cpu_set_abort_callback(lctx.backend_cpu, lctx.abort_callback, lctx.abort_callback_data);
  7574. }
  7575. ggml_backend_sched_graph_compute_async(lctx.sched, gf);
  7576. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  7577. #ifdef GGML_USE_MPI
  7578. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  7579. #endif
  7580. }
  7581. // decode a batch of tokens by evaluating the transformer
  7582. //
  7583. // - lctx: llama context
  7584. // - batch: batch to evaluate
  7585. //
  7586. // return 0 on success
  7587. // return positive int on warning
  7588. // return negative int on error
  7589. //
  7590. static int llama_decode_internal(
  7591. llama_context & lctx,
  7592. llama_batch batch_all) { // TODO: rename back to batch
  7593. const uint32_t n_tokens_all = batch_all.n_tokens;
  7594. if (n_tokens_all == 0) {
  7595. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  7596. return -1;
  7597. }
  7598. const auto & model = lctx.model;
  7599. const auto & hparams = model.hparams;
  7600. const auto & cparams = lctx.cparams;
  7601. GGML_ASSERT((!batch_all.token && batch_all.embd) || (batch_all.token && !batch_all.embd)); // NOLINT
  7602. GGML_ASSERT(n_tokens_all <= cparams.n_batch);
  7603. GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
  7604. if (lctx.t_compute_start_us == 0) {
  7605. lctx.t_compute_start_us = ggml_time_us();
  7606. }
  7607. lctx.n_queued_tokens += n_tokens_all;
  7608. #ifdef GGML_USE_MPI
  7609. // TODO: needs fix after #3228
  7610. GGML_ASSERT(false && "not implemented");
  7611. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  7612. #endif
  7613. auto & kv_self = lctx.kv_self;
  7614. const int64_t n_embd = hparams.n_embd;
  7615. const int64_t n_vocab = hparams.n_vocab;
  7616. auto * logits_out = lctx.logits;
  7617. #ifndef NDEBUG
  7618. auto & logits_valid = lctx.logits_valid;
  7619. logits_valid.clear();
  7620. logits_valid.resize(n_tokens_all);
  7621. memset(logits_out, 0, lctx.logits_size*sizeof(float));
  7622. #endif
  7623. const auto n_ubatch = cparams.n_ubatch;
  7624. std::vector<llama_pos> pos;
  7625. std::vector<int32_t> n_seq_id;
  7626. std::vector<llama_seq_id *> seq_id_arr;
  7627. std::vector<std::vector<llama_seq_id>> seq_id;
  7628. for (uint32_t cur_token = 0; cur_token < n_tokens_all; cur_token += n_ubatch) {
  7629. const uint32_t n_tokens = std::min(n_ubatch, n_tokens_all - cur_token);
  7630. llama_batch u_batch = {
  7631. /* .n_tokens = */ (int32_t) n_tokens,
  7632. /* .token = */ batch_all.token ? batch_all.token + cur_token : nullptr,
  7633. /* .embd = */ batch_all.embd ? batch_all.embd + cur_token*n_embd : nullptr,
  7634. /* .pos = */ batch_all.pos ? batch_all.pos + cur_token : nullptr,
  7635. /* .n_seq_id = */ batch_all.n_seq_id ? batch_all.n_seq_id + cur_token : nullptr,
  7636. /* .seq_id = */ batch_all.seq_id ? batch_all.seq_id + cur_token : nullptr,
  7637. /* .logits = */ batch_all.logits ? batch_all.logits + cur_token : nullptr,
  7638. /* .all_pos_0 = */ batch_all.all_pos_0 + (llama_pos) cur_token*batch_all.all_pos_1,
  7639. /* .all_pos_1 = */ batch_all.all_pos_1,
  7640. /* .all_seq_id = */ batch_all.all_seq_id,
  7641. };
  7642. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  7643. GGML_ASSERT(n_threads > 0);
  7644. // helpers for smoother batch API transition
  7645. // after deprecating the llama_eval calls, these will be removed
  7646. if (u_batch.pos == nullptr) {
  7647. pos.resize(n_tokens);
  7648. for (uint32_t i = 0; i < n_tokens; i++) {
  7649. pos[i] = u_batch.all_pos_0 + i*u_batch.all_pos_1;
  7650. }
  7651. u_batch.pos = pos.data();
  7652. }
  7653. if (u_batch.seq_id == nullptr) {
  7654. n_seq_id.resize(n_tokens);
  7655. seq_id.resize(n_tokens);
  7656. seq_id_arr.resize(n_tokens);
  7657. for (uint32_t i = 0; i < n_tokens; i++) {
  7658. n_seq_id[i] = 1;
  7659. seq_id[i].resize(1);
  7660. seq_id[i][0] = u_batch.all_seq_id;
  7661. seq_id_arr[i] = seq_id[i].data();
  7662. }
  7663. u_batch.n_seq_id = n_seq_id.data();
  7664. u_batch.seq_id = seq_id_arr.data();
  7665. }
  7666. // non-causal masks do not use the KV cache
  7667. if (hparams.causal_attn) {
  7668. llama_kv_cache_update(&lctx);
  7669. // if we have enough unused cells before the current head ->
  7670. // better to start searching from the beginning of the cache, hoping to fill it
  7671. if (kv_self.head > kv_self.used + 2*n_tokens) {
  7672. kv_self.head = 0;
  7673. }
  7674. if (!llama_kv_cache_find_slot(kv_self, u_batch)) {
  7675. return 1;
  7676. }
  7677. if (!kv_self.recurrent) {
  7678. // a heuristic, to avoid attending the full cache if it is not yet utilized
  7679. // after enough generations, the benefit from this heuristic disappears
  7680. // if we start defragmenting the cache, the benefit from this will be more important
  7681. kv_self.n = std::min(kv_self.size, std::max(32u, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  7682. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  7683. }
  7684. }
  7685. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  7686. ggml_backend_sched_reset(lctx.sched);
  7687. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  7688. ggml_cgraph * gf = llama_build_graph(lctx, u_batch, false);
  7689. // the output is always the last tensor in the graph
  7690. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  7691. struct ggml_tensor * embd = gf->nodes[gf->n_nodes - 2];
  7692. if (!hparams.causal_attn) {
  7693. res = nullptr; // do not extract logits for embedding models such as BERT
  7694. // token or sequence embeddings
  7695. embd = gf->nodes[gf->n_nodes - 1];
  7696. GGML_ASSERT(strcmp(embd->name, "result_embd") == 0 || strcmp(embd->name, "result_embd_pooled") == 0);
  7697. } else {
  7698. if (strcmp(res->name, "result_output") == 0) {
  7699. // the token embeddings could be the second to last tensor, or the third to last tensor
  7700. if (strcmp(embd->name, "result_norm") != 0) {
  7701. embd = gf->nodes[gf->n_nodes - 3];
  7702. GGML_ASSERT(strcmp(embd->name, "result_norm") == 0);
  7703. }
  7704. } else {
  7705. GGML_ASSERT(false && "missing result_output tensor");
  7706. }
  7707. }
  7708. // 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);
  7709. // for big prompts, if BLAS is enabled, it is better to use only one thread
  7710. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  7711. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  7712. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  7713. // with the BLAS calls. need a better solution
  7714. // MoE Special Case: This logic applies when hparams.n_expert == 0, i.e. the model is NOT an MoE model. When an MoE is
  7715. // being processed then Accelerate/BLAS will not be involved, so capping would limit performance.
  7716. if (n_tokens >= 32 && hparams.n_expert == 0 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  7717. n_threads = std::min(4, n_threads);
  7718. }
  7719. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  7720. llama_set_inputs(lctx, u_batch);
  7721. llama_graph_compute(lctx, gf, n_threads);
  7722. // update the kv ring buffer
  7723. {
  7724. kv_self.head += n_tokens;
  7725. // Ensure kv cache head points to a valid index.
  7726. if (kv_self.head >= kv_self.size) {
  7727. kv_self.head = 0;
  7728. }
  7729. }
  7730. #ifdef GGML_PERF
  7731. // print timing information per ggml operation (for debugging purposes)
  7732. // requires GGML_PERF to be defined
  7733. ggml_graph_print(gf);
  7734. #endif
  7735. // plot the computation graph in dot format (for debugging purposes)
  7736. //if (n_past%100 == 0) {
  7737. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  7738. //}
  7739. // extract logits
  7740. // TODO: do not compute and extract logits if only embeddings are needed
  7741. // update the graphs to skip "result_output" if logits are not needed
  7742. if (res) {
  7743. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(lctx.sched, res);
  7744. GGML_ASSERT(backend_res != nullptr);
  7745. if (u_batch.logits) {
  7746. int32_t i_first = -1;
  7747. for (uint32_t i = 0; i < n_tokens; i++) {
  7748. if (u_batch.logits[i] && i_first == -1) {
  7749. i_first = (int32_t) i;
  7750. }
  7751. if (u_batch.logits[i] == 0 || i == n_tokens - 1) {
  7752. if (i_first != -1) {
  7753. int i_last = u_batch.logits[i] == 0 ? i : i + 1;
  7754. // extract logits for the range [i_first, i_last)
  7755. // group the requests to minimize the number of calls to the backend
  7756. ggml_backend_tensor_get_async(backend_res, res,
  7757. logits_out + n_vocab*(cur_token + i_first),
  7758. i_first*n_vocab*sizeof(float),
  7759. (i_last - i_first)*n_vocab*sizeof(float));
  7760. i_first = -1;
  7761. }
  7762. }
  7763. #ifndef NDEBUG
  7764. logits_valid[cur_token + i] = u_batch.logits[i] != 0;;
  7765. #endif
  7766. }
  7767. } else if (lctx.logits_all) {
  7768. ggml_backend_tensor_get_async(backend_res, res, logits_out + n_vocab*cur_token, 0, n_vocab*n_tokens*sizeof(float));
  7769. #ifndef NDEBUG
  7770. std::fill(logits_valid.begin() + cur_token, logits_valid.begin() + cur_token + n_tokens, true);
  7771. #endif
  7772. } else {
  7773. if (cur_token + n_tokens >= n_tokens_all) {
  7774. ggml_backend_tensor_get_async(backend_res, res, logits_out, n_vocab*(n_tokens - 1)*sizeof(float), n_vocab*sizeof(float));
  7775. #ifndef NDEBUG
  7776. logits_valid[0] = true;
  7777. #endif
  7778. }
  7779. }
  7780. }
  7781. // extract embeddings
  7782. if (cparams.embeddings && embd) {
  7783. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched, embd);
  7784. GGML_ASSERT(backend_embd != nullptr);
  7785. switch (cparams.pooling_type) {
  7786. case LLAMA_POOLING_TYPE_NONE:
  7787. {
  7788. // extract token embeddings
  7789. auto & embd_out = lctx.embd;
  7790. if (u_batch.logits) {
  7791. //embd_out.resize(n_embd * n_tokens);
  7792. for (uint32_t i = 0; i < n_tokens; i++) {
  7793. if (u_batch.logits[i] == 0) {
  7794. continue;
  7795. }
  7796. ggml_backend_tensor_get_async(backend_embd, embd, embd_out + n_embd*(i + cur_token), (n_embd*i)*sizeof(float), n_embd*sizeof(float));
  7797. }
  7798. }
  7799. } break;
  7800. case LLAMA_POOLING_TYPE_CLS:
  7801. case LLAMA_POOLING_TYPE_MEAN:
  7802. {
  7803. GGML_ASSERT(strcmp(embd->name, "result_embd_pooled") == 0);
  7804. // extract sequence embeddings
  7805. auto & embd_seq_out = lctx.embd_seq;
  7806. embd_seq_out.clear();
  7807. for (uint32_t i = 0; i < n_tokens; i++) {
  7808. const llama_seq_id seq_id = u_batch.seq_id[i][0];
  7809. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  7810. continue;
  7811. }
  7812. embd_seq_out[seq_id].resize(n_embd);
  7813. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  7814. }
  7815. } break;
  7816. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  7817. {
  7818. GGML_ASSERT(false && "unknown pooling type");
  7819. } break;
  7820. }
  7821. }
  7822. }
  7823. // wait for the computation to finish (automatically done when obtaining the model output)
  7824. //llama_synchronize(&lctx);
  7825. // decide if we need to defrag the kv cache
  7826. if (cparams.causal_attn && cparams.defrag_thold >= 0.0f) {
  7827. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used)/float(kv_self.n) : 0.0f;
  7828. // queue defragmentation for next llama_kv_cache_update
  7829. if (fragmentation > cparams.defrag_thold) {
  7830. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  7831. llama_kv_cache_defrag(kv_self);
  7832. }
  7833. }
  7834. return 0;
  7835. }
  7836. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  7837. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  7838. auto & kv_self = lctx.kv_self;
  7839. const auto & hparams = lctx.model.hparams;
  7840. const uint32_t n_layer = hparams.n_layer;
  7841. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  7842. const uint32_t n_used = kv_self.used;
  7843. assert(n_used <= n_kv);
  7844. //const int64_t t_start = ggml_time_us();
  7845. // number of cells moved
  7846. uint32_t n_moves = 0;
  7847. // each move requires 6*n_layer tensors (see build_defrag)
  7848. // - source view, destination view, copy operation
  7849. // - x2 for keys and values
  7850. const uint32_t max_moves = LLAMA_MAX_NODES/(6*n_layer);
  7851. // determine which KV cells to move where
  7852. //
  7853. // cell i moves to ids[i]
  7854. //
  7855. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  7856. //
  7857. std::vector<uint32_t> ids(n_kv, n_kv);
  7858. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  7859. const auto & cell0 = kv_self.cells[i0];
  7860. if (!cell0.is_empty()) {
  7861. ids[i0] = i0;
  7862. continue;
  7863. }
  7864. // found a hole - fill it with data from the end of the cache
  7865. uint32_t nh = 1;
  7866. // determine the size of the hole
  7867. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  7868. nh++;
  7869. }
  7870. uint32_t nf = 0;
  7871. uint32_t is = n_kv - 1;
  7872. // starting from the end, find nh non-empty cells
  7873. for (; is > i0; --is) {
  7874. const auto & cell1 = kv_self.cells[is];
  7875. if (cell1.is_empty() || ids[is] != n_kv) {
  7876. continue;
  7877. }
  7878. // non-empty cell which is not yet moved
  7879. nf++;
  7880. if (nf == nh) {
  7881. break;
  7882. }
  7883. }
  7884. // this can only happen if `n_used` is not accurate, which would be a bug
  7885. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  7886. nf = 0;
  7887. uint32_t i1 = is;
  7888. // are we moving a continuous block of memory?
  7889. bool cont = false;
  7890. // should we stop searching for the next move?
  7891. bool stop = false;
  7892. // go back and move the nf cells to the hole
  7893. for (; i1 < n_kv; ++i1) {
  7894. auto & cell1 = kv_self.cells[i1];
  7895. if (cell1.is_empty() || ids[i1] != n_kv) {
  7896. if (n_moves == max_moves) {
  7897. stop = true;
  7898. break;
  7899. }
  7900. cont = false;
  7901. continue;
  7902. }
  7903. // this cell goes to (i0 + nf)
  7904. ids[i1] = i0 + nf;
  7905. // move the cell meta data
  7906. kv_self.cells[i0 + nf] = cell1;
  7907. // clear the old cell and move the head there
  7908. cell1 = llama_kv_cell();
  7909. kv_self.head = n_used;
  7910. if (!cont) {
  7911. n_moves++;
  7912. cont = true;
  7913. }
  7914. nf++;
  7915. if (nf == nh) {
  7916. break;
  7917. }
  7918. }
  7919. if (stop || n_moves == max_moves) {
  7920. break;
  7921. }
  7922. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  7923. i0 += nh - 1;
  7924. }
  7925. if (n_moves == 0) {
  7926. return;
  7927. }
  7928. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  7929. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  7930. #if 0
  7931. // CPU defrag
  7932. //
  7933. // TODO: optimizations are possible:
  7934. // - multiple threads
  7935. // - avoid copying to the host memory when already there
  7936. //
  7937. // likely not worth the effort, as we have ggml_graph based defrag
  7938. //
  7939. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  7940. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  7941. const uint32_t kv_size = kv_self.size;
  7942. std::vector<uint8_t> buf_k;
  7943. std::vector<uint8_t> buf_v;
  7944. for (uint32_t il = 0; il < n_layer; ++il) {
  7945. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  7946. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  7947. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  7948. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  7949. buf_k.resize(k_size);
  7950. buf_v.resize(v_size);
  7951. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  7952. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  7953. // batch move [i, i+nm) to [id, id+nm)
  7954. // note: cells can move only to a lower index
  7955. for (uint32_t i = 0; i < n_kv; ++i) {
  7956. const uint32_t id = ids[i];
  7957. if (i == id || id == n_kv) {
  7958. continue;
  7959. }
  7960. uint32_t nm = 1;
  7961. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  7962. nm++;
  7963. }
  7964. // move keys
  7965. {
  7966. const int64_t os = i*k_size_row;
  7967. const int64_t od = id*k_size_row;
  7968. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  7969. }
  7970. // move values (note: they are transposed)
  7971. {
  7972. const int64_t os = i;
  7973. const int64_t od = id;
  7974. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  7975. memcpy(buf_v.data() + (od + j*kv_size)*v_size_el, buf_v.data() + (os + j*kv_size)*v_size_el, nm*v_size_el);
  7976. }
  7977. }
  7978. i += nm - 1;
  7979. }
  7980. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  7981. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  7982. }
  7983. #else
  7984. // ggml_graph defrag
  7985. ggml_backend_sched_reset(lctx.sched);
  7986. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  7987. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  7988. #endif
  7989. //const int64_t t_end = ggml_time_us();
  7990. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  7991. }
  7992. static void llama_kv_cache_update_internal(struct llama_context & lctx) {
  7993. bool need_reserve = false;
  7994. // apply K-shift if needed
  7995. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE && lctx.kv_self.has_shift) {
  7996. {
  7997. ggml_backend_sched_reset(lctx.sched);
  7998. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  7999. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  8000. llama_set_k_shift(lctx);
  8001. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  8002. need_reserve = true;
  8003. }
  8004. {
  8005. auto & kv_self = lctx.kv_self;
  8006. kv_self.has_shift = false;
  8007. for (uint32_t i = 0; i < kv_self.size; ++i) {
  8008. kv_self.cells[i].delta = 0;
  8009. }
  8010. }
  8011. }
  8012. if (lctx.kv_self.recurrent && lctx.kv_self.do_copy) {
  8013. {
  8014. ggml_backend_sched_reset(lctx.sched);
  8015. ggml_cgraph * gf = llama_build_graph_s_copy(lctx);
  8016. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  8017. llama_set_s_copy(lctx);
  8018. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  8019. need_reserve = true;
  8020. }
  8021. {
  8022. auto & kv_self = lctx.kv_self;
  8023. kv_self.do_copy = false;
  8024. for (uint32_t i = 0; i < kv_self.size; ++i) {
  8025. kv_self.cells[i].src = i;
  8026. }
  8027. }
  8028. }
  8029. // defragment the KV cache if needed
  8030. if (lctx.kv_self.do_defrag) {
  8031. llama_kv_cache_defrag_internal(lctx);
  8032. need_reserve = true;
  8033. lctx.kv_self.do_defrag = false;
  8034. }
  8035. // reserve a worst case graph again
  8036. if (need_reserve) {
  8037. // TODO: extract to a function
  8038. // build worst-case graph
  8039. int n_tokens = (int)std::min(lctx.cparams.n_ctx, lctx.cparams.n_ubatch);
  8040. int n_past = lctx.cparams.n_ctx - n_tokens;
  8041. llama_token token = llama_token_bos(&lctx.model); // not actually used by llama_build_graph, but required to choose between token and embedding inputs graph
  8042. ggml_cgraph * gf = llama_build_graph(lctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  8043. // initialize scheduler with the worst-case graph
  8044. ggml_backend_sched_reset(lctx.sched);
  8045. if (!ggml_backend_sched_reserve(lctx.sched, gf)) {
  8046. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  8047. }
  8048. }
  8049. }
  8050. //
  8051. // tokenizer
  8052. //
  8053. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  8054. return vocab.type;
  8055. }
  8056. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  8057. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8058. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  8059. }
  8060. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  8061. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8062. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  8063. }
  8064. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  8065. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8066. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  8067. }
  8068. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  8069. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8070. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  8071. }
  8072. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  8073. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8074. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  8075. }
  8076. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  8077. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  8078. GGML_ASSERT(llama_is_byte_token(vocab, id));
  8079. const auto& token_data = vocab.id_to_token.at(id);
  8080. switch (llama_vocab_get_type(vocab)) {
  8081. case LLAMA_VOCAB_TYPE_SPM: {
  8082. auto buf = token_data.text.substr(3, 2);
  8083. return strtol(buf.c_str(), NULL, 16);
  8084. }
  8085. case LLAMA_VOCAB_TYPE_BPE: {
  8086. GGML_ASSERT(false);
  8087. return unicode_utf8_to_byte(token_data.text);
  8088. }
  8089. case LLAMA_VOCAB_TYPE_WPM: {
  8090. GGML_ASSERT(false);
  8091. }
  8092. default:
  8093. GGML_ASSERT(false);
  8094. }
  8095. }
  8096. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  8097. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  8098. static const char * hex = "0123456789ABCDEF";
  8099. switch (llama_vocab_get_type(vocab)) {
  8100. case LLAMA_VOCAB_TYPE_SPM: {
  8101. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  8102. auto token = vocab.token_to_id.find(buf);
  8103. if (token != vocab.token_to_id.end()) {
  8104. return (*token).second;
  8105. }
  8106. // Try to fall back to just the byte as a string
  8107. const char buf2[2] = { (char)ch, 0 };
  8108. return vocab.token_to_id.at(buf2);
  8109. }
  8110. case LLAMA_VOCAB_TYPE_WPM:
  8111. case LLAMA_VOCAB_TYPE_BPE: {
  8112. return vocab.token_to_id.at(unicode_byte_to_utf8(ch));
  8113. }
  8114. default:
  8115. GGML_ASSERT(false);
  8116. }
  8117. }
  8118. static void llama_escape_whitespace(std::string & text) {
  8119. replace_all(text, " ", "\xe2\x96\x81");
  8120. }
  8121. static void llama_unescape_whitespace(std::string & word) {
  8122. replace_all(word, "\xe2\x96\x81", " ");
  8123. }
  8124. struct llm_symbol {
  8125. using index = int;
  8126. index prev;
  8127. index next;
  8128. const char * text;
  8129. size_t n;
  8130. };
  8131. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  8132. // SPM tokenizer
  8133. // original implementation:
  8134. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  8135. struct llm_bigram_spm {
  8136. struct comparator {
  8137. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  8138. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  8139. }
  8140. };
  8141. using queue_storage = std::vector<llm_bigram_spm>;
  8142. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  8143. llm_symbol::index left;
  8144. llm_symbol::index right;
  8145. float score;
  8146. size_t size;
  8147. };
  8148. struct llm_tokenizer_spm {
  8149. llm_tokenizer_spm(const llama_vocab & vocab) : vocab(vocab) {}
  8150. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  8151. // split string into utf8 chars
  8152. int index = 0;
  8153. size_t offs = 0;
  8154. while (offs < text.size()) {
  8155. llm_symbol sym;
  8156. size_t len = utf8_len(text[offs]);
  8157. sym.text = text.c_str() + offs;
  8158. sym.n = std::min(len, text.size() - offs);
  8159. offs += sym.n;
  8160. sym.prev = index - 1;
  8161. sym.next = offs == text.size() ? -1 : index + 1;
  8162. index++;
  8163. symbols.emplace_back(sym);
  8164. }
  8165. // seed the work queue with all possible 2-character tokens.
  8166. for (size_t i = 1; i < symbols.size(); ++i) {
  8167. try_add_bigram(i - 1, i);
  8168. }
  8169. // keep substituting the highest frequency pairs for as long as we can.
  8170. while (!work_queue.empty()) {
  8171. auto bigram = work_queue.top();
  8172. work_queue.pop();
  8173. auto & left_sym = symbols[bigram.left];
  8174. auto & right_sym = symbols[bigram.right];
  8175. // if one of the symbols already got merged, skip it.
  8176. if (left_sym.n == 0 || right_sym.n == 0 ||
  8177. left_sym.n + right_sym.n != bigram.size) {
  8178. continue;
  8179. }
  8180. // merge the right sym into the left one
  8181. left_sym.n += right_sym.n;
  8182. right_sym.n = 0;
  8183. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  8184. // remove the right sym from the chain
  8185. left_sym.next = right_sym.next;
  8186. if (right_sym.next >= 0) {
  8187. symbols[right_sym.next].prev = bigram.left;
  8188. }
  8189. // find more substitutions
  8190. try_add_bigram(left_sym.prev, bigram.left);
  8191. try_add_bigram(bigram.left, left_sym.next);
  8192. }
  8193. for (int i = 0; i != -1; i = symbols[i].next) {
  8194. auto & symbol = symbols[i];
  8195. resegment(symbol, output);
  8196. }
  8197. }
  8198. private:
  8199. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  8200. auto text = std::string(symbol.text, symbol.n);
  8201. auto token = vocab.token_to_id.find(text);
  8202. // Do we need to support is_unused?
  8203. if (token != vocab.token_to_id.end()) {
  8204. output.push_back((*token).second);
  8205. return;
  8206. }
  8207. const auto p = rev_merge.find(text);
  8208. if (p == rev_merge.end()) {
  8209. // output any symbols that did not form tokens as bytes.
  8210. output.reserve(output.size() + symbol.n);
  8211. for (int j = 0; j < (int)symbol.n; ++j) {
  8212. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  8213. output.push_back(token_id);
  8214. }
  8215. return;
  8216. }
  8217. resegment(symbols[p->second.first], output);
  8218. resegment(symbols[p->second.second], output);
  8219. }
  8220. void try_add_bigram(int left, int right) {
  8221. if (left == -1 || right == -1) {
  8222. return;
  8223. }
  8224. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  8225. auto token = vocab.token_to_id.find(text);
  8226. if (token == vocab.token_to_id.end()) {
  8227. return;
  8228. }
  8229. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  8230. return;
  8231. }
  8232. const auto & tok_data = vocab.id_to_token[(*token).second];
  8233. llm_bigram_spm bigram;
  8234. bigram.left = left;
  8235. bigram.right = right;
  8236. bigram.score = tok_data.score;
  8237. bigram.size = text.size();
  8238. work_queue.push(bigram);
  8239. // Do we need to support is_unused?
  8240. rev_merge[text] = std::make_pair(left, right);
  8241. }
  8242. const llama_vocab & vocab;
  8243. std::vector<llm_symbol> symbols;
  8244. llm_bigram_spm::queue work_queue;
  8245. std::map<std::string, std::pair<int, int>> rev_merge;
  8246. };
  8247. // BPE tokenizer
  8248. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  8249. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  8250. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  8251. struct llm_bigram_bpe {
  8252. struct comparator {
  8253. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  8254. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  8255. }
  8256. };
  8257. using queue_storage = std::vector<llm_bigram_bpe>;
  8258. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  8259. llm_symbol::index left;
  8260. llm_symbol::index right;
  8261. std::string text;
  8262. int rank;
  8263. size_t size;
  8264. };
  8265. struct llm_tokenizer_bpe {
  8266. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  8267. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  8268. int final_prev_index = -1;
  8269. auto word_collection = bpe_gpt2_preprocess(text);
  8270. symbols_final.clear();
  8271. for (auto & word : word_collection) {
  8272. work_queue = llm_bigram_bpe::queue();
  8273. symbols.clear();
  8274. int index = 0;
  8275. size_t offset = 0;
  8276. while (offset < word.size()) {
  8277. llm_symbol sym;
  8278. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  8279. sym.text = word.c_str() + offset;
  8280. sym.n = char_len;
  8281. offset += sym.n;
  8282. sym.prev = index - 1;
  8283. sym.next = offset == word.size() ? -1 : index + 1;
  8284. index++;
  8285. symbols.emplace_back(sym);
  8286. }
  8287. for (size_t i = 1; i < symbols.size(); ++i) {
  8288. add_new_bigram(i - 1, i);
  8289. }
  8290. // build token(s)
  8291. while (!work_queue.empty()) {
  8292. auto bigram = work_queue.top();
  8293. work_queue.pop();
  8294. auto & left_symbol = symbols[bigram.left];
  8295. auto & right_symbol = symbols[bigram.right];
  8296. if (left_symbol.n == 0 || right_symbol.n == 0) {
  8297. continue;
  8298. }
  8299. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  8300. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  8301. if (left_token + right_token != bigram.text) {
  8302. continue; // Skip this bigram if it's outdated
  8303. }
  8304. // merge the right sym into the left one
  8305. left_symbol.n += right_symbol.n;
  8306. right_symbol.n = 0;
  8307. // remove the right sym from the chain
  8308. left_symbol.next = right_symbol.next;
  8309. if (right_symbol.next >= 0) {
  8310. symbols[right_symbol.next].prev = bigram.left;
  8311. }
  8312. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  8313. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  8314. }
  8315. // add the fnished tokens to the final list keeping correct order for next and prev
  8316. for (auto & sym : symbols) {
  8317. if (sym.n > 0) {
  8318. sym.prev = final_prev_index;
  8319. sym.next = -1;
  8320. if (final_prev_index != -1) {
  8321. symbols_final[final_prev_index].next = symbols_final.size();
  8322. }
  8323. symbols_final.emplace_back(sym);
  8324. final_prev_index = symbols_final.size() - 1;
  8325. }
  8326. }
  8327. }
  8328. symbols = symbols_final;
  8329. if (!symbols.empty()) {
  8330. for (int i = 0; i != -1; i = symbols[i].next) {
  8331. auto & symbol = symbols[i];
  8332. if (symbol.n == 0) {
  8333. continue;
  8334. }
  8335. const std::string str = std::string(symbol.text, symbol.n);
  8336. const auto token = vocab.token_to_id.find(str);
  8337. if (token == vocab.token_to_id.end()) {
  8338. for (auto j = str.begin(); j != str.end(); ++j) {
  8339. std::string byte_str(1, *j);
  8340. auto token_multibyte = vocab.token_to_id.find(byte_str);
  8341. if (token_multibyte == vocab.token_to_id.end()) {
  8342. throw std::runtime_error("ERROR: byte not found in vocab");
  8343. }
  8344. output.push_back((*token_multibyte).second);
  8345. }
  8346. } else {
  8347. output.push_back((*token).second);
  8348. }
  8349. }
  8350. }
  8351. }
  8352. private:
  8353. void add_new_bigram(int left, int right) {
  8354. if (left == -1 || right == -1) {
  8355. return;
  8356. }
  8357. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  8358. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  8359. int rank_found = -1;
  8360. rank_found = vocab.find_bpe_rank(left_token, right_token);
  8361. if (rank_found < 0) {
  8362. return;
  8363. }
  8364. llm_bigram_bpe bigram;
  8365. bigram.left = left;
  8366. bigram.right = right;
  8367. bigram.text = left_token + right_token;
  8368. bigram.size = left_token.size() + right_token.size();
  8369. bigram.rank = rank_found;
  8370. work_queue.push(bigram);
  8371. }
  8372. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  8373. std::vector<std::string> bpe_words;
  8374. std::vector<std::string> bpe_encoded_words;
  8375. std::string token = "";
  8376. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  8377. bool collecting_numeric = false;
  8378. bool collecting_letter = false;
  8379. bool collecting_special = false;
  8380. bool collecting_whitespace_lookahead = false;
  8381. bool collecting = false;
  8382. std::vector<std::string> text_utf;
  8383. text_utf.reserve(text.size());
  8384. bpe_words.reserve(text.size());
  8385. bpe_encoded_words.reserve(text.size());
  8386. const auto cpts = unicode_cpts_from_utf8(text);
  8387. for (size_t i = 0; i < cpts.size(); ++i)
  8388. text_utf.emplace_back(unicode_cpt_to_utf8(cpts[i]));
  8389. for (int i = 0; i < (int)text_utf.size(); i++) {
  8390. const std::string & utf_char = text_utf[i];
  8391. bool split_condition = false;
  8392. int bytes_remain = text_utf.size() - i;
  8393. // forward backward lookups
  8394. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  8395. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  8396. // handling contractions
  8397. if (!split_condition && bytes_remain >= 2) {
  8398. // 's|'t|'m|'d
  8399. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  8400. split_condition = true;
  8401. }
  8402. if (split_condition) {
  8403. if (token.size()) {
  8404. bpe_words.emplace_back(token); // push previous content as token
  8405. }
  8406. token = utf_char + utf_char_next;
  8407. bpe_words.emplace_back(token);
  8408. token = "";
  8409. i++;
  8410. continue;
  8411. }
  8412. }
  8413. if (!split_condition && bytes_remain >= 3) {
  8414. // 're|'ve|'ll
  8415. if (utf_char == "\'" && (
  8416. (utf_char_next == "r" && utf_char_next_next == "e") ||
  8417. (utf_char_next == "v" && utf_char_next_next == "e") ||
  8418. (utf_char_next == "l" && utf_char_next_next == "l"))
  8419. ) {
  8420. split_condition = true;
  8421. }
  8422. if (split_condition) {
  8423. // current token + next token can be defined
  8424. if (token.size()) {
  8425. bpe_words.emplace_back(token); // push previous content as token
  8426. }
  8427. token = utf_char + utf_char_next + utf_char_next_next;
  8428. bpe_words.emplace_back(token); // the contraction
  8429. token = "";
  8430. i += 2;
  8431. continue;
  8432. }
  8433. }
  8434. if (!split_condition && !collecting) {
  8435. if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  8436. collecting_letter = true;
  8437. collecting = true;
  8438. }
  8439. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  8440. collecting_numeric = true;
  8441. collecting = true;
  8442. }
  8443. else if (
  8444. ((unicode_cpt_type(utf_char) != CODEPOINT_TYPE_LETTER && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (unicode_cpt_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  8445. (!token.size() && utf_char == " " && unicode_cpt_type(utf_char_next) != CODEPOINT_TYPE_LETTER && unicode_cpt_type(utf_char_next) != CODEPOINT_TYPE_DIGIT && unicode_cpt_type(utf_char_next) != CODEPOINT_TYPE_WHITESPACE)
  8446. ) {
  8447. collecting_special = true;
  8448. collecting = true;
  8449. }
  8450. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  8451. collecting_whitespace_lookahead = true;
  8452. collecting = true;
  8453. }
  8454. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  8455. split_condition = true;
  8456. }
  8457. }
  8458. else if (!split_condition && collecting) {
  8459. if (collecting_letter && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  8460. split_condition = true;
  8461. }
  8462. else if (collecting_numeric && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  8463. split_condition = true;
  8464. }
  8465. else if (collecting_special && (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_LETTER || unicode_cpt_type(utf_char) == CODEPOINT_TYPE_DIGIT || unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE)) {
  8466. split_condition = true;
  8467. }
  8468. else if (collecting_whitespace_lookahead && (unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_LETTER || unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  8469. split_condition = true;
  8470. }
  8471. }
  8472. if (utf_char_next == "") {
  8473. split_condition = true; // final
  8474. token += utf_char;
  8475. }
  8476. if (split_condition) {
  8477. if (token.size()) {
  8478. bpe_words.emplace_back(token);
  8479. }
  8480. token = utf_char;
  8481. collecting = false;
  8482. collecting_letter = false;
  8483. collecting_numeric = false;
  8484. collecting_special = false;
  8485. collecting_whitespace_lookahead = false;
  8486. }
  8487. else {
  8488. token += utf_char;
  8489. }
  8490. }
  8491. for (std::string & word : bpe_words) {
  8492. std::string encoded_token = "";
  8493. for (char & c : word) {
  8494. encoded_token += unicode_byte_to_utf8(c);
  8495. }
  8496. bpe_encoded_words.emplace_back(encoded_token);
  8497. }
  8498. return bpe_encoded_words;
  8499. }
  8500. const llama_vocab & vocab;
  8501. std::vector<llm_symbol> symbols;
  8502. std::vector<llm_symbol> symbols_final;
  8503. llm_bigram_bpe::queue work_queue;
  8504. };
  8505. struct llm_tokenizer_wpm {
  8506. llm_tokenizer_wpm(const llama_vocab & vocab): vocab(vocab) {}
  8507. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  8508. auto * token_map = &vocab.token_to_id;
  8509. // normalize and split by whitespace
  8510. std::vector<std::string> words = preprocess(text);
  8511. // bos token prepended already
  8512. // find the longest tokens that form the words
  8513. for (const std::string &word : words) {
  8514. // skip empty words
  8515. if (word.size() == 0) {
  8516. continue;
  8517. }
  8518. // prepend phantom space
  8519. std::string word1 = "\xe2\x96\x81" + word;
  8520. int n = word1.size();
  8521. // we're at the start of a new word
  8522. int i = 0;
  8523. bool match_any = false;
  8524. // move through character position in word
  8525. while (i < n) {
  8526. // loop through possible match length
  8527. bool match = false;
  8528. for (int j = n; j > i; j--) {
  8529. auto it = token_map->find(word1.substr(i, j - i));
  8530. if (it != token_map->end()) {
  8531. output.push_back(it->second);
  8532. match = true;
  8533. match_any = true;
  8534. i = j;
  8535. break;
  8536. }
  8537. }
  8538. // must be an unknown character
  8539. if (!match) {
  8540. i++;
  8541. }
  8542. }
  8543. // we didn't find any matches for this word
  8544. if (!match_any) {
  8545. output.push_back(vocab.special_unk_id);
  8546. }
  8547. }
  8548. // append eos token
  8549. output.push_back(vocab.special_eos_id);
  8550. }
  8551. std::vector<std::string> preprocess(const std::string & text) {
  8552. std::vector<uint32_t> cpts_nfd = unicode_cpts_normalize_nfd(unicode_cpts_from_utf8(text));
  8553. // strip accents, strip control, uniformize whitespace,
  8554. // to lowercase, pad chinese characters, pad punctuation
  8555. std::string new_str = "";
  8556. for (uint32_t code : cpts_nfd) {
  8557. int type = unicode_cpt_type(code);
  8558. if (type == CODEPOINT_TYPE_ACCENT_MARK || type == CODEPOINT_TYPE_CONTROL) {
  8559. continue;
  8560. }
  8561. code = to_lower(code);
  8562. if (type == CODEPOINT_TYPE_WHITESPACE) {
  8563. code = ' ';
  8564. }
  8565. std::string s = unicode_cpt_to_utf8(code);
  8566. if (type == CODEPOINT_TYPE_PUNCTUATION || is_ascii_punct(code) || is_chinese_char(code)) {
  8567. new_str += " ";
  8568. new_str += s;
  8569. new_str += " ";
  8570. } else {
  8571. new_str += s;
  8572. }
  8573. }
  8574. // split by whitespace
  8575. uint64_t l = 0;
  8576. uint64_t r = 0;
  8577. std::vector<std::string> words;
  8578. while (r < new_str.size()) {
  8579. // if is whitespace
  8580. if (isspace(new_str[r])) {
  8581. if (r > l) words.push_back(new_str.substr(l, (r - l)));
  8582. l = r + 1;
  8583. r = l;
  8584. } else {
  8585. r += 1;
  8586. }
  8587. }
  8588. if (r > l) {
  8589. words.push_back(new_str.substr(l, (r - l)));
  8590. }
  8591. return words;
  8592. }
  8593. uint32_t to_lower(uint32_t code) {
  8594. static const std::locale locale("en_US.UTF-8");
  8595. #if defined(_WIN32)
  8596. if (code > 0xFFFF) {
  8597. return code;
  8598. }
  8599. #endif
  8600. return std::tolower(wchar_t(code), locale);
  8601. }
  8602. bool is_ascii_punct(uint32_t code) {
  8603. return code < 256 && ispunct(code);
  8604. }
  8605. bool is_chinese_char(uint32_t cpt) {
  8606. if ((cpt >= 0x4E00 && cpt <= 0x9FFF) ||
  8607. (cpt >= 0x3400 && cpt <= 0x4DBF) ||
  8608. (cpt >= 0x20000 && cpt <= 0x2A6DF) ||
  8609. (cpt >= 0x2A700 && cpt <= 0x2B73F) ||
  8610. (cpt >= 0x2B740 && cpt <= 0x2B81F) ||
  8611. (cpt >= 0x2B920 && cpt <= 0x2CEAF) || // this should be 0x2B820 but in hf rust code it is 0x2B920
  8612. (cpt >= 0xF900 && cpt <= 0xFAFF) ||
  8613. (cpt >= 0x2F800 && cpt <= 0x2FA1F) ||
  8614. (cpt >= 0x3000 && cpt <= 0x303F) ||
  8615. (cpt >= 0xFF00 && cpt <= 0xFFEF)) {
  8616. return true; // NOLINT
  8617. }
  8618. return false;
  8619. }
  8620. const llama_vocab & vocab;
  8621. };
  8622. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE {
  8623. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  8624. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  8625. } FRAGMENT_BUFFER_VARIANT_TYPE;
  8626. struct fragment_buffer_variant {
  8627. fragment_buffer_variant(llama_vocab::id _token)
  8628. :
  8629. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  8630. token(_token),
  8631. raw_text(_dummy),
  8632. offset(0),
  8633. length(0) {}
  8634. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  8635. :
  8636. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  8637. token((llama_vocab::id) - 1),
  8638. raw_text(_raw_text),
  8639. offset(_offset),
  8640. length(_length){
  8641. GGML_ASSERT(_offset >= 0);
  8642. GGML_ASSERT(_length >= 1);
  8643. GGML_ASSERT(offset + length <= raw_text.length());
  8644. }
  8645. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  8646. const llama_vocab::id token;
  8647. const std::string _dummy;
  8648. const std::string & raw_text;
  8649. const uint64_t offset;
  8650. const uint64_t length;
  8651. };
  8652. // #define PRETOKENIZERDEBUG
  8653. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer) {
  8654. // for each special token
  8655. for (const auto & st: vocab.special_tokens_cache) {
  8656. const auto & special_token = st.first;
  8657. const auto & special_id = st.second;
  8658. // for each text fragment
  8659. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  8660. while (it != buffer.end()) {
  8661. auto & fragment = (*it);
  8662. // if a fragment is text ( not yet processed )
  8663. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  8664. auto * raw_text = &(fragment.raw_text);
  8665. auto raw_text_base_offset = fragment.offset;
  8666. auto raw_text_base_length = fragment.length;
  8667. // loop over the text
  8668. while (true) {
  8669. // find the first occurrence of a given special token in this fragment
  8670. // passing offset argument only limit the "search area" but match coordinates
  8671. // are still relative to the source full raw_text
  8672. auto match = raw_text->find(special_token, raw_text_base_offset);
  8673. // no occurrences found, stop processing this fragment for a given special token
  8674. if (match == std::string::npos) break;
  8675. // check if match is within bounds of offset <-> length
  8676. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  8677. #ifdef PRETOKENIZERDEBUG
  8678. LLAMA_LOG_WARN("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());
  8679. #endif
  8680. auto source = std::distance(buffer.begin(), it);
  8681. // if match is further than base offset
  8682. // then we have some text to the left of it
  8683. if (match > raw_text_base_offset) {
  8684. // left
  8685. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  8686. const int64_t left_reminder_length = match - raw_text_base_offset;
  8687. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  8688. #ifdef PRETOKENIZERDEBUG
  8689. LLAMA_LOG_WARN("FL: (%ld %ld) '%s'\n", left_reminder_offset, left_reminder_length, raw_text->substr(left_reminder_offset, left_reminder_length).c_str());
  8690. #endif
  8691. it++;
  8692. }
  8693. // special token
  8694. buffer.emplace_after(it, special_id);
  8695. it++;
  8696. // right
  8697. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  8698. const int64_t right_reminder_offset = match + special_token.length();
  8699. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  8700. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  8701. #ifdef PRETOKENIZERDEBUG
  8702. LLAMA_LOG_WARN("FR: (%ld %ld) '%s'\n", right_reminder_offset, right_reminder_length, raw_text->substr(right_reminder_offset, right_reminder_length).c_str());
  8703. #endif
  8704. it++;
  8705. if (source == 0) {
  8706. buffer.erase_after(buffer.before_begin());
  8707. } else {
  8708. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  8709. }
  8710. // repeat for the right side
  8711. raw_text_base_offset = right_reminder_offset;
  8712. raw_text_base_length = right_reminder_length;
  8713. #ifdef PRETOKENIZERDEBUG
  8714. LLAMA_LOG_WARN("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());
  8715. #endif
  8716. } else {
  8717. if (source == 0) {
  8718. buffer.erase_after(buffer.before_begin());
  8719. } else {
  8720. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  8721. }
  8722. break;
  8723. }
  8724. }
  8725. }
  8726. it++;
  8727. }
  8728. }
  8729. }
  8730. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  8731. std::vector<llama_vocab::id> output;
  8732. // OG tokenizer behavior:
  8733. //
  8734. // tokenizer.encode('', add_bos=True) returns [1]
  8735. // tokenizer.encode('', add_bos=False) returns []
  8736. if (bos && vocab.special_bos_id != -1) {
  8737. output.push_back(vocab.special_bos_id);
  8738. }
  8739. if (raw_text.empty()) {
  8740. return output;
  8741. }
  8742. std::forward_list<fragment_buffer_variant> fragment_buffer;
  8743. fragment_buffer.emplace_front(raw_text, 0, raw_text.length());
  8744. if (special) tokenizer_st_partition(vocab, fragment_buffer);
  8745. switch (vocab.type) {
  8746. case LLAMA_VOCAB_TYPE_SPM:
  8747. {
  8748. for (const auto & fragment : fragment_buffer) {
  8749. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  8750. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  8751. // TODO: It's likely possible to get rid of this string copy entirely
  8752. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  8753. // and passing 'add space prefix' as bool argument
  8754. //
  8755. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  8756. if (&fragment == &fragment_buffer.front()) {
  8757. if (vocab.add_space_prefix) {
  8758. raw_text = " " + raw_text; // prefix with space if the first token is not special
  8759. }
  8760. }
  8761. #ifdef PRETOKENIZERDEBUG
  8762. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  8763. #endif
  8764. llm_tokenizer_spm tokenizer(vocab);
  8765. llama_escape_whitespace(raw_text);
  8766. tokenizer.tokenize(raw_text, output);
  8767. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  8768. output.push_back(fragment.token);
  8769. }
  8770. }
  8771. } break;
  8772. case LLAMA_VOCAB_TYPE_BPE:
  8773. {
  8774. for (const auto & fragment : fragment_buffer) {
  8775. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  8776. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  8777. #ifdef PRETOKENIZERDEBUG
  8778. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  8779. #endif
  8780. llm_tokenizer_bpe tokenizer(vocab);
  8781. tokenizer.tokenize(raw_text, output);
  8782. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  8783. output.push_back(fragment.token);
  8784. }
  8785. }
  8786. } break;
  8787. case LLAMA_VOCAB_TYPE_WPM:
  8788. {
  8789. for (const auto & fragment : fragment_buffer) {
  8790. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  8791. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  8792. #ifdef PRETOKENIZERDEBUG
  8793. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  8794. #endif
  8795. llm_tokenizer_wpm tokenizer(vocab);
  8796. tokenizer.tokenize(raw_text, output);
  8797. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  8798. output.push_back(fragment.token);
  8799. }
  8800. }
  8801. } break;
  8802. case LLAMA_VOCAB_TYPE_NONE:
  8803. GGML_ASSERT(false);
  8804. }
  8805. return output;
  8806. }
  8807. //
  8808. // grammar - internal
  8809. //
  8810. struct llama_partial_utf8 {
  8811. uint32_t value; // bit value so far (unshifted)
  8812. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  8813. };
  8814. struct llama_grammar {
  8815. const std::vector<std::vector<llama_grammar_element>> rules;
  8816. std::vector<std::vector<const llama_grammar_element *>> stacks;
  8817. // buffer for partially generated UTF-8 sequence from accepted tokens
  8818. llama_partial_utf8 partial_utf8;
  8819. };
  8820. struct llama_grammar_candidate {
  8821. size_t index;
  8822. const uint32_t * code_points;
  8823. llama_partial_utf8 partial_utf8;
  8824. };
  8825. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  8826. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  8827. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  8828. const std::string & src,
  8829. llama_partial_utf8 partial_start) {
  8830. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  8831. const char * pos = src.c_str();
  8832. std::vector<uint32_t> code_points;
  8833. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  8834. code_points.reserve(src.size() + 1);
  8835. uint32_t value = partial_start.value;
  8836. int n_remain = partial_start.n_remain;
  8837. // continue previous decode, if applicable
  8838. while (*pos != 0 && n_remain > 0) {
  8839. uint8_t next_byte = static_cast<uint8_t>(*pos);
  8840. if ((next_byte >> 6) != 2) {
  8841. // invalid sequence, abort
  8842. code_points.push_back(0);
  8843. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  8844. }
  8845. value = (value << 6) + (next_byte & 0x3F);
  8846. ++pos;
  8847. --n_remain;
  8848. }
  8849. if (partial_start.n_remain > 0 && n_remain == 0) {
  8850. code_points.push_back(value);
  8851. }
  8852. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  8853. while (*pos != 0) {
  8854. uint8_t first_byte = static_cast<uint8_t>(*pos);
  8855. uint8_t highbits = first_byte >> 4;
  8856. n_remain = lookup[highbits] - 1;
  8857. if (n_remain < 0) {
  8858. // invalid sequence, abort
  8859. code_points.clear();
  8860. code_points.push_back(0);
  8861. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  8862. }
  8863. uint8_t mask = (1 << (7 - n_remain)) - 1;
  8864. value = first_byte & mask;
  8865. ++pos;
  8866. while (*pos != 0 && n_remain > 0) {
  8867. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  8868. ++pos;
  8869. --n_remain;
  8870. }
  8871. if (n_remain == 0) {
  8872. code_points.push_back(value);
  8873. }
  8874. }
  8875. code_points.push_back(0);
  8876. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  8877. }
  8878. // returns true iff pos points to the end of one of the definitions of a rule
  8879. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  8880. switch (pos->type) {
  8881. case LLAMA_GRETYPE_END: return true; // NOLINT
  8882. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  8883. default: return false;
  8884. }
  8885. }
  8886. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  8887. // asserts that pos is pointing to a char range element
  8888. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  8889. const llama_grammar_element * pos,
  8890. const uint32_t chr) {
  8891. bool found = false;
  8892. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  8893. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  8894. do {
  8895. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  8896. // inclusive range, e.g. [a-z]
  8897. found = found || (pos->value <= chr && chr <= pos[1].value);
  8898. pos += 2;
  8899. } else {
  8900. // exact char match, e.g. [a] or "a"
  8901. found = found || pos->value == chr;
  8902. pos += 1;
  8903. }
  8904. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  8905. return std::make_pair(found == is_positive_char, pos);
  8906. }
  8907. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  8908. // range at pos (regular or inverse range)
  8909. // asserts that pos is pointing to a char range element
  8910. static bool llama_grammar_match_partial_char(
  8911. const llama_grammar_element * pos,
  8912. const llama_partial_utf8 partial_utf8) {
  8913. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  8914. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  8915. uint32_t partial_value = partial_utf8.value;
  8916. int n_remain = partial_utf8.n_remain;
  8917. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  8918. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  8919. return false;
  8920. }
  8921. // range of possible code points this partial UTF-8 sequence could complete to
  8922. uint32_t low = partial_value << (n_remain * 6);
  8923. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  8924. if (low == 0) {
  8925. if (n_remain == 2) {
  8926. low = 1 << 11;
  8927. } else if (n_remain == 3) {
  8928. low = 1 << 16;
  8929. }
  8930. }
  8931. do {
  8932. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  8933. // inclusive range, e.g. [a-z]
  8934. if (pos->value <= high && low <= pos[1].value) {
  8935. return is_positive_char;
  8936. }
  8937. pos += 2;
  8938. } else {
  8939. // exact char match, e.g. [a] or "a"
  8940. if (low <= pos->value && pos->value <= high) {
  8941. return is_positive_char;
  8942. }
  8943. pos += 1;
  8944. }
  8945. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  8946. return !is_positive_char;
  8947. }
  8948. // transforms a grammar pushdown stack into N possible stacks, all ending
  8949. // at a character range (terminal element)
  8950. static void llama_grammar_advance_stack(
  8951. const std::vector<std::vector<llama_grammar_element>> & rules,
  8952. const std::vector<const llama_grammar_element *> & stack,
  8953. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  8954. if (stack.empty()) {
  8955. new_stacks.emplace_back(stack);
  8956. return;
  8957. }
  8958. const llama_grammar_element * pos = stack.back();
  8959. switch (pos->type) {
  8960. case LLAMA_GRETYPE_RULE_REF: {
  8961. const size_t rule_id = static_cast<size_t>(pos->value);
  8962. const llama_grammar_element * subpos = rules[rule_id].data();
  8963. do {
  8964. // init new stack without the top (pos)
  8965. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  8966. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  8967. // if this rule ref is followed by another element, add that to stack
  8968. new_stack.push_back(pos + 1);
  8969. }
  8970. if (!llama_grammar_is_end_of_sequence(subpos)) {
  8971. // if alternate is nonempty, add to stack
  8972. new_stack.push_back(subpos);
  8973. }
  8974. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  8975. while (!llama_grammar_is_end_of_sequence(subpos)) {
  8976. // scan to end of alternate def
  8977. subpos++;
  8978. }
  8979. if (subpos->type == LLAMA_GRETYPE_ALT) {
  8980. // there's another alternate def of this rule to process
  8981. subpos++;
  8982. } else {
  8983. break;
  8984. }
  8985. } while (true);
  8986. break;
  8987. }
  8988. case LLAMA_GRETYPE_CHAR:
  8989. case LLAMA_GRETYPE_CHAR_NOT:
  8990. new_stacks.emplace_back(stack);
  8991. break;
  8992. default:
  8993. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  8994. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  8995. // those
  8996. GGML_ASSERT(false);
  8997. }
  8998. }
  8999. // takes a set of possible pushdown stacks on a grammar, which are required to
  9000. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  9001. // produces the N possible stacks if the given char is accepted at those
  9002. // positions
  9003. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  9004. const std::vector<std::vector<llama_grammar_element>> & rules,
  9005. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  9006. const uint32_t chr) {
  9007. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  9008. for (const auto & stack : stacks) {
  9009. if (stack.empty()) {
  9010. continue;
  9011. }
  9012. auto match = llama_grammar_match_char(stack.back(), chr);
  9013. if (match.first) {
  9014. const llama_grammar_element * pos = match.second;
  9015. // update top of stack to next element, if any
  9016. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  9017. if (!llama_grammar_is_end_of_sequence(pos)) {
  9018. new_stack.push_back(pos);
  9019. }
  9020. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  9021. }
  9022. }
  9023. return new_stacks;
  9024. }
  9025. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  9026. const std::vector<std::vector<llama_grammar_element>> & rules,
  9027. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  9028. const std::vector<llama_grammar_candidate> & candidates);
  9029. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  9030. const std::vector<std::vector<llama_grammar_element>> & rules,
  9031. const std::vector<const llama_grammar_element *> & stack,
  9032. const std::vector<llama_grammar_candidate> & candidates) {
  9033. std::vector<llama_grammar_candidate> rejects;
  9034. if (stack.empty()) {
  9035. for (const auto & tok : candidates) {
  9036. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  9037. rejects.push_back(tok);
  9038. }
  9039. }
  9040. return rejects;
  9041. }
  9042. const llama_grammar_element * stack_pos = stack.back();
  9043. std::vector<llama_grammar_candidate> next_candidates;
  9044. for (const auto & tok : candidates) {
  9045. if (*tok.code_points == 0) {
  9046. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  9047. // that cannot satisfy this position in grammar
  9048. if (tok.partial_utf8.n_remain != 0 &&
  9049. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  9050. rejects.push_back(tok);
  9051. }
  9052. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  9053. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  9054. } else {
  9055. rejects.push_back(tok);
  9056. }
  9057. }
  9058. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  9059. // update top of stack to next element, if any
  9060. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  9061. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  9062. stack_after.push_back(stack_pos_after);
  9063. }
  9064. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  9065. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  9066. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  9067. for (const auto & tok : next_rejects) {
  9068. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  9069. }
  9070. return rejects;
  9071. }
  9072. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  9073. const std::vector<std::vector<llama_grammar_element>> & rules,
  9074. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  9075. const std::vector<llama_grammar_candidate> & candidates) {
  9076. GGML_ASSERT(!stacks.empty()); // REVIEW
  9077. if (candidates.empty()) {
  9078. return std::vector<llama_grammar_candidate>();
  9079. }
  9080. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  9081. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  9082. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  9083. }
  9084. return rejects;
  9085. }
  9086. //
  9087. // grammar - external
  9088. //
  9089. struct llama_grammar * llama_grammar_init(
  9090. const llama_grammar_element ** rules,
  9091. size_t n_rules,
  9092. size_t start_rule_index) {
  9093. const llama_grammar_element * pos;
  9094. // copy rule definitions into vectors
  9095. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  9096. for (size_t i = 0; i < n_rules; i++) {
  9097. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  9098. vec_rules[i].push_back(*pos);
  9099. }
  9100. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  9101. }
  9102. // loop over alternates of start rule to build initial stacks
  9103. std::vector<std::vector<const llama_grammar_element *>> stacks;
  9104. pos = vec_rules[start_rule_index].data();
  9105. do {
  9106. std::vector<const llama_grammar_element *> stack;
  9107. if (!llama_grammar_is_end_of_sequence(pos)) {
  9108. // if alternate is nonempty, add to stack
  9109. stack.push_back(pos);
  9110. }
  9111. llama_grammar_advance_stack(vec_rules, stack, stacks);
  9112. while (!llama_grammar_is_end_of_sequence(pos)) {
  9113. // scan to end of alternate def
  9114. pos++;
  9115. }
  9116. if (pos->type == LLAMA_GRETYPE_ALT) {
  9117. // there's another alternate def of this rule to process
  9118. pos++;
  9119. } else {
  9120. break;
  9121. }
  9122. } while (true);
  9123. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  9124. }
  9125. void llama_grammar_free(struct llama_grammar * grammar) {
  9126. delete grammar;
  9127. }
  9128. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  9129. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  9130. // redirect elements in stacks to point to new rules
  9131. for (size_t is = 0; is < result->stacks.size(); is++) {
  9132. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  9133. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  9134. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  9135. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  9136. result->stacks[is][ie] = &result->rules[ir0][ir1];
  9137. }
  9138. }
  9139. }
  9140. }
  9141. }
  9142. return result;
  9143. }
  9144. //
  9145. // sampling
  9146. //
  9147. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  9148. if (seed == LLAMA_DEFAULT_SEED) {
  9149. seed = time(NULL);
  9150. }
  9151. ctx->rng.seed(seed);
  9152. }
  9153. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  9154. GGML_ASSERT(candidates->size > 0);
  9155. const int64_t t_start_sample_us = ggml_time_us();
  9156. // Sort the logits in descending order
  9157. if (!candidates->sorted) {
  9158. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  9159. return a.logit > b.logit;
  9160. });
  9161. candidates->sorted = true;
  9162. }
  9163. float max_l = candidates->data[0].logit;
  9164. float cum_sum = 0.0f;
  9165. for (size_t i = 0; i < candidates->size; ++i) {
  9166. float p = expf(candidates->data[i].logit - max_l);
  9167. candidates->data[i].p = p;
  9168. cum_sum += p;
  9169. }
  9170. for (size_t i = 0; i < candidates->size; ++i) {
  9171. candidates->data[i].p /= cum_sum;
  9172. }
  9173. if (ctx) {
  9174. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9175. }
  9176. }
  9177. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  9178. // TODO: move bucket sort to separate function so that top_p/tail_free/typical/softmax first is equally fast
  9179. // if (k >= (int32_t)candidates->size) {
  9180. // return;
  9181. // }
  9182. const int64_t t_start_sample_us = ggml_time_us();
  9183. if (k <= 0) {
  9184. k = candidates->size;
  9185. }
  9186. k = std::max(k, (int) min_keep);
  9187. k = std::min(k, (int) candidates->size);
  9188. // Sort scores in descending order
  9189. if (!candidates->sorted) {
  9190. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  9191. return a.logit > b.logit;
  9192. };
  9193. if (k <= 128) {
  9194. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  9195. } else {
  9196. constexpr int nbuckets = 128;
  9197. constexpr float bucket_low = -10.0f;
  9198. constexpr float bucket_high = 10.0f;
  9199. constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
  9200. constexpr float bucker_inter = -bucket_low * bucket_scale;
  9201. std::vector<int> bucket_idx(candidates->size);
  9202. std::vector<int> histo(nbuckets, 0);
  9203. for (int i = 0; i < (int)candidates->size; ++i) {
  9204. const float val = candidates->data[i].logit;
  9205. int ib = int(bucket_scale * val + bucker_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
  9206. ib = std::max(0, std::min(nbuckets-1, ib));
  9207. bucket_idx[i] = ib;
  9208. ++histo[ib];
  9209. }
  9210. int nhave = 0;
  9211. int ib = nbuckets - 1;
  9212. for ( ; ib >= 0; --ib) {
  9213. nhave += histo[ib];
  9214. if (nhave >= k) break;
  9215. }
  9216. std::vector<llama_token_data> tmp_tokens(nhave);
  9217. auto ptr = tmp_tokens.data();
  9218. std::vector<llama_token_data*> bucket_ptrs;
  9219. bucket_ptrs.reserve(nbuckets - ib);
  9220. for (int j = nbuckets - 1; j >= ib; --j) {
  9221. bucket_ptrs.push_back(ptr);
  9222. ptr += histo[j];
  9223. }
  9224. for (int i = 0; i < (int)candidates->size; ++i) {
  9225. int j = bucket_idx[i];
  9226. if (j >= ib) {
  9227. *bucket_ptrs[nbuckets-1-j]++ = candidates->data[i];
  9228. }
  9229. }
  9230. ptr = tmp_tokens.data();
  9231. int ndone = 0;
  9232. for (int j = nbuckets-1; j > ib; --j) {
  9233. std::sort(ptr, ptr + histo[j], comp);
  9234. ptr += histo[j];
  9235. ndone += histo[j];
  9236. }
  9237. std::partial_sort(ptr, ptr + k - ndone, ptr + histo[ib], comp);
  9238. std::memcpy(candidates->data, tmp_tokens.data(), k*sizeof(llama_token_data));
  9239. }
  9240. candidates->sorted = true;
  9241. }
  9242. candidates->size = k;
  9243. if (ctx) {
  9244. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9245. }
  9246. }
  9247. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  9248. if (p >= 1.0f) {
  9249. return;
  9250. }
  9251. llama_sample_softmax(ctx, candidates);
  9252. const int64_t t_start_sample_us = ggml_time_us();
  9253. // Compute the cumulative probabilities
  9254. float cum_sum = 0.0f;
  9255. size_t last_idx = candidates->size;
  9256. for (size_t i = 0; i < candidates->size; ++i) {
  9257. cum_sum += candidates->data[i].p;
  9258. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  9259. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  9260. if (cum_sum >= p && i + 1 >= min_keep) {
  9261. last_idx = i + 1;
  9262. break;
  9263. }
  9264. }
  9265. // Resize the output vector to keep only the top-p tokens
  9266. candidates->size = last_idx;
  9267. if (ctx) {
  9268. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9269. }
  9270. }
  9271. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  9272. if (p <= 0.0f || !candidates->size) {
  9273. return;
  9274. }
  9275. const int64_t t_start_sample_us = ggml_time_us();
  9276. bool min_p_applied = false;
  9277. // if the candidates aren't sorted, try the unsorted implementation first
  9278. if (!candidates->sorted) {
  9279. std::vector<llama_token_data> filtered_tokens;
  9280. float max_logit = -FLT_MAX;
  9281. for (size_t i = 0; i < candidates->size; ++i) {
  9282. max_logit = std::max(max_logit, candidates->data[i].logit);
  9283. }
  9284. const float min_logit = max_logit + logf(p); // min logit for p_i >= p * p_max
  9285. for (size_t i = 0; i < candidates->size; ++i) {
  9286. if (candidates->data[i].logit >= min_logit) {
  9287. filtered_tokens.push_back(candidates->data[i]);
  9288. }
  9289. }
  9290. // if we have enough values the operation was a success
  9291. if (filtered_tokens.size() >= min_keep) {
  9292. memcpy(candidates->data, filtered_tokens.data(), filtered_tokens.size()*sizeof(llama_token_data));
  9293. candidates->size = filtered_tokens.size();
  9294. min_p_applied = true;
  9295. }
  9296. }
  9297. // if the candidates are sorted or the unsorted implementation failed, use this implementation
  9298. if (!min_p_applied) {
  9299. // Sort the logits in descending order
  9300. if (!candidates->sorted) {
  9301. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  9302. return a.logit > b.logit;
  9303. });
  9304. candidates->sorted = true;
  9305. }
  9306. const float min_logit = candidates->data[0].logit + logf(p); // min logit for p_i >= p * p_max
  9307. size_t i = 1; // first token always matches
  9308. for (; i < candidates->size; ++i) {
  9309. if (candidates->data[i].logit < min_logit && i >= min_keep) {
  9310. break; // prob too small
  9311. }
  9312. }
  9313. // Resize the output vector to keep only the matching tokens
  9314. candidates->size = i;
  9315. }
  9316. if (ctx) {
  9317. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9318. }
  9319. }
  9320. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  9321. if (z >= 1.0f || candidates->size <= 2) {
  9322. return;
  9323. }
  9324. llama_sample_softmax(nullptr, candidates);
  9325. const int64_t t_start_sample_us = ggml_time_us();
  9326. // Compute the first and second derivatives
  9327. std::vector<float> first_derivatives(candidates->size - 1);
  9328. std::vector<float> second_derivatives(candidates->size - 2);
  9329. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  9330. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  9331. }
  9332. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  9333. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  9334. }
  9335. // Calculate absolute value of second derivatives
  9336. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  9337. second_derivatives[i] = std::abs(second_derivatives[i]);
  9338. }
  9339. // Normalize the second derivatives
  9340. {
  9341. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  9342. if (second_derivatives_sum > 1e-6f) {
  9343. for (float & value : second_derivatives) {
  9344. value /= second_derivatives_sum;
  9345. }
  9346. } else {
  9347. for (float & value : second_derivatives) {
  9348. value = 1.0f / second_derivatives.size();
  9349. }
  9350. }
  9351. }
  9352. float cum_sum = 0.0f;
  9353. size_t last_idx = candidates->size;
  9354. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  9355. cum_sum += second_derivatives[i];
  9356. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  9357. if (cum_sum > z && i >= min_keep) {
  9358. last_idx = i;
  9359. break;
  9360. }
  9361. }
  9362. // Resize the output vector to keep only the tokens above the tail location
  9363. candidates->size = last_idx;
  9364. if (ctx) {
  9365. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9366. }
  9367. }
  9368. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  9369. // Reference implementation:
  9370. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  9371. if (p >= 1.0f) {
  9372. return;
  9373. }
  9374. // Compute the softmax of logits and calculate entropy
  9375. llama_sample_softmax(nullptr, candidates);
  9376. const int64_t t_start_sample_us = ggml_time_us();
  9377. float entropy = 0.0f;
  9378. for (size_t i = 0; i < candidates->size; ++i) {
  9379. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  9380. }
  9381. // Compute the absolute difference between negative log probability and entropy for each candidate
  9382. std::vector<float> shifted_scores;
  9383. for (size_t i = 0; i < candidates->size; ++i) {
  9384. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  9385. shifted_scores.push_back(shifted_score);
  9386. }
  9387. // Sort tokens based on the shifted_scores and their corresponding indices
  9388. std::vector<size_t> indices(candidates->size);
  9389. std::iota(indices.begin(), indices.end(), 0);
  9390. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  9391. return shifted_scores[a] < shifted_scores[b];
  9392. });
  9393. // Compute the cumulative probabilities
  9394. float cum_sum = 0.0f;
  9395. size_t last_idx = indices.size();
  9396. for (size_t i = 0; i < indices.size(); ++i) {
  9397. size_t idx = indices[i];
  9398. cum_sum += candidates->data[idx].p;
  9399. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  9400. if (cum_sum > p && i >= min_keep - 1) {
  9401. last_idx = i + 1;
  9402. break;
  9403. }
  9404. }
  9405. // Resize the output vector to keep only the locally typical tokens
  9406. std::vector<llama_token_data> new_candidates;
  9407. for (size_t i = 0; i < last_idx; ++i) {
  9408. size_t idx = indices[i];
  9409. new_candidates.push_back(candidates->data[idx]);
  9410. }
  9411. // Replace the data in candidates with the new_candidates data
  9412. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  9413. candidates->size = new_candidates.size();
  9414. candidates->sorted = false;
  9415. if (ctx) {
  9416. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9417. }
  9418. }
  9419. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  9420. const int64_t t_start_sample_us = ggml_time_us();
  9421. // no need to do anything if there is only one (or zero) candidates
  9422. if(candidates_p->size <= 1) {
  9423. return;
  9424. }
  9425. // Calculate maximum possible entropy
  9426. float max_entropy = -logf(1.0f / candidates_p->size);
  9427. llama_sample_softmax(nullptr, candidates_p);
  9428. // Calculate entropy of the softmax probabilities
  9429. float entropy = 0.0f;
  9430. for (size_t i = 0; i < candidates_p->size; ++i) {
  9431. float prob = candidates_p->data[i].p;
  9432. if (prob > 0.0f) { // Ensure no log(0)
  9433. entropy -= prob * logf(prob);
  9434. }
  9435. }
  9436. // Normalize the entropy (max_entropy cannot be 0 here because we checked candidates_p->size != 1 above)
  9437. float normalized_entropy = entropy / max_entropy;
  9438. // Map the normalized entropy to the desired temperature range using the power function
  9439. float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);
  9440. #ifdef DEBUG
  9441. LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
  9442. LLAMA_LOG_INFO("Entropy: %f\n", entropy);
  9443. LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
  9444. LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
  9445. LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
  9446. LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
  9447. #endif
  9448. // Apply the dynamically calculated temperature scaling
  9449. for (size_t i = 0; i < candidates_p->size; ++i) {
  9450. candidates_p->data[i].logit /= dyn_temp;
  9451. }
  9452. // Re-compute softmax probabilities after scaling logits with dynamic temperature
  9453. double max_l_double = candidates_p->data[0].logit;
  9454. double cum_sum_double = 0.0;
  9455. for (size_t i = 0; i < candidates_p->size; ++i) {
  9456. double p = exp(candidates_p->data[i].logit - max_l_double);
  9457. candidates_p->data[i].p = p; // Store the scaled probability
  9458. cum_sum_double += p;
  9459. }
  9460. for (size_t i = 0; i < candidates_p->size; ++i) {
  9461. candidates_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
  9462. }
  9463. #ifdef DEBUG
  9464. // Print the updated top 25 probabilities after temperature scaling
  9465. LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
  9466. for (size_t i = 0; i < 25 && i < candidates_p->size; ++i) {
  9467. LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, candidates_p->data[i].p * 100.0f);
  9468. }
  9469. #endif
  9470. if (ctx) {
  9471. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9472. }
  9473. }
  9474. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  9475. const int64_t t_start_sample_us = ggml_time_us();
  9476. for (size_t i = 0; i < candidates_p->size; ++i) {
  9477. candidates_p->data[i].logit /= temp;
  9478. }
  9479. if (ctx) {
  9480. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9481. }
  9482. }
  9483. void llama_sample_repetition_penalties(
  9484. struct llama_context * ctx,
  9485. llama_token_data_array * candidates,
  9486. const llama_token * last_tokens,
  9487. size_t penalty_last_n,
  9488. float penalty_repeat,
  9489. float penalty_freq,
  9490. float penalty_present) {
  9491. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  9492. return;
  9493. }
  9494. const int64_t t_start_sample_us = ggml_time_us();
  9495. // Create a frequency map to count occurrences of each token in last_tokens
  9496. std::unordered_map<llama_token, int> token_count;
  9497. for (size_t i = 0; i < penalty_last_n; ++i) {
  9498. token_count[last_tokens[i]]++;
  9499. }
  9500. // Apply frequency and presence penalties to the candidates
  9501. for (size_t i = 0; i < candidates->size; ++i) {
  9502. const auto token_iter = token_count.find(candidates->data[i].id);
  9503. if (token_iter == token_count.end()) {
  9504. continue;
  9505. }
  9506. const int count = token_iter->second;
  9507. // 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.
  9508. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  9509. if (candidates->data[i].logit <= 0) {
  9510. candidates->data[i].logit *= penalty_repeat;
  9511. } else {
  9512. candidates->data[i].logit /= penalty_repeat;
  9513. }
  9514. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  9515. }
  9516. candidates->sorted = false;
  9517. if (ctx) {
  9518. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9519. }
  9520. }
  9521. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  9522. GGML_ASSERT(ctx);
  9523. const int64_t t_start_sample_us = ggml_time_us();
  9524. bool allow_eos = false;
  9525. for (const auto & stack : grammar->stacks) {
  9526. if (stack.empty()) {
  9527. allow_eos = true;
  9528. break;
  9529. }
  9530. }
  9531. const llama_token eos = llama_token_eos(&ctx->model);
  9532. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  9533. candidates_decoded.reserve(candidates->size);
  9534. std::vector<llama_grammar_candidate> candidates_grammar;
  9535. candidates_grammar.reserve(candidates->size);
  9536. for (size_t i = 0; i < candidates->size; ++i) {
  9537. const llama_token id = candidates->data[i].id;
  9538. const std::string piece = llama_token_to_piece(ctx, id);
  9539. if (id == eos) {
  9540. if (!allow_eos) {
  9541. candidates->data[i].logit = -INFINITY;
  9542. }
  9543. } else if (piece.empty() || piece[0] == 0) {
  9544. candidates->data[i].logit = -INFINITY;
  9545. } else {
  9546. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  9547. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  9548. }
  9549. }
  9550. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  9551. for (const auto & reject : rejects) {
  9552. candidates->data[reject.index].logit = -INFINITY;
  9553. }
  9554. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9555. }
  9556. static void llama_log_softmax(float * array, size_t size) {
  9557. float max_l = *std::max_element(array, array + size);
  9558. float sum = 0.f;
  9559. for (size_t i = 0; i < size; ++i) {
  9560. float p = expf(array[i] - max_l);
  9561. sum += p;
  9562. array[i] = p;
  9563. }
  9564. for (size_t i = 0; i < size; ++i) {
  9565. array[i] = logf(array[i] / sum);
  9566. }
  9567. }
  9568. void llama_sample_apply_guidance(
  9569. struct llama_context * ctx,
  9570. float * logits,
  9571. float * logits_guidance,
  9572. float scale) {
  9573. GGML_ASSERT(ctx);
  9574. const auto t_start_sample_us = ggml_time_us();
  9575. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  9576. llama_log_softmax(logits, n_vocab);
  9577. llama_log_softmax(logits_guidance, n_vocab);
  9578. for (int i = 0; i < n_vocab; ++i) {
  9579. auto & l = logits[i];
  9580. const auto & g = logits_guidance[i];
  9581. l = scale * (l - g) + g;
  9582. }
  9583. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9584. }
  9585. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  9586. GGML_ASSERT(ctx);
  9587. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  9588. int64_t t_start_sample_us;
  9589. t_start_sample_us = ggml_time_us();
  9590. llama_sample_softmax(nullptr, candidates);
  9591. // Estimate s_hat using the most probable m tokens
  9592. float s_hat = 0.0;
  9593. float sum_ti_bi = 0.0;
  9594. float sum_ti_sq = 0.0;
  9595. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  9596. float t_i = logf(float(i + 2) / float(i + 1));
  9597. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  9598. sum_ti_bi += t_i * b_i;
  9599. sum_ti_sq += t_i * t_i;
  9600. }
  9601. s_hat = sum_ti_bi / sum_ti_sq;
  9602. // Compute k from the estimated s_hat and target surprise value
  9603. float epsilon_hat = s_hat - 1;
  9604. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  9605. // Sample the next word X using top-k sampling
  9606. llama_sample_top_k(nullptr, candidates, int(k), 1);
  9607. if (ctx) {
  9608. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9609. }
  9610. llama_token X = llama_sample_token(ctx, candidates);
  9611. t_start_sample_us = ggml_time_us();
  9612. // Compute error as the difference between observed surprise and target surprise value
  9613. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  9614. return candidate.id == X;
  9615. }));
  9616. float observed_surprise = -log2f(candidates->data[X_idx].p);
  9617. float e = observed_surprise - tau;
  9618. // Update mu using the learning rate and error
  9619. *mu = *mu - eta * e;
  9620. if (ctx) {
  9621. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9622. }
  9623. return X;
  9624. }
  9625. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  9626. int64_t t_start_sample_us;
  9627. t_start_sample_us = ggml_time_us();
  9628. llama_sample_softmax(ctx, candidates);
  9629. // Truncate the words with surprise values greater than mu
  9630. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  9631. return -log2f(candidate.p) > *mu;
  9632. }));
  9633. if (candidates->size == 0) {
  9634. candidates->size = 1;
  9635. }
  9636. if (ctx) {
  9637. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9638. }
  9639. // Normalize the probabilities of the remaining words
  9640. llama_sample_softmax(ctx, candidates);
  9641. // Sample the next word X from the remaining words
  9642. llama_token X = llama_sample_token(ctx, candidates);
  9643. t_start_sample_us = ggml_time_us();
  9644. // Compute error as the difference between observed surprise and target surprise value
  9645. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  9646. return candidate.id == X;
  9647. }));
  9648. float observed_surprise = -log2f(candidates->data[X_idx].p);
  9649. float e = observed_surprise - tau;
  9650. // Update mu using the learning rate and error
  9651. *mu = *mu - eta * e;
  9652. if (ctx) {
  9653. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9654. }
  9655. return X;
  9656. }
  9657. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  9658. const int64_t t_start_sample_us = ggml_time_us();
  9659. // Find max element
  9660. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  9661. return a.logit < b.logit;
  9662. });
  9663. llama_token result = max_iter->id;
  9664. if (ctx) {
  9665. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9666. ctx->n_sample++;
  9667. }
  9668. return result;
  9669. }
  9670. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  9671. GGML_ASSERT(ctx);
  9672. const int64_t t_start_sample_us = ggml_time_us();
  9673. llama_sample_softmax(nullptr, candidates);
  9674. std::vector<float> probs;
  9675. probs.reserve(candidates->size);
  9676. for (size_t i = 0; i < candidates->size; ++i) {
  9677. probs.push_back(candidates->data[i].p);
  9678. }
  9679. std::discrete_distribution<> dist(probs.begin(), probs.end());
  9680. auto & rng = ctx->rng;
  9681. int idx = dist(rng);
  9682. llama_token result = candidates->data[idx].id;
  9683. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9684. ctx->n_sample++;
  9685. return result;
  9686. }
  9687. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  9688. const int64_t t_start_sample_us = ggml_time_us();
  9689. if (token == llama_token_eos(&ctx->model)) {
  9690. for (const auto & stack : grammar->stacks) {
  9691. if (stack.empty()) {
  9692. return;
  9693. }
  9694. }
  9695. GGML_ASSERT(false);
  9696. }
  9697. const std::string piece = llama_token_to_piece(ctx, token);
  9698. // Note terminating 0 in decoded string
  9699. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  9700. const auto & code_points = decoded.first;
  9701. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  9702. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  9703. }
  9704. grammar->partial_utf8 = decoded.second;
  9705. GGML_ASSERT(!grammar->stacks.empty());
  9706. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9707. }
  9708. //
  9709. // Beam search
  9710. //
  9711. struct llama_beam {
  9712. std::vector<llama_token> tokens;
  9713. float p; // Cumulative beam probability (renormalized relative to all beams)
  9714. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  9715. // Sort beams by probability. In case of ties, prefer beams at eob.
  9716. bool operator<(const llama_beam & rhs) const {
  9717. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  9718. }
  9719. // Shift off first n tokens and discard them.
  9720. void shift_tokens(const size_t n) {
  9721. if (n) {
  9722. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  9723. tokens.resize(tokens.size() - n);
  9724. }
  9725. }
  9726. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  9727. };
  9728. // A struct for calculating logit-related info.
  9729. struct llama_logit_info {
  9730. const float * const logits;
  9731. const int n_vocab;
  9732. const float max_l;
  9733. const float normalizer;
  9734. struct sum_exp {
  9735. float max_l;
  9736. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  9737. };
  9738. llama_logit_info(llama_context * ctx)
  9739. : logits(llama_get_logits(ctx))
  9740. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  9741. , max_l(*std::max_element(logits, logits + n_vocab))
  9742. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  9743. { }
  9744. llama_token_data get_token_data(const llama_token token_id) const {
  9745. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  9746. return {token_id, logits[token_id], p};
  9747. }
  9748. // Return top k token_data by logit.
  9749. std::vector<llama_token_data> top_k(size_t k) {
  9750. std::vector<llama_token_data> min_heap; // min-heap by logit
  9751. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  9752. min_heap.reserve(k_min);
  9753. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  9754. min_heap.push_back(get_token_data(token_id));
  9755. }
  9756. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  9757. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  9758. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  9759. if (min_heap.front().logit < logits[token_id]) {
  9760. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  9761. min_heap.back().id = token_id;
  9762. min_heap.back().logit = logits[token_id];
  9763. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  9764. }
  9765. }
  9766. return min_heap;
  9767. }
  9768. float probability_from_logit(float logit) const {
  9769. return normalizer * std::exp(logit - max_l);
  9770. }
  9771. };
  9772. struct llama_beam_search_data {
  9773. llama_context * ctx;
  9774. size_t n_beams;
  9775. int n_past;
  9776. int n_predict;
  9777. std::vector<llama_beam> beams;
  9778. std::vector<llama_beam> next_beams;
  9779. // Re-calculated on each loop iteration
  9780. size_t common_prefix_length;
  9781. // Used to communicate to/from callback on beams state.
  9782. std::vector<llama_beam_view> beam_views;
  9783. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  9784. : ctx(ctx)
  9785. , n_beams(n_beams)
  9786. , n_past(n_past)
  9787. , n_predict(n_predict)
  9788. , beam_views(n_beams) {
  9789. beams.reserve(n_beams);
  9790. next_beams.reserve(n_beams);
  9791. }
  9792. // Collapse beams to a single beam given by index.
  9793. void collapse_beams(const size_t beam_idx) {
  9794. if (0u < beam_idx) {
  9795. std::swap(beams[0], beams[beam_idx]);
  9796. }
  9797. beams.resize(1);
  9798. }
  9799. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  9800. // The repetitive patterns below reflect the 2 stages of heaps:
  9801. // * Gather elements until the vector is full, then call std::make_heap() on it.
  9802. // * If the heap is full and a new element is found that should be included, pop the
  9803. // least element to the back(), replace it with the new, then push it into the heap.
  9804. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  9805. // Min-heaps use a greater-than comparator.
  9806. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  9807. if (beam.eob) {
  9808. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  9809. if (next_beams.size() < n_beams) {
  9810. next_beams.push_back(std::move(beam));
  9811. if (next_beams.size() == n_beams) {
  9812. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  9813. }
  9814. } else if (next_beams.front().p < beam.p) {
  9815. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  9816. next_beams.back() = std::move(beam);
  9817. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  9818. }
  9819. } else {
  9820. // beam is not at end-of-sentence, so branch with next top_k tokens.
  9821. if (!beam.tokens.empty()) {
  9822. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  9823. }
  9824. llama_logit_info logit_info(ctx);
  9825. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  9826. size_t i=0;
  9827. if (next_beams.size() < n_beams) {
  9828. for (; next_beams.size() < n_beams ; ++i) {
  9829. llama_beam next_beam = beam;
  9830. next_beam.tokens.push_back(next_tokens[i].id);
  9831. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  9832. next_beams.push_back(std::move(next_beam));
  9833. }
  9834. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  9835. } else {
  9836. for (; next_beams.front().p == 0.0f ; ++i) {
  9837. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  9838. next_beams.back() = beam;
  9839. next_beams.back().tokens.push_back(next_tokens[i].id);
  9840. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  9841. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  9842. }
  9843. }
  9844. for (; i < n_beams ; ++i) {
  9845. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  9846. if (next_beams.front().p < next_p) {
  9847. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  9848. next_beams.back() = beam;
  9849. next_beams.back().tokens.push_back(next_tokens[i].id);
  9850. next_beams.back().p = next_p;
  9851. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  9852. }
  9853. }
  9854. }
  9855. }
  9856. // Find common_prefix_length based on beams.
  9857. // Requires beams is not empty.
  9858. size_t find_common_prefix_length() {
  9859. size_t common_prefix_length = beams[0].tokens.size();
  9860. for (size_t i = 1 ; i < beams.size() ; ++i) {
  9861. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  9862. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  9863. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  9864. common_prefix_length = j;
  9865. break;
  9866. }
  9867. }
  9868. }
  9869. return common_prefix_length;
  9870. }
  9871. // Construct beams_state to send back to caller via the callback function.
  9872. // Side effect: set common_prefix_length = find_common_prefix_length();
  9873. llama_beams_state get_beams_state(const bool last_call) {
  9874. for (size_t i = 0 ; i < beams.size() ; ++i) {
  9875. beam_views[i] = beams[i].view();
  9876. }
  9877. common_prefix_length = find_common_prefix_length();
  9878. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  9879. }
  9880. // Loop:
  9881. // * while i < n_predict, AND
  9882. // * any of the beams have not yet reached end-of-beam (eob), AND
  9883. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  9884. // (since all other beam probabilities can only decrease)
  9885. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  9886. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  9887. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  9888. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  9889. !beams[top_beam_index()].eob ; ++i) {
  9890. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  9891. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  9892. if (common_prefix_length) {
  9893. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  9894. n_past += common_prefix_length;
  9895. }
  9896. // Zero-out next_beam probabilities to place them last in following min-heap.
  9897. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  9898. for (llama_beam & beam : beams) {
  9899. beam.shift_tokens(common_prefix_length);
  9900. fill_next_beams_by_top_probabilities(beam);
  9901. }
  9902. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  9903. beams.swap(next_beams);
  9904. renormalize_beam_probabilities(beams);
  9905. }
  9906. collapse_beams(top_beam_index());
  9907. callback(callback_data, get_beams_state(true));
  9908. }
  9909. // As beams grow, the cumulative probabilities decrease.
  9910. // Renormalize them to avoid floating point underflow.
  9911. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  9912. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  9913. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  9914. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  9915. }
  9916. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  9917. size_t top_beam_index() {
  9918. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  9919. }
  9920. // Copy (p,eob) for each beam which may have been changed by the callback.
  9921. void update_beams_from_beam_views() {
  9922. for (size_t i = 0 ; i < beams.size() ; ++i) {
  9923. beams[i].p = beam_views[i].p;
  9924. beams[i].eob = beam_views[i].eob;
  9925. }
  9926. }
  9927. };
  9928. void llama_beam_search(llama_context * ctx,
  9929. llama_beam_search_callback_fn_t callback, void * callback_data,
  9930. size_t n_beams, int n_past, int n_predict) {
  9931. assert(ctx);
  9932. const int64_t t_start_sample_us = ggml_time_us();
  9933. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  9934. beam_search_data.loop(callback, callback_data);
  9935. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9936. ctx->n_sample++;
  9937. }
  9938. //
  9939. // quantization
  9940. //
  9941. struct quantize_state_internal {
  9942. const llama_model & model;
  9943. const llama_model_quantize_params * params;
  9944. int n_attention_wv = 0;
  9945. int n_ffn_down = 0;
  9946. int n_ffn_gate = 0;
  9947. int n_ffn_up = 0;
  9948. int i_attention_wv = 0;
  9949. int i_ffn_down = 0;
  9950. int i_ffn_gate = 0;
  9951. int i_ffn_up = 0;
  9952. int n_k_quantized = 0;
  9953. int n_fallback = 0;
  9954. bool has_imatrix = false;
  9955. // used to figure out if a model shares tok_embd with the output weight
  9956. bool has_output = false;
  9957. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  9958. : model(model)
  9959. , params(params)
  9960. {}
  9961. };
  9962. static void llama_tensor_dequantize_internal(
  9963. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  9964. const size_t nelements, const int nthread
  9965. ) {
  9966. if (output.size() < nelements) {
  9967. output.resize(nelements);
  9968. }
  9969. float * f32_output = (float *) output.data();
  9970. ggml_type_traits_t qtype;
  9971. if (ggml_is_quantized(tensor->type)) {
  9972. qtype = ggml_internal_get_type_traits(tensor->type);
  9973. if (qtype.to_float == NULL) {
  9974. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  9975. }
  9976. } else if (tensor->type != GGML_TYPE_F16) {
  9977. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  9978. }
  9979. if (nthread < 2) {
  9980. if (tensor->type == GGML_TYPE_F16) {
  9981. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  9982. } else if (ggml_is_quantized(tensor->type)) {
  9983. qtype.to_float(tensor->data, f32_output, nelements);
  9984. } else {
  9985. GGML_ASSERT(false); // unreachable
  9986. }
  9987. return;
  9988. }
  9989. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  9990. size_t block_size_bytes = ggml_type_size(tensor->type);
  9991. GGML_ASSERT(nelements % block_size == 0);
  9992. size_t nblocks = nelements / block_size;
  9993. size_t blocks_per_thread = nblocks / nthread;
  9994. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  9995. size_t in_buff_offs = 0;
  9996. size_t out_buff_offs = 0;
  9997. for (int tnum = 0; tnum < nthread; tnum++) {
  9998. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  9999. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  10000. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  10001. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  10002. if (typ == GGML_TYPE_F16) {
  10003. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  10004. } else {
  10005. qtype.to_float(inbuf, outbuf, nels);
  10006. }
  10007. };
  10008. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  10009. in_buff_offs += thr_block_bytes;
  10010. out_buff_offs += thr_elems;
  10011. }
  10012. for (auto & w : workers) { w.join(); }
  10013. workers.clear();
  10014. }
  10015. static ggml_type llama_tensor_get_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  10016. const std::string name = ggml_get_name(tensor);
  10017. // TODO: avoid hardcoded tensor names - use the TN_* constants
  10018. const llm_arch arch = qs.model.arch;
  10019. const auto tn = LLM_TN(arch);
  10020. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  10021. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  10022. };
  10023. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  10024. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  10025. if (n_expert > 1) {
  10026. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  10027. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  10028. // for getting the current layer as I initially thought, and we need to resort to parsing the
  10029. // tensor name.
  10030. n_layer /= n_expert;
  10031. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  10032. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  10033. }
  10034. if (i_layer < 0 || i_layer >= n_layer) {
  10035. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  10036. }
  10037. }
  10038. return std::make_pair(i_layer, n_layer);
  10039. };
  10040. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  10041. // with the quantization of the output tensor
  10042. if (name == tn(LLM_TENSOR_OUTPUT, "weight") || (!qs.has_output && name == tn(LLM_TENSOR_TOKEN_EMBD, "weight"))) {
  10043. if (qs.params->output_tensor_type < GGML_TYPE_COUNT) {
  10044. new_type = qs.params->output_tensor_type;
  10045. } else {
  10046. int nx = tensor->ne[0];
  10047. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  10048. new_type = GGML_TYPE_Q8_0;
  10049. }
  10050. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  10051. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  10052. new_type = GGML_TYPE_Q5_K;
  10053. }
  10054. else if (new_type != GGML_TYPE_Q8_0) {
  10055. new_type = GGML_TYPE_Q6_K;
  10056. }
  10057. }
  10058. } else if (name == "token_embd.weight") {
  10059. if (qs.params->token_embedding_type < GGML_TYPE_COUNT) {
  10060. new_type = qs.params->token_embedding_type;
  10061. } else {
  10062. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) {
  10063. new_type = GGML_TYPE_Q2_K;
  10064. }
  10065. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  10066. new_type = GGML_TYPE_IQ3_S;
  10067. }
  10068. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10069. new_type = GGML_TYPE_IQ3_S;
  10070. }
  10071. }
  10072. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  10073. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  10074. if (name.find("attn_v.weight") != std::string::npos) {
  10075. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  10076. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  10077. ++qs.i_attention_wv;
  10078. }
  10079. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  10080. new_type = GGML_TYPE_Q4_K;
  10081. }
  10082. else if (name.find("ffn_down") != std::string::npos) {
  10083. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  10084. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  10085. }
  10086. ++qs.i_ffn_down;
  10087. }
  10088. else if (name.find("attn_output.weight") != std::string::npos) {
  10089. if (qs.model.hparams.n_expert == 8) {
  10090. new_type = GGML_TYPE_Q5_K;
  10091. } else {
  10092. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) new_type = GGML_TYPE_IQ2_XXS;
  10093. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  10094. }
  10095. }
  10096. } else if (name.find("attn_v.weight") != std::string::npos) {
  10097. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  10098. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  10099. }
  10100. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  10101. new_type = GGML_TYPE_Q4_K;
  10102. }
  10103. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10104. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  10105. }
  10106. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S) && qs.model.hparams.n_gqa() >= 4) {
  10107. new_type = GGML_TYPE_Q4_K;
  10108. }
  10109. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  10110. new_type = GGML_TYPE_Q4_K;
  10111. }
  10112. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  10113. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  10114. }
  10115. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  10116. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  10117. new_type = GGML_TYPE_Q5_K;
  10118. }
  10119. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  10120. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  10121. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  10122. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  10123. (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;
  10124. if (qs.model.type == MODEL_70B) {
  10125. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  10126. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  10127. // nearly negligible increase in model size by quantizing this tensor with more bits:
  10128. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  10129. }
  10130. if (qs.model.hparams.n_expert == 8) {
  10131. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  10132. // TODO: explore better strategies
  10133. new_type = GGML_TYPE_Q8_0;
  10134. }
  10135. ++qs.i_attention_wv;
  10136. } else if (name.find("attn_k.weight") != std::string::npos) {
  10137. if (qs.model.hparams.n_expert == 8) {
  10138. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  10139. // TODO: explore better strategies
  10140. new_type = GGML_TYPE_Q8_0;
  10141. }
  10142. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  10143. new_type = GGML_TYPE_IQ3_XXS;
  10144. }
  10145. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10146. new_type = GGML_TYPE_IQ2_S;
  10147. }
  10148. } else if (name.find("attn_q.weight") != std::string::npos) {
  10149. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  10150. new_type = GGML_TYPE_IQ3_XXS;
  10151. }
  10152. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10153. new_type = GGML_TYPE_IQ2_S;
  10154. }
  10155. } else if (name.find("ffn_down") != std::string::npos) {
  10156. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  10157. int i_layer = info.first, n_layer = info.second;
  10158. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  10159. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  10160. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  10161. }
  10162. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  10163. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  10164. }
  10165. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  10166. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  10167. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  10168. : GGML_TYPE_Q3_K;
  10169. }
  10170. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  10171. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  10172. new_type = GGML_TYPE_Q4_K;
  10173. }
  10174. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  10175. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  10176. }
  10177. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  10178. if (arch == LLM_ARCH_FALCON) {
  10179. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  10180. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  10181. } else {
  10182. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  10183. }
  10184. }
  10185. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  10186. new_type = GGML_TYPE_Q5_K;
  10187. }
  10188. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  10189. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  10190. new_type = GGML_TYPE_Q5_K;
  10191. }
  10192. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  10193. && qs.has_imatrix && i_layer < n_layer/8) {
  10194. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  10195. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  10196. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  10197. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  10198. }
  10199. ++qs.i_ffn_down;
  10200. } else if (name.find("attn_output.weight") != std::string::npos) {
  10201. if (arch != LLM_ARCH_FALCON) {
  10202. if (qs.model.hparams.n_expert == 8) {
  10203. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  10204. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  10205. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  10206. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  10207. new_type = GGML_TYPE_Q5_K;
  10208. }
  10209. } else {
  10210. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  10211. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  10212. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  10213. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  10214. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  10215. }
  10216. } else {
  10217. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  10218. }
  10219. }
  10220. else if (name.find("attn_qkv.weight") != std::string::npos) {
  10221. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  10222. new_type = GGML_TYPE_Q4_K;
  10223. }
  10224. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  10225. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  10226. }
  10227. else if (name.find("ffn_gate") != std::string::npos) {
  10228. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  10229. int i_layer = info.first, n_layer = info.second;
  10230. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  10231. new_type = GGML_TYPE_IQ3_XXS;
  10232. }
  10233. ++qs.i_ffn_gate;
  10234. }
  10235. else if (name.find("ffn_up") != std::string::npos) {
  10236. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  10237. int i_layer = info.first, n_layer = info.second;
  10238. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  10239. new_type = GGML_TYPE_IQ3_XXS;
  10240. }
  10241. ++qs.i_ffn_up;
  10242. }
  10243. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  10244. //}
  10245. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  10246. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  10247. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  10248. //}
  10249. // This can be used to reduce the size of the Q5_K_S model.
  10250. // The associated PPL increase is fully in line with the size reduction
  10251. //else {
  10252. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  10253. //}
  10254. bool convert_incompatible_tensor = false;
  10255. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  10256. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  10257. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  10258. new_type == GGML_TYPE_IQ3_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || new_type == GGML_TYPE_IQ3_S) {
  10259. int nx = tensor->ne[0];
  10260. int ny = tensor->ne[1];
  10261. if (nx % QK_K != 0) {
  10262. 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));
  10263. convert_incompatible_tensor = true;
  10264. } else {
  10265. ++qs.n_k_quantized;
  10266. }
  10267. }
  10268. if (convert_incompatible_tensor) {
  10269. switch (new_type) {
  10270. case GGML_TYPE_IQ2_XXS:
  10271. case GGML_TYPE_IQ2_XS:
  10272. case GGML_TYPE_IQ2_S:
  10273. case GGML_TYPE_IQ3_XXS:
  10274. case GGML_TYPE_IQ3_S:
  10275. case GGML_TYPE_IQ1_S:
  10276. case GGML_TYPE_Q2_K:
  10277. case GGML_TYPE_Q3_K:
  10278. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  10279. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  10280. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  10281. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  10282. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  10283. }
  10284. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  10285. ++qs.n_fallback;
  10286. }
  10287. return new_type;
  10288. }
  10289. static size_t llama_tensor_quantize_internal(enum ggml_type new_type, const float * f32_data, void * new_data, const int chunk_size, int nrows, int n_per_row, const float * imatrix, std::vector<std::thread> & workers, const int nthread) {
  10290. std::mutex mutex;
  10291. int counter = 0;
  10292. size_t new_size = 0;
  10293. if (nthread < 2) {
  10294. // single-thread
  10295. return ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, imatrix);
  10296. }
  10297. auto compute = [&mutex, &counter, &new_size, new_type, f32_data, new_data, chunk_size,
  10298. nrows, n_per_row, imatrix]() {
  10299. const int nrows_per_chunk = chunk_size / n_per_row;
  10300. size_t local_size = 0;
  10301. while (true) {
  10302. std::unique_lock<std::mutex> lock(mutex);
  10303. int first_row = counter; counter += nrows_per_chunk;
  10304. if (first_row >= nrows) {
  10305. if (local_size > 0) {
  10306. new_size += local_size;
  10307. }
  10308. break;
  10309. }
  10310. lock.unlock();
  10311. const int this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  10312. local_size += ggml_quantize_chunk(new_type, f32_data, new_data, first_row * n_per_row, this_nrow, n_per_row, imatrix);
  10313. }
  10314. };
  10315. for (int it = 0; it < nthread - 1; ++it) {
  10316. workers.emplace_back(compute);
  10317. }
  10318. compute();
  10319. for (auto & w : workers) { w.join(); }
  10320. workers.clear();
  10321. return new_size;
  10322. }
  10323. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  10324. ggml_type default_type;
  10325. llama_ftype ftype = params->ftype;
  10326. switch (params->ftype) {
  10327. case LLAMA_FTYPE_MOSTLY_Q4_0: default_type = GGML_TYPE_Q4_0; break;
  10328. case LLAMA_FTYPE_MOSTLY_Q4_1: default_type = GGML_TYPE_Q4_1; break;
  10329. case LLAMA_FTYPE_MOSTLY_Q5_0: default_type = GGML_TYPE_Q5_0; break;
  10330. case LLAMA_FTYPE_MOSTLY_Q5_1: default_type = GGML_TYPE_Q5_1; break;
  10331. case LLAMA_FTYPE_MOSTLY_Q8_0: default_type = GGML_TYPE_Q8_0; break;
  10332. case LLAMA_FTYPE_MOSTLY_F16: default_type = GGML_TYPE_F16; break;
  10333. case LLAMA_FTYPE_ALL_F32: default_type = GGML_TYPE_F32; break;
  10334. // K-quants
  10335. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  10336. case LLAMA_FTYPE_MOSTLY_Q2_K: default_type = GGML_TYPE_Q2_K; break;
  10337. case LLAMA_FTYPE_MOSTLY_IQ3_XS: default_type = GGML_TYPE_IQ3_S; break;
  10338. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  10339. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  10340. case LLAMA_FTYPE_MOSTLY_Q3_K_L: default_type = GGML_TYPE_Q3_K; break;
  10341. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  10342. case LLAMA_FTYPE_MOSTLY_Q4_K_M: default_type = GGML_TYPE_Q4_K; break;
  10343. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  10344. case LLAMA_FTYPE_MOSTLY_Q5_K_M: default_type = GGML_TYPE_Q5_K; break;
  10345. case LLAMA_FTYPE_MOSTLY_Q6_K: default_type = GGML_TYPE_Q6_K; break;
  10346. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: default_type = GGML_TYPE_IQ2_XXS; break;
  10347. case LLAMA_FTYPE_MOSTLY_IQ2_XS: default_type = GGML_TYPE_IQ2_XS; break;
  10348. case LLAMA_FTYPE_MOSTLY_IQ2_S: default_type = GGML_TYPE_IQ2_XS; break;
  10349. case LLAMA_FTYPE_MOSTLY_IQ2_M: default_type = GGML_TYPE_IQ2_S; break;
  10350. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: default_type = GGML_TYPE_IQ3_XXS; break;
  10351. case LLAMA_FTYPE_MOSTLY_IQ1_S: default_type = GGML_TYPE_IQ1_S; break;
  10352. case LLAMA_FTYPE_MOSTLY_IQ4_NL: default_type = GGML_TYPE_IQ4_NL; break;
  10353. case LLAMA_FTYPE_MOSTLY_IQ4_XS: default_type = GGML_TYPE_IQ4_XS; break;
  10354. case LLAMA_FTYPE_MOSTLY_IQ3_S: default_type = GGML_TYPE_IQ3_S; break;
  10355. case LLAMA_FTYPE_MOSTLY_IQ3_M: default_type = GGML_TYPE_IQ3_S; break;
  10356. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  10357. }
  10358. int nthread = params->nthread;
  10359. if (nthread <= 0) {
  10360. nthread = std::thread::hardware_concurrency();
  10361. }
  10362. // mmap consistently increases speed Linux, and also increases speed on Windows with
  10363. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  10364. #if defined(__linux__) || defined(_WIN32)
  10365. constexpr bool use_mmap = true;
  10366. #else
  10367. constexpr bool use_mmap = false;
  10368. #endif
  10369. llama_model_loader ml(fname_inp, use_mmap, NULL);
  10370. ml.init_mappings(false); // no prefetching?
  10371. llama_model model;
  10372. llm_load_arch(ml, model);
  10373. llm_load_hparams(ml, model);
  10374. struct quantize_state_internal qs(model, params);
  10375. if (params->only_copy) {
  10376. ftype = model.ftype;
  10377. }
  10378. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  10379. if (params->imatrix) {
  10380. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  10381. if (imatrix_data) {
  10382. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  10383. qs.has_imatrix = true;
  10384. }
  10385. }
  10386. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  10387. struct gguf_context * ctx_out = gguf_init_empty();
  10388. // copy the KV pairs from the input file
  10389. gguf_set_kv (ctx_out, ml.meta);
  10390. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  10391. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  10392. for (int i = 0; i < ml.n_tensors; ++i) {
  10393. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  10394. const std::string name = ggml_get_name(meta);
  10395. // TODO: avoid hardcoded tensor names - use the TN_* constants
  10396. if (name.find("attn_v.weight") != std::string::npos || name.find("attn_qkv.weight") != std::string::npos) {
  10397. ++qs.n_attention_wv;
  10398. }
  10399. else if (name.find("ffn_down") != std::string::npos) {
  10400. ++qs.n_ffn_down;
  10401. }
  10402. else if (name.find("ffn_gate") != std::string::npos) {
  10403. ++qs.n_ffn_gate;
  10404. }
  10405. else if (name.find("ffn_up") != std::string::npos) {
  10406. ++qs.n_ffn_up;
  10407. }
  10408. else if (name == LLM_TN(model.arch)(LLM_TENSOR_OUTPUT, "weight")) {
  10409. qs.has_output = true;
  10410. }
  10411. }
  10412. if (qs.n_attention_wv != qs.n_ffn_down || (uint32_t)qs.n_attention_wv != model.hparams.n_layer) {
  10413. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_ffn_down = %d, hparams.n_layer = %d\n",
  10414. __func__, qs.n_attention_wv, qs.n_ffn_down, model.hparams.n_layer);
  10415. }
  10416. size_t total_size_org = 0;
  10417. size_t total_size_new = 0;
  10418. std::vector<std::thread> workers;
  10419. workers.reserve(nthread);
  10420. int idx = 0;
  10421. std::vector<no_init<uint8_t>> read_data;
  10422. std::vector<no_init<uint8_t>> work;
  10423. std::vector<no_init<float>> f32_conv_buf;
  10424. // populate the original tensors so we get an initial meta data
  10425. for (int i = 0; i < ml.n_tensors; ++i) {
  10426. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  10427. gguf_add_tensor(ctx_out, meta);
  10428. }
  10429. std::ofstream fout(fname_out, std::ios::binary);
  10430. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  10431. const size_t meta_size = gguf_get_meta_size(ctx_out);
  10432. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  10433. // placeholder for the meta data
  10434. ::zeros(fout, meta_size);
  10435. for (int i = 0; i < ml.n_tensors; ++i) {
  10436. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  10437. const std::string name = ggml_get_name(tensor);
  10438. if (!ml.use_mmap) {
  10439. if (read_data.size() < ggml_nbytes(tensor)) {
  10440. read_data.resize(ggml_nbytes(tensor));
  10441. }
  10442. tensor->data = read_data.data();
  10443. }
  10444. ml.load_data_for(tensor);
  10445. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  10446. ++idx, ml.n_tensors,
  10447. ggml_get_name(tensor),
  10448. llama_format_tensor_shape(tensor).c_str(),
  10449. ggml_type_name(tensor->type));
  10450. // This used to be a regex, but <regex> has an extreme cost to compile times.
  10451. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  10452. // quantize only 2D tensors
  10453. quantize &= (ggml_n_dims(tensor) == 2);
  10454. quantize &= params->quantize_output_tensor || name != "output.weight";
  10455. quantize &= !params->only_copy;
  10456. // do not quantize expert gating tensors
  10457. // NOTE: can't use LLM_TN here because the layer number is not known
  10458. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  10459. // do not quantize positional embeddings and token types (BERT)
  10460. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  10461. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  10462. // do not quantize Mamba's small yet 2D weights
  10463. // NOTE: can't use LLM_TN here because the layer number is not known
  10464. quantize &= name.find("ssm_conv1d.weight") == std::string::npos;
  10465. quantize &= name.find("ssm_x.weight") == std::string::npos;
  10466. quantize &= name.find("ssm_dt.weight") == std::string::npos;
  10467. enum ggml_type new_type;
  10468. void * new_data;
  10469. size_t new_size;
  10470. if (quantize) {
  10471. new_type = default_type;
  10472. // get more optimal quantization type based on the tensor shape, layer, etc.
  10473. if (!params->pure && ggml_is_quantized(default_type)) {
  10474. new_type = llama_tensor_get_type(qs, new_type, tensor, ftype);
  10475. }
  10476. // If we've decided to quantize to the same type the tensor is already
  10477. // in then there's nothing to do.
  10478. quantize = tensor->type != new_type;
  10479. }
  10480. if (!quantize) {
  10481. new_type = tensor->type;
  10482. new_data = tensor->data;
  10483. new_size = ggml_nbytes(tensor);
  10484. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  10485. } else {
  10486. const size_t nelements = ggml_nelements(tensor);
  10487. const float * imatrix = nullptr;
  10488. if (imatrix_data) {
  10489. auto it = imatrix_data->find(tensor->name);
  10490. if (it == imatrix_data->end()) {
  10491. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  10492. } else {
  10493. if (it->second.size() == (size_t)tensor->ne[0]) {
  10494. imatrix = it->second.data();
  10495. } else {
  10496. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  10497. int(it->second.size()), int(tensor->ne[0]), tensor->name);
  10498. }
  10499. }
  10500. }
  10501. if ((new_type == GGML_TYPE_IQ2_XXS ||
  10502. new_type == GGML_TYPE_IQ2_XS ||
  10503. new_type == GGML_TYPE_IQ2_S ||
  10504. new_type == GGML_TYPE_IQ1_S ||
  10505. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  10506. LLAMA_LOG_ERROR("\n\n============================================================\n");
  10507. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  10508. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  10509. LLAMA_LOG_ERROR("============================================================\n\n");
  10510. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  10511. }
  10512. float * f32_data;
  10513. if (tensor->type == GGML_TYPE_F32) {
  10514. f32_data = (float *) tensor->data;
  10515. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  10516. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  10517. } else {
  10518. llama_tensor_dequantize_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  10519. f32_data = (float *) f32_conv_buf.data();
  10520. }
  10521. LLAMA_LOG_INFO("converting to %s .. ", ggml_type_name(new_type));
  10522. fflush(stdout);
  10523. if (work.size() < nelements * 4) {
  10524. work.resize(nelements * 4); // upper bound on size
  10525. }
  10526. new_data = work.data();
  10527. const int n_per_row = tensor->ne[0];
  10528. const int nrows = nelements / n_per_row;
  10529. static const int min_chunk_size = 32 * 512;
  10530. const int chunk_size = n_per_row >= min_chunk_size ? n_per_row : n_per_row * ((min_chunk_size + n_per_row - 1)/n_per_row);
  10531. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  10532. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  10533. new_size = llama_tensor_quantize_internal(new_type, f32_data, new_data, chunk_size, nrows, n_per_row, imatrix, workers, nthread_use);
  10534. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB\n", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  10535. }
  10536. total_size_org += ggml_nbytes(tensor);
  10537. total_size_new += new_size;
  10538. // update the gguf meta data as we go
  10539. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  10540. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  10541. // write tensor data + padding
  10542. fout.write((const char *) new_data, new_size);
  10543. zeros(fout, GGML_PAD(new_size, align) - new_size);
  10544. }
  10545. // go back to beginning of file and write the updated meta data
  10546. {
  10547. fout.seekp(0);
  10548. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  10549. gguf_get_meta_data(ctx_out, data.data());
  10550. fout.write((const char *) data.data(), data.size());
  10551. }
  10552. fout.close();
  10553. gguf_free(ctx_out);
  10554. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  10555. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  10556. if (qs.n_fallback > 0) {
  10557. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n",
  10558. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  10559. }
  10560. }
  10561. static int llama_apply_lora_from_file_internal(
  10562. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  10563. ) {
  10564. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  10565. const int64_t t_start_lora_us = ggml_time_us();
  10566. llama_file fin(path_lora, "rb");
  10567. // verify magic and version
  10568. {
  10569. uint32_t magic = fin.read_u32();
  10570. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  10571. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  10572. return 1;
  10573. }
  10574. uint32_t format_version = fin.read_u32();
  10575. if (format_version != 1) {
  10576. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  10577. return 1;
  10578. }
  10579. }
  10580. int32_t lora_r = fin.read_u32();
  10581. int32_t lora_alpha = fin.read_u32();
  10582. float scaling = scale * (float)lora_alpha / (float)lora_r;
  10583. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  10584. // load base model
  10585. std::unique_ptr<llama_model_loader> ml;
  10586. if (path_base_model) {
  10587. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  10588. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  10589. ml->init_mappings(/*prefetch*/ false); // no prefetching
  10590. }
  10591. struct tensor_meta {
  10592. std::string name;
  10593. ggml_type type;
  10594. int32_t ne[2];
  10595. size_t offset;
  10596. };
  10597. std::map<std::string, tensor_meta> tensor_meta_map;
  10598. // load all tensor meta
  10599. while (true) {
  10600. if (fin.tell() == fin.size) {
  10601. // eof
  10602. break;
  10603. }
  10604. int32_t n_dims;
  10605. int32_t name_len;
  10606. int32_t ftype;
  10607. fin.read_raw(&n_dims, sizeof(n_dims));
  10608. fin.read_raw(&name_len, sizeof(name_len));
  10609. fin.read_raw(&ftype, sizeof(ftype));
  10610. if (n_dims != 1 && n_dims != 2) {
  10611. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  10612. return 1;
  10613. }
  10614. int32_t ne[2] = { 1, 1 };
  10615. for (int i = 0; i < n_dims; ++i) {
  10616. fin.read_raw(&ne[i], sizeof(ne[i]));
  10617. }
  10618. std::string name;
  10619. {
  10620. GGML_ASSERT(name_len < GGML_MAX_NAME);
  10621. char buf[GGML_MAX_NAME];
  10622. fin.read_raw(buf, name_len);
  10623. name = std::string(buf, name_len);
  10624. }
  10625. // check for lora suffix
  10626. std::string lora_suffix;
  10627. if (name.length() > 6) {
  10628. lora_suffix = name.substr(name.length() - 6);
  10629. }
  10630. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  10631. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  10632. return 1;
  10633. }
  10634. // tensor type
  10635. ggml_type wtype;
  10636. switch (ftype) {
  10637. case 0: wtype = GGML_TYPE_F32; break;
  10638. case 1: wtype = GGML_TYPE_F16; break;
  10639. default:
  10640. {
  10641. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  10642. __func__, ftype);
  10643. return 1;
  10644. }
  10645. }
  10646. // data offset
  10647. size_t offset = fin.tell();
  10648. offset = (offset + 31) & -32;
  10649. // skip tensor data
  10650. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  10651. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  10652. }
  10653. bool warned = false;
  10654. int n_tensors = 0;
  10655. // apply
  10656. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  10657. if (backend_cpu == nullptr) {
  10658. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  10659. return 1;
  10660. }
  10661. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  10662. std::vector<no_init<uint8_t>> read_buf;
  10663. for (const auto & it : model.tensors_by_name) {
  10664. const std::string & base_name = it.first;
  10665. ggml_tensor * model_t = it.second;
  10666. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  10667. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  10668. continue;
  10669. }
  10670. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  10671. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  10672. ggml_init_params lora_init_params = {
  10673. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  10674. /* .mem_buffer */ nullptr,
  10675. /* .no_alloc */ true,
  10676. };
  10677. ggml_context * lora_ctx = ggml_init(lora_init_params);
  10678. if (lora_ctx == nullptr) {
  10679. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  10680. ggml_backend_free(backend_cpu);
  10681. return 1;
  10682. }
  10683. // create tensors
  10684. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  10685. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  10686. ggml_set_name(loraA, metaA.name.c_str());
  10687. ggml_set_name(loraB, metaB.name.c_str());
  10688. ggml_tensor * base_t;
  10689. if (ml) {
  10690. if (!ml->get_tensor_meta(base_name.c_str())) {
  10691. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  10692. return 1;
  10693. }
  10694. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  10695. } else {
  10696. base_t = ggml_dup_tensor(lora_ctx, model_t);
  10697. }
  10698. ggml_set_name(base_t, base_name.c_str());
  10699. // allocate in backend buffer
  10700. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  10701. if (lora_buf == nullptr) {
  10702. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  10703. return 1;
  10704. }
  10705. // load tensor data
  10706. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  10707. read_buf.resize(ggml_nbytes(tensor));
  10708. fin.seek(tensor_meta.offset, SEEK_SET);
  10709. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  10710. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  10711. };
  10712. load_tensor(metaA, loraA);
  10713. load_tensor(metaB, loraB);
  10714. // load base model tensor data
  10715. if (ml) {
  10716. ml->load_data_for(base_t);
  10717. } else {
  10718. ggml_backend_tensor_copy(model_t, base_t);
  10719. }
  10720. if (ggml_is_quantized(base_t->type) && !warned) {
  10721. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  10722. "use a f16 or f32 base model with --lora-base\n", __func__);
  10723. warned = true;
  10724. }
  10725. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  10726. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  10727. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  10728. ggml_free(lora_ctx);
  10729. ggml_backend_buffer_free(lora_buf);
  10730. ggml_backend_free(backend_cpu);
  10731. return 1;
  10732. }
  10733. auto build_lora_graph = [&]() {
  10734. // w = w + BA*s
  10735. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  10736. ggml_set_name(BA, "BA");
  10737. if (scaling != 1.0f) {
  10738. BA = ggml_scale(lora_ctx, BA, scaling);
  10739. ggml_set_name(BA, "BA_scaled");
  10740. }
  10741. ggml_tensor * r;
  10742. r = ggml_add_inplace(lora_ctx, base_t, BA);
  10743. ggml_set_name(r, "r_add");
  10744. if (base_t->type != model_t->type) {
  10745. // convert the result to the model type
  10746. r = ggml_cast(lora_ctx, r, model_t->type);
  10747. ggml_set_name(r, "r_cast");
  10748. }
  10749. return r;
  10750. };
  10751. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  10752. ggml_tensor * r = build_lora_graph();
  10753. ggml_build_forward_expand(gf, r);
  10754. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  10755. if (graph_buf == nullptr) {
  10756. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  10757. ggml_free(lora_ctx);
  10758. ggml_backend_buffer_free(lora_buf);
  10759. ggml_backend_free(backend_cpu);
  10760. return 1;
  10761. }
  10762. ggml_backend_graph_compute(backend_cpu, gf);
  10763. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  10764. #if 0
  10765. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  10766. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  10767. // sched compute
  10768. ggml_build_forward_expand(gf, build_graph());
  10769. ggml_backend_sched_init_measure(sched, gf);
  10770. // create the graph again, since the previous one was destroyed by the measure
  10771. ggml_graph_clear(gf);
  10772. ggml_build_forward_expand(gf, build_graph());
  10773. ggml_backend_sched_graph_compute(sched, gf);
  10774. ggml_backend_sched_free(sched);
  10775. #endif
  10776. ggml_backend_buffer_free(lora_buf);
  10777. ggml_backend_buffer_free(graph_buf);
  10778. ggml_free(lora_ctx);
  10779. n_tensors++;
  10780. if (n_tensors % 4 == 0) {
  10781. LLAMA_LOG_INFO(".");
  10782. }
  10783. }
  10784. ggml_backend_free(backend_cpu);
  10785. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  10786. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  10787. return 0;
  10788. }
  10789. //
  10790. // interface implementation
  10791. //
  10792. struct llama_model_params llama_model_default_params() {
  10793. struct llama_model_params result = {
  10794. /*.n_gpu_layers =*/ 0,
  10795. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  10796. /*.main_gpu =*/ 0,
  10797. /*.tensor_split =*/ nullptr,
  10798. /*.progress_callback =*/ nullptr,
  10799. /*.progress_callback_user_data =*/ nullptr,
  10800. /*.kv_overrides =*/ nullptr,
  10801. /*.vocab_only =*/ false,
  10802. /*.use_mmap =*/ true,
  10803. /*.use_mlock =*/ false,
  10804. };
  10805. #ifdef GGML_USE_METAL
  10806. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  10807. result.n_gpu_layers = 999;
  10808. #endif
  10809. return result;
  10810. }
  10811. struct llama_context_params llama_context_default_params() {
  10812. struct llama_context_params result = {
  10813. /*.seed =*/ LLAMA_DEFAULT_SEED,
  10814. /*.n_ctx =*/ 512,
  10815. /*.n_batch =*/ 2048,
  10816. /*.n_ubatch =*/ 512,
  10817. /*.n_seq_max =*/ 1,
  10818. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  10819. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  10820. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  10821. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  10822. /*.rope_freq_base =*/ 0.0f,
  10823. /*.rope_freq_scale =*/ 0.0f,
  10824. /*.yarn_ext_factor =*/ -1.0f,
  10825. /*.yarn_attn_factor =*/ 1.0f,
  10826. /*.yarn_beta_fast =*/ 32.0f,
  10827. /*.yarn_beta_slow =*/ 1.0f,
  10828. /*.yarn_orig_ctx =*/ 0,
  10829. /*.defrag_thold =*/ -1.0f,
  10830. /*.cb_eval =*/ nullptr,
  10831. /*.cb_eval_user_data =*/ nullptr,
  10832. /*.type_k =*/ GGML_TYPE_F16,
  10833. /*.type_v =*/ GGML_TYPE_F16,
  10834. /*.logits_all =*/ false,
  10835. /*.embeddings =*/ false,
  10836. /*.offload_kqv =*/ true,
  10837. /*.abort_callback =*/ nullptr,
  10838. /*.abort_callback_data =*/ nullptr,
  10839. };
  10840. return result;
  10841. }
  10842. struct llama_model_quantize_params llama_model_quantize_default_params() {
  10843. struct llama_model_quantize_params result = {
  10844. /*.nthread =*/ 0,
  10845. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  10846. /*.output_tensor_type =*/ GGML_TYPE_COUNT,
  10847. /*.token_embedding_type =*/ GGML_TYPE_COUNT,
  10848. /*.allow_requantize =*/ false,
  10849. /*.quantize_output_tensor =*/ true,
  10850. /*.only_copy =*/ false,
  10851. /*.pure =*/ false,
  10852. /*.imatrix =*/ nullptr,
  10853. };
  10854. return result;
  10855. }
  10856. size_t llama_max_devices(void) {
  10857. #if defined(GGML_USE_METAL)
  10858. return 1;
  10859. #elif defined(GGML_USE_CUBLAS)
  10860. return GGML_CUDA_MAX_DEVICES;
  10861. #elif defined(GGML_USE_SYCL)
  10862. return GGML_SYCL_MAX_DEVICES;
  10863. #elif defined(GGML_USE_VULKAN)
  10864. return GGML_VK_MAX_DEVICES;
  10865. #else
  10866. return 1;
  10867. #endif
  10868. }
  10869. bool llama_supports_mmap(void) {
  10870. return llama_mmap::SUPPORTED;
  10871. }
  10872. bool llama_supports_mlock(void) {
  10873. return llama_mlock::SUPPORTED;
  10874. }
  10875. bool llama_supports_gpu_offload(void) {
  10876. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  10877. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE)
  10878. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  10879. return true;
  10880. #else
  10881. return false;
  10882. #endif
  10883. }
  10884. void llama_backend_init(void) {
  10885. ggml_time_init();
  10886. // needed to initialize f16 tables
  10887. {
  10888. struct ggml_init_params params = { 0, NULL, false };
  10889. struct ggml_context * ctx = ggml_init(params);
  10890. ggml_free(ctx);
  10891. }
  10892. #ifdef GGML_USE_MPI
  10893. ggml_mpi_backend_init();
  10894. #endif
  10895. }
  10896. void llama_numa_init(enum ggml_numa_strategy numa) {
  10897. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  10898. ggml_numa_init(numa);
  10899. }
  10900. }
  10901. void llama_backend_free(void) {
  10902. #ifdef GGML_USE_MPI
  10903. ggml_mpi_backend_free();
  10904. #endif
  10905. ggml_quantize_free();
  10906. }
  10907. int64_t llama_time_us(void) {
  10908. return ggml_time_us();
  10909. }
  10910. struct llama_model * llama_load_model_from_file(
  10911. const char * path_model,
  10912. struct llama_model_params params) {
  10913. ggml_time_init();
  10914. llama_model * model = new llama_model;
  10915. unsigned cur_percentage = 0;
  10916. if (params.progress_callback == NULL) {
  10917. params.progress_callback_user_data = &cur_percentage;
  10918. params.progress_callback = [](float progress, void * ctx) {
  10919. unsigned * cur_percentage_p = (unsigned *) ctx;
  10920. unsigned percentage = (unsigned) (100 * progress);
  10921. while (percentage > *cur_percentage_p) {
  10922. *cur_percentage_p = percentage;
  10923. LLAMA_LOG_INFO(".");
  10924. if (percentage >= 100) {
  10925. LLAMA_LOG_INFO("\n");
  10926. }
  10927. }
  10928. return true;
  10929. };
  10930. }
  10931. int status = llama_model_load(path_model, *model, params);
  10932. GGML_ASSERT(status <= 0);
  10933. if (status < 0) {
  10934. if (status == -1) {
  10935. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  10936. } else if (status == -2) {
  10937. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  10938. }
  10939. delete model;
  10940. return nullptr;
  10941. }
  10942. return model;
  10943. }
  10944. void llama_free_model(struct llama_model * model) {
  10945. delete model;
  10946. }
  10947. struct llama_context * llama_new_context_with_model(
  10948. struct llama_model * model,
  10949. struct llama_context_params params) {
  10950. if (!model) {
  10951. LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
  10952. return nullptr;
  10953. }
  10954. if (params.n_batch == 0 && params.n_ubatch == 0) {
  10955. LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
  10956. return nullptr;
  10957. }
  10958. if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
  10959. LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
  10960. return nullptr;
  10961. }
  10962. llama_context * ctx = new llama_context(*model);
  10963. const auto & hparams = model->hparams;
  10964. auto & cparams = ctx->cparams;
  10965. // TODO: maybe add n_seq_max here too
  10966. cparams.n_threads = params.n_threads;
  10967. cparams.n_threads_batch = params.n_threads_batch;
  10968. cparams.yarn_ext_factor = params.yarn_ext_factor;
  10969. cparams.yarn_attn_factor = params.yarn_attn_factor;
  10970. cparams.yarn_beta_fast = params.yarn_beta_fast;
  10971. cparams.yarn_beta_slow = params.yarn_beta_slow;
  10972. cparams.defrag_thold = params.defrag_thold;
  10973. cparams.embeddings = params.embeddings;
  10974. cparams.offload_kqv = params.offload_kqv;
  10975. cparams.pooling_type = params.pooling_type;
  10976. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  10977. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  10978. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  10979. // this is necessary due to kv_self.n being padded later during inference
  10980. cparams.n_ctx = GGML_PAD(cparams.n_ctx, 32);
  10981. // with causal attention, the batch size is limited by the context size
  10982. cparams.n_batch = hparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
  10983. cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
  10984. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  10985. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  10986. hparams.n_ctx_train;
  10987. cparams.cb_eval = params.cb_eval;
  10988. cparams.cb_eval_user_data = params.cb_eval_user_data;
  10989. auto rope_scaling_type = params.rope_scaling_type;
  10990. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  10991. rope_scaling_type = hparams.rope_scaling_type_train;
  10992. }
  10993. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  10994. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  10995. }
  10996. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  10997. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  10998. }
  10999. cparams.causal_attn = hparams.causal_attn;
  11000. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  11001. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  11002. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  11003. } else {
  11004. cparams.pooling_type = hparams.pooling_type;
  11005. }
  11006. }
  11007. if (params.seed == LLAMA_DEFAULT_SEED) {
  11008. params.seed = time(NULL);
  11009. }
  11010. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  11011. LLAMA_LOG_INFO("%s: n_batch = %u\n", __func__, cparams.n_batch);
  11012. LLAMA_LOG_INFO("%s: n_ubatch = %u\n", __func__, cparams.n_ubatch);
  11013. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  11014. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  11015. ctx->abort_callback = params.abort_callback;
  11016. ctx->abort_callback_data = params.abort_callback_data;
  11017. ctx->rng = std::mt19937(params.seed);
  11018. ctx->logits_all = params.logits_all;
  11019. uint32_t kv_size = cparams.n_ctx;
  11020. ggml_type type_k = params.type_k;
  11021. ggml_type type_v = params.type_v;
  11022. // Mamba only needs a constant number of KV cache cells per sequence
  11023. if (model->arch == LLM_ARCH_MAMBA) {
  11024. // Mamba needs at least as many KV cells as there are sequences kept at any time
  11025. kv_size = std::max((uint32_t) 1, params.n_seq_max);
  11026. // it's probably best to keep as much precision as possible for the states
  11027. type_k = GGML_TYPE_F32; // required by ggml_ssm_conv for Mamba's conv_states
  11028. type_v = GGML_TYPE_F32; // required by ggml_ssm_scan for Mamba's ssm_states
  11029. }
  11030. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  11031. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  11032. if (!hparams.vocab_only) {
  11033. // initialize backends
  11034. #ifdef GGML_USE_METAL
  11035. if (model->n_gpu_layers > 0) {
  11036. ctx->backend_metal = ggml_backend_metal_init();
  11037. if (ctx->backend_metal == nullptr) {
  11038. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  11039. llama_free(ctx);
  11040. return nullptr;
  11041. }
  11042. ctx->backends.push_back(ctx->backend_metal);
  11043. }
  11044. #elif defined(GGML_USE_CUBLAS)
  11045. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  11046. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  11047. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  11048. if (backend == nullptr) {
  11049. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  11050. llama_free(ctx);
  11051. return nullptr;
  11052. }
  11053. ctx->backends.push_back(backend);
  11054. } else {
  11055. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  11056. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  11057. ggml_backend_t backend = ggml_backend_cuda_init(device);
  11058. if (backend == nullptr) {
  11059. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  11060. llama_free(ctx);
  11061. return nullptr;
  11062. }
  11063. ctx->backends.push_back(backend);
  11064. }
  11065. }
  11066. #elif defined(GGML_USE_VULKAN)
  11067. if (model->n_gpu_layers > 0) {
  11068. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  11069. ggml_backend_t backend = ggml_backend_vk_init(device);
  11070. if (backend == nullptr) {
  11071. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  11072. llama_free(ctx);
  11073. return nullptr;
  11074. }
  11075. ctx->backends.push_back(backend);
  11076. }
  11077. }
  11078. #elif defined(GGML_USE_SYCL)
  11079. if (model->n_gpu_layers > 0) {
  11080. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  11081. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  11082. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  11083. if (backend == nullptr) {
  11084. int main_gpu_id = ggml_backend_sycl_get_device_id(model->main_gpu);
  11085. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d) backend\n", __func__, main_gpu_id, model->main_gpu);
  11086. llama_free(ctx);
  11087. return nullptr;
  11088. }
  11089. ctx->backends.push_back(backend);
  11090. } else {
  11091. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  11092. for (int i = 0; i < ggml_backend_sycl_get_device_count(); ++i) {
  11093. ggml_backend_t backend = ggml_backend_sycl_init(i);
  11094. if (backend == nullptr) {
  11095. int id_list[GGML_SYCL_MAX_DEVICES];
  11096. ggml_sycl_get_gpu_list(id_list, GGML_SYCL_MAX_DEVICES);
  11097. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d) backend\n", __func__, id_list[i], i);
  11098. llama_free(ctx);
  11099. return nullptr;
  11100. }
  11101. ctx->backends.push_back(backend);
  11102. }
  11103. }
  11104. }
  11105. #elif defined(GGML_USE_KOMPUTE)
  11106. if (model->n_gpu_layers > 0) {
  11107. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  11108. if (backend == nullptr) {
  11109. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  11110. llama_free(ctx);
  11111. return nullptr;
  11112. }
  11113. ctx->backends.push_back(backend);
  11114. }
  11115. #endif
  11116. ctx->backend_cpu = ggml_backend_cpu_init();
  11117. if (ctx->backend_cpu == nullptr) {
  11118. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  11119. llama_free(ctx);
  11120. return nullptr;
  11121. }
  11122. ctx->backends.push_back(ctx->backend_cpu);
  11123. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v, kv_size, cparams.offload_kqv)) {
  11124. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  11125. llama_free(ctx);
  11126. return nullptr;
  11127. }
  11128. {
  11129. size_t memory_size_k = 0;
  11130. size_t memory_size_v = 0;
  11131. for (auto & k : ctx->kv_self.k_l) {
  11132. memory_size_k += ggml_nbytes(k);
  11133. }
  11134. for (auto & v : ctx->kv_self.v_l) {
  11135. memory_size_v += ggml_nbytes(v);
  11136. }
  11137. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  11138. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  11139. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  11140. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  11141. }
  11142. // graph outputs buffer
  11143. {
  11144. // resized during inference, reserve maximum
  11145. ctx->logits_size = hparams.n_vocab*cparams.n_batch;
  11146. ctx->embd_size = params.embeddings ? hparams.n_embd*cparams.n_batch : 0;
  11147. const size_t buf_output_size = (ctx->logits_size + ctx->embd_size)*sizeof(float);
  11148. ctx->buf_output = ggml_backend_buft_alloc_buffer(llama_default_buffer_type_cpu(true), buf_output_size);
  11149. if (ctx->buf_output == nullptr) {
  11150. LLAMA_LOG_ERROR("%s: failed to allocate logits buffer\n", __func__);
  11151. llama_free(ctx);
  11152. return nullptr;
  11153. }
  11154. ggml_backend_buffer_clear(ctx->buf_output, 0);
  11155. ctx->logits = (float *) ggml_backend_buffer_get_base(ctx->buf_output);
  11156. if (params.embeddings) {
  11157. ctx->embd = ctx->logits + ctx->logits_size;
  11158. }
  11159. LLAMA_LOG_INFO("%s: %10s output buffer size = %8.2f MiB\n", __func__,
  11160. ggml_backend_buffer_name(ctx->buf_output),
  11161. ggml_backend_buffer_get_size(ctx->buf_output) / 1024.0 / 1024.0);
  11162. }
  11163. // scheduler and compute buffers
  11164. {
  11165. // buffer types used for the compute buffer of each backend
  11166. std::vector<ggml_backend_buffer_type_t> backend_buft;
  11167. for (auto * backend : ctx->backends) {
  11168. if (ggml_backend_is_cpu(backend)) {
  11169. // use host buffers for the CPU backend compute buffer
  11170. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  11171. } else {
  11172. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  11173. }
  11174. }
  11175. // buffer used to store the computation graph and the tensor meta data
  11176. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead_custom(LLAMA_MAX_NODES, false));
  11177. // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
  11178. bool pipeline_parallel = llama_get_device_count() > 1 && model->n_gpu_layers > (int)model->hparams.n_layer && model->split_mode == LLAMA_SPLIT_MODE_LAYER;
  11179. #ifndef GGML_USE_CUBLAS
  11180. // pipeline parallelism requires support for async compute and events
  11181. // currently this is only implemented in the CUDA backend
  11182. pipeline_parallel = false;
  11183. #endif
  11184. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES, pipeline_parallel);
  11185. if (pipeline_parallel) {
  11186. LLAMA_LOG_INFO("%s: pipeline parallelism enabled (n_copies=%d)\n", __func__, ggml_backend_sched_get_n_copies(ctx->sched));
  11187. }
  11188. // build worst-case graph
  11189. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_ubatch);
  11190. int n_past = cparams.n_ctx - n_tokens;
  11191. 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
  11192. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  11193. // initialize scheduler with the worst-case graph
  11194. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  11195. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  11196. llama_free(ctx);
  11197. return nullptr;
  11198. }
  11199. for (size_t i = 0; i < ctx->backends.size(); i++) {
  11200. ggml_backend_t backend = ctx->backends[i];
  11201. ggml_backend_buffer_type_t buft = backend_buft[i];
  11202. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  11203. if (size > 1) {
  11204. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  11205. ggml_backend_buft_name(buft),
  11206. size / 1024.0 / 1024.0);
  11207. }
  11208. }
  11209. // note: the number of splits during measure is higher than during inference due to the kv shift
  11210. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  11211. LLAMA_LOG_INFO("%s: graph nodes = %d\n", __func__, gf->n_nodes);
  11212. LLAMA_LOG_INFO("%s: graph splits = %d\n", __func__, n_splits);
  11213. }
  11214. }
  11215. #ifdef GGML_USE_MPI
  11216. ctx->ctx_mpi = ggml_mpi_init();
  11217. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  11218. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  11219. // TODO: needs fix after #3228
  11220. GGML_ASSERT(false && "not implemented");
  11221. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  11222. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  11223. llama_backend_free();
  11224. exit(1);
  11225. }
  11226. #endif
  11227. return ctx;
  11228. }
  11229. void llama_free(struct llama_context * ctx) {
  11230. delete ctx;
  11231. }
  11232. const llama_model * llama_get_model(const struct llama_context * ctx) {
  11233. return &ctx->model;
  11234. }
  11235. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  11236. return ctx->cparams.n_ctx;
  11237. }
  11238. uint32_t llama_n_batch(const struct llama_context * ctx) {
  11239. return ctx->cparams.n_batch;
  11240. }
  11241. uint32_t llama_n_ubatch(const struct llama_context * ctx) {
  11242. return ctx->cparams.n_ubatch;
  11243. }
  11244. uint32_t llama_n_seq_max(const struct llama_context * ctx) {
  11245. return ctx->kv_self.size;
  11246. }
  11247. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  11248. return model->vocab.type;
  11249. }
  11250. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  11251. switch (model->arch) {
  11252. // these models do not use RoPE
  11253. case LLM_ARCH_GPT2:
  11254. case LLM_ARCH_GPTJ:
  11255. case LLM_ARCH_GPTNEOX:
  11256. case LLM_ARCH_MPT:
  11257. case LLM_ARCH_REFACT:
  11258. case LLM_ARCH_BLOOM:
  11259. case LLM_ARCH_MAMBA:
  11260. return LLAMA_ROPE_TYPE_NONE;
  11261. // use what we call a normal RoPE, operating on pairs of consecutive head values
  11262. case LLM_ARCH_LLAMA:
  11263. case LLM_ARCH_BAICHUAN:
  11264. case LLM_ARCH_STARCODER:
  11265. case LLM_ARCH_PLAMO:
  11266. case LLM_ARCH_CODESHELL:
  11267. case LLM_ARCH_ORION:
  11268. case LLM_ARCH_INTERNLM2:
  11269. case LLM_ARCH_MINICPM:
  11270. case LLM_ARCH_COMMAND_R:
  11271. return LLAMA_ROPE_TYPE_NORM;
  11272. // the pairs of head values are offset by n_rot/2
  11273. case LLM_ARCH_FALCON:
  11274. case LLM_ARCH_PERSIMMON:
  11275. case LLM_ARCH_BERT:
  11276. case LLM_ARCH_NOMIC_BERT:
  11277. case LLM_ARCH_STABLELM:
  11278. case LLM_ARCH_QWEN:
  11279. case LLM_ARCH_QWEN2:
  11280. case LLM_ARCH_PHI2:
  11281. case LLM_ARCH_GEMMA:
  11282. case LLM_ARCH_STARCODER2:
  11283. return LLAMA_ROPE_TYPE_NEOX;
  11284. // all model arches should be listed explicitly here
  11285. case LLM_ARCH_UNKNOWN:
  11286. GGML_ASSERT(false && "unknown architecture");
  11287. break;
  11288. }
  11289. return LLAMA_ROPE_TYPE_NONE;
  11290. }
  11291. int32_t llama_n_vocab(const struct llama_model * model) {
  11292. return model->hparams.n_vocab;
  11293. }
  11294. int32_t llama_n_ctx_train(const struct llama_model * model) {
  11295. return model->hparams.n_ctx_train;
  11296. }
  11297. int32_t llama_n_embd(const struct llama_model * model) {
  11298. return model->hparams.n_embd;
  11299. }
  11300. int32_t llama_n_layer(const struct llama_model * model) {
  11301. return model->hparams.n_layer;
  11302. }
  11303. float llama_rope_freq_scale_train(const struct llama_model * model) {
  11304. return model->hparams.rope_freq_scale_train;
  11305. }
  11306. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  11307. const auto & it = model->gguf_kv.find(key);
  11308. if (it == model->gguf_kv.end()) {
  11309. if (buf_size > 0) {
  11310. buf[0] = '\0';
  11311. }
  11312. return -1;
  11313. }
  11314. return snprintf(buf, buf_size, "%s", it->second.c_str());
  11315. }
  11316. int32_t llama_model_meta_count(const struct llama_model * model) {
  11317. return (int)model->gguf_kv.size();
  11318. }
  11319. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  11320. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  11321. if (buf_size > 0) {
  11322. buf[0] = '\0';
  11323. }
  11324. return -1;
  11325. }
  11326. auto it = model->gguf_kv.begin();
  11327. std::advance(it, i);
  11328. return snprintf(buf, buf_size, "%s", it->first.c_str());
  11329. }
  11330. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  11331. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  11332. if (buf_size > 0) {
  11333. buf[0] = '\0';
  11334. }
  11335. return -1;
  11336. }
  11337. auto it = model->gguf_kv.begin();
  11338. std::advance(it, i);
  11339. return snprintf(buf, buf_size, "%s", it->second.c_str());
  11340. }
  11341. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  11342. return snprintf(buf, buf_size, "%s %s %s",
  11343. llama_model_arch_name(model->arch),
  11344. llama_model_type_name(model->type),
  11345. llama_model_ftype_name(model->ftype).c_str());
  11346. }
  11347. uint64_t llama_model_size(const struct llama_model * model) {
  11348. uint64_t size = 0;
  11349. for (const auto & it : model->tensors_by_name) {
  11350. size += ggml_nbytes(it.second);
  11351. }
  11352. return size;
  11353. }
  11354. uint64_t llama_model_n_params(const struct llama_model * model) {
  11355. uint64_t nparams = 0;
  11356. for (const auto & it : model->tensors_by_name) {
  11357. nparams += ggml_nelements(it.second);
  11358. }
  11359. return nparams;
  11360. }
  11361. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  11362. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  11363. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  11364. return it.first == name;
  11365. });
  11366. if (it == model->tensors_by_name.end()) {
  11367. return nullptr;
  11368. }
  11369. return it->second;
  11370. }
  11371. uint32_t llama_model_quantize(
  11372. const char * fname_inp,
  11373. const char * fname_out,
  11374. const llama_model_quantize_params * params) {
  11375. try {
  11376. llama_model_quantize_internal(fname_inp, fname_out, params);
  11377. return 0;
  11378. } catch (const std::exception & err) {
  11379. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  11380. return 1;
  11381. }
  11382. }
  11383. int32_t llama_model_apply_lora_from_file(const struct llama_model * model, const char * path_lora, float scale, const char * path_base_model, int32_t n_threads) {
  11384. try {
  11385. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  11386. } catch (const std::exception & err) {
  11387. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  11388. return 1;
  11389. }
  11390. }
  11391. static bool llama_control_vector_init(struct llama_control_vector & cvec, const llama_model & model) {
  11392. GGML_ASSERT(cvec.tensors.empty());
  11393. GGML_ASSERT(cvec.ctxs.empty());
  11394. GGML_ASSERT(cvec.bufs.empty());
  11395. // count layer buffer types
  11396. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  11397. for (int64_t i = 0; i < model.hparams.n_layer; i++) {
  11398. buft_layer_count[model.buft_layer[i].buft]++;
  11399. }
  11400. // allocate contexts
  11401. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  11402. for (auto & it : buft_layer_count) {
  11403. int n_layers = it.second;
  11404. struct ggml_init_params params = {
  11405. /*.mem_size =*/ n_layers * ggml_tensor_overhead(),
  11406. /*.mem_buffer =*/ NULL,
  11407. /*.no_alloc =*/ true,
  11408. };
  11409. ggml_context * ctx = ggml_init(params);
  11410. if (!ctx) {
  11411. LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
  11412. return 1;
  11413. }
  11414. ctx_map[it.first] = ctx;
  11415. }
  11416. // make tensors
  11417. cvec.tensors.push_back(nullptr); // there's never a tensor for layer 0
  11418. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  11419. struct ggml_context * ctx = ctx_map.at(model.buft_layer[il].buft);
  11420. ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_embd);
  11421. cvec.tensors.push_back(tensor);
  11422. }
  11423. // allocate tensors / buffers and zero
  11424. for (auto it : ctx_map) {
  11425. ggml_backend_buffer_type_t buft = it.first;
  11426. ggml_context * ctx = it.second;
  11427. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  11428. if (!buf) {
  11429. LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
  11430. return false;
  11431. }
  11432. ggml_backend_buffer_clear(buf, 0);
  11433. cvec.ctxs.push_back(ctx);
  11434. cvec.bufs.push_back(buf);
  11435. }
  11436. return true;
  11437. }
  11438. int32_t llama_control_vector_apply(struct llama_context * lctx, const float * data, size_t len, int32_t n_embd, int32_t il_start, int32_t il_end) {
  11439. const llama_model & model = lctx->model;
  11440. llama_control_vector & cvec = lctx->cvec;
  11441. if (data == nullptr) {
  11442. // disable the current control vector (but leave allocated for later)
  11443. cvec.layer_start = -1;
  11444. cvec.layer_end = -1;
  11445. return 0;
  11446. }
  11447. if (n_embd != (int) model.hparams.n_embd) {
  11448. LLAMA_LOG_ERROR("%s: control vector n_embd does not match model\n", __func__);
  11449. return 1;
  11450. }
  11451. if (cvec.tensors.empty()) {
  11452. if (!llama_control_vector_init(cvec, model)) {
  11453. return 1;
  11454. }
  11455. }
  11456. cvec.layer_start = il_start;
  11457. cvec.layer_end = il_end;
  11458. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  11459. assert(cvec.tensors[il] != nullptr);
  11460. const size_t off = n_embd * (il - 1); // buffer doesn't have data for layer 0, since it's never present
  11461. if (off + n_embd <= len) {
  11462. ggml_backend_tensor_set(cvec.tensors[il], data + off, 0, n_embd * ggml_element_size(cvec.tensors[il]));
  11463. }
  11464. }
  11465. return 0;
  11466. }
  11467. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_seq_max) {
  11468. struct llama_kv_cache_view result = {
  11469. /*.n_cells = */ 0,
  11470. /*.n_seq_max = */ n_seq_max,
  11471. /*.token_count = */ 0,
  11472. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  11473. /*.max_contiguous = */ 0,
  11474. /*.max_contiguous_idx = */ -1,
  11475. /*.cells = */ nullptr,
  11476. /*.cells_sequences = */ nullptr,
  11477. };
  11478. return result;
  11479. }
  11480. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  11481. if (view->cells != nullptr) {
  11482. free(view->cells);
  11483. view->cells = nullptr;
  11484. }
  11485. if (view->cells_sequences != nullptr) {
  11486. free(view->cells_sequences);
  11487. view->cells_sequences = nullptr;
  11488. }
  11489. }
  11490. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  11491. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  11492. view->n_cells = int32_t(ctx->kv_self.size);
  11493. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  11494. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  11495. view->cells = (struct llama_kv_cache_view_cell *)p;
  11496. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_seq_max * view->n_cells);
  11497. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  11498. view->cells_sequences = (llama_seq_id *)p;
  11499. }
  11500. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  11501. llama_kv_cache_view_cell * c_curr = view->cells;
  11502. llama_seq_id * cs_curr = view->cells_sequences;
  11503. int32_t used_cells = 0;
  11504. int32_t token_count = 0;
  11505. int32_t curr_contig_idx = -1;
  11506. uint32_t max_contig = 0;
  11507. int32_t max_contig_idx = -1;
  11508. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_seq_max) {
  11509. const size_t curr_size = kv_cells[i].seq_id.size();
  11510. token_count += curr_size;
  11511. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  11512. if (curr_size > 0) {
  11513. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  11514. max_contig = i - curr_contig_idx;
  11515. max_contig_idx = curr_contig_idx;
  11516. }
  11517. curr_contig_idx = -1;
  11518. } else if (curr_contig_idx < 0) {
  11519. curr_contig_idx = i;
  11520. }
  11521. int seq_idx = 0;
  11522. for (const llama_seq_id it : kv_cells[i].seq_id) {
  11523. if (seq_idx >= view->n_seq_max) {
  11524. break;
  11525. }
  11526. cs_curr[seq_idx] = it;
  11527. seq_idx++;
  11528. }
  11529. if (seq_idx != 0) {
  11530. used_cells++;
  11531. }
  11532. for (; seq_idx < view->n_seq_max; seq_idx++) {
  11533. cs_curr[seq_idx] = -1;
  11534. }
  11535. }
  11536. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  11537. max_contig_idx = curr_contig_idx;
  11538. max_contig = kv_cells.size() - curr_contig_idx;
  11539. }
  11540. view->max_contiguous = max_contig;
  11541. view->max_contiguous_idx = max_contig_idx;
  11542. view->token_count = token_count;
  11543. view->used_cells = used_cells;
  11544. if (uint32_t(used_cells) != ctx->kv_self.used) {
  11545. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  11546. __func__, ctx->kv_self.used, used_cells);
  11547. }
  11548. }
  11549. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  11550. int result = 0;
  11551. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  11552. result += ctx->kv_self.cells[i].seq_id.size();
  11553. }
  11554. return result;
  11555. }
  11556. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  11557. return ctx->kv_self.used;
  11558. }
  11559. void llama_kv_cache_clear(struct llama_context * ctx) {
  11560. llama_kv_cache_clear(ctx->kv_self);
  11561. }
  11562. bool llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  11563. return llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  11564. }
  11565. 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) {
  11566. if (seq_id_src == seq_id_dst) {
  11567. return;
  11568. }
  11569. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  11570. }
  11571. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  11572. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  11573. }
  11574. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  11575. if (delta == 0) {
  11576. return;
  11577. }
  11578. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  11579. }
  11580. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  11581. if (d == 1) {
  11582. return;
  11583. }
  11584. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  11585. }
  11586. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  11587. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  11588. }
  11589. void llama_kv_cache_defrag(struct llama_context * ctx) {
  11590. llama_kv_cache_defrag(ctx->kv_self);
  11591. }
  11592. void llama_kv_cache_update(struct llama_context * ctx) {
  11593. llama_kv_cache_update_internal(*ctx);
  11594. }
  11595. // Returns the *maximum* size of the state
  11596. size_t llama_get_state_size(const struct llama_context * ctx) {
  11597. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  11598. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  11599. const size_t s_rng_size = sizeof(size_t);
  11600. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  11601. const size_t s_logits_size = sizeof(size_t);
  11602. // assume worst case for logits although only currently set ones are serialized
  11603. const size_t s_logits = ctx->logits_size * sizeof(float);
  11604. const size_t s_embedding_size = sizeof(size_t);
  11605. const size_t s_embedding = ctx->embd_size * sizeof(float);
  11606. const size_t s_kv_buf_size = sizeof(size_t);
  11607. const size_t s_kv_head = sizeof(uint32_t);
  11608. const size_t s_kv_size = sizeof(uint32_t);
  11609. const size_t s_kv_used = sizeof(uint32_t);
  11610. const size_t s_kv = ctx->kv_self.total_size();
  11611. // TODO: assume the max is more than 1 seq_id per KV cell
  11612. const size_t s_kv_cell = sizeof(llama_pos) + sizeof(size_t) + sizeof(llama_seq_id);
  11613. const size_t s_kv_cells = ctx->kv_self.size * s_kv_cell;
  11614. const size_t s_total = (
  11615. + s_rng_size
  11616. + s_rng
  11617. + s_logits_size
  11618. + s_logits
  11619. + s_embedding_size
  11620. + s_embedding
  11621. + s_kv_buf_size
  11622. + s_kv_head
  11623. + s_kv_size
  11624. + s_kv_used
  11625. + s_kv
  11626. + s_kv_cells
  11627. );
  11628. return s_total;
  11629. }
  11630. // llama_context_data
  11631. struct llama_data_context {
  11632. virtual void write(const void * src, size_t size) = 0;
  11633. virtual size_t get_size_written() = 0;
  11634. virtual ~llama_data_context() = default;
  11635. };
  11636. struct llama_data_buffer_context : llama_data_context {
  11637. uint8_t * ptr;
  11638. size_t size_written = 0;
  11639. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  11640. void write(const void * src, size_t size) override {
  11641. memcpy(ptr, src, size);
  11642. ptr += size;
  11643. size_written += size;
  11644. }
  11645. size_t get_size_written() override {
  11646. return size_written;
  11647. }
  11648. };
  11649. struct llama_data_file_context : llama_data_context {
  11650. llama_file * file;
  11651. size_t size_written = 0;
  11652. llama_data_file_context(llama_file * f) : file(f) {}
  11653. void write(const void * src, size_t size) override {
  11654. file->write_raw(src, size);
  11655. size_written += size;
  11656. }
  11657. size_t get_size_written() override {
  11658. return size_written;
  11659. }
  11660. };
  11661. /** copy state data into either a buffer or file depending on the passed in context
  11662. *
  11663. * file context:
  11664. * llama_file file("/path", "wb");
  11665. * llama_data_file_context data_ctx(&file);
  11666. * llama_copy_state_data(ctx, &data_ctx);
  11667. *
  11668. * buffer context:
  11669. * std::vector<uint8_t> buf(max_size, 0);
  11670. * llama_data_buffer_context data_ctx(&buf.data());
  11671. * llama_copy_state_data(ctx, &data_ctx);
  11672. *
  11673. */
  11674. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  11675. // copy rng
  11676. {
  11677. std::ostringstream rng_ss;
  11678. rng_ss << ctx->rng;
  11679. const std::string & rng_str = rng_ss.str();
  11680. const size_t rng_size = rng_str.size();
  11681. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  11682. data_ctx->write(&rng_size, sizeof(rng_size));
  11683. data_ctx->write(rng_str.data(), rng_size);
  11684. }
  11685. // copy logits
  11686. {
  11687. const size_t logits_size = ctx->logits_size;
  11688. data_ctx->write(&logits_size, sizeof(logits_size));
  11689. if (logits_size) {
  11690. data_ctx->write(ctx->logits, logits_size * sizeof(float));
  11691. }
  11692. }
  11693. // copy embeddings
  11694. {
  11695. const size_t embeddings_size = ctx->embd_size;
  11696. data_ctx->write(&embeddings_size, sizeof(embeddings_size));
  11697. if (embeddings_size) {
  11698. data_ctx->write(ctx->embd, embeddings_size * sizeof(float));
  11699. }
  11700. }
  11701. // copy kv cache
  11702. {
  11703. const auto & kv_self = ctx->kv_self;
  11704. const auto & hparams = ctx->model.hparams;
  11705. const uint32_t n_layer = hparams.n_layer;
  11706. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  11707. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  11708. const size_t kv_buf_size = kv_self.total_size();
  11709. const uint32_t kv_head = llama_kv_cache_cell_max(kv_self);
  11710. const uint32_t kv_size = kv_self.size;
  11711. const uint32_t kv_used = kv_self.used;
  11712. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  11713. data_ctx->write(&kv_head, sizeof(kv_head));
  11714. data_ctx->write(&kv_size, sizeof(kv_size));
  11715. data_ctx->write(&kv_used, sizeof(kv_used));
  11716. if (kv_buf_size) {
  11717. std::vector<uint8_t> tmp_buf;
  11718. for (int il = 0; il < (int) n_layer; ++il) {
  11719. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  11720. tmp_buf.resize(k_size);
  11721. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  11722. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  11723. if (kv_self.recurrent) {
  11724. // v is contiguous for recurrent models
  11725. // TODO: use other tensors for state models than k and v
  11726. const size_t v_size = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*kv_head);
  11727. tmp_buf.resize(v_size);
  11728. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), 0, tmp_buf.size());
  11729. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  11730. continue;
  11731. }
  11732. // v is not contiguous, copy row by row
  11733. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  11734. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_size);
  11735. tmp_buf.resize(v_row_size);
  11736. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  11737. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*v_row_stride, tmp_buf.size());
  11738. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  11739. }
  11740. }
  11741. }
  11742. for (uint32_t i = 0; i < kv_head; ++i) {
  11743. const auto & cell = kv_self.cells[i];
  11744. const llama_pos pos = cell.pos;
  11745. const size_t seq_id_size = cell.seq_id.size();
  11746. data_ctx->write(&pos, sizeof(pos));
  11747. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  11748. for (auto seq_id : cell.seq_id) {
  11749. data_ctx->write(&seq_id, sizeof(seq_id));
  11750. }
  11751. }
  11752. }
  11753. }
  11754. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  11755. llama_data_buffer_context data_ctx(dst);
  11756. llama_copy_state_data_internal(ctx, &data_ctx);
  11757. return data_ctx.get_size_written();
  11758. }
  11759. // Sets the state reading from the specified source address
  11760. size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
  11761. const uint8_t * inp = src;
  11762. // set rng
  11763. {
  11764. size_t rng_size;
  11765. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  11766. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  11767. std::string rng_str((const char *)inp, rng_size); inp += rng_size;
  11768. std::istringstream rng_ss(rng_str);
  11769. rng_ss >> ctx->rng;
  11770. GGML_ASSERT(!rng_ss.fail());
  11771. }
  11772. // set logits
  11773. {
  11774. size_t logits_size;
  11775. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  11776. GGML_ASSERT(ctx->logits_size >= logits_size);
  11777. if (logits_size) {
  11778. memcpy(ctx->logits, inp, logits_size * sizeof(float));
  11779. inp += logits_size * sizeof(float);
  11780. }
  11781. }
  11782. // set embeddings
  11783. {
  11784. size_t embeddings_size;
  11785. memcpy(&embeddings_size, inp, sizeof(embeddings_size)); inp += sizeof(embeddings_size);
  11786. GGML_ASSERT(ctx->embd_size == embeddings_size);
  11787. if (embeddings_size) {
  11788. memcpy(ctx->embd, inp, embeddings_size * sizeof(float));
  11789. inp += embeddings_size * sizeof(float);
  11790. }
  11791. }
  11792. // set kv cache
  11793. {
  11794. const auto & kv_self = ctx->kv_self;
  11795. const auto & hparams = ctx->model.hparams;
  11796. const uint32_t n_layer = hparams.n_layer;
  11797. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  11798. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  11799. size_t kv_buf_size;
  11800. uint32_t kv_head;
  11801. uint32_t kv_size;
  11802. uint32_t kv_used;
  11803. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  11804. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  11805. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  11806. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  11807. if (kv_buf_size) {
  11808. GGML_ASSERT(kv_self.total_size() == kv_buf_size);
  11809. for (int il = 0; il < (int) n_layer; ++il) {
  11810. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  11811. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  11812. inp += k_size;
  11813. if (kv_self.recurrent) {
  11814. // v is contiguous for recurrent models
  11815. // TODO: use other tensors for state models than k and v
  11816. const size_t v_size = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*kv_head);
  11817. ggml_backend_tensor_set(kv_self.v_l[il], inp, 0, v_size);
  11818. inp += v_size;
  11819. continue;
  11820. }
  11821. // v is not contiguous, copy row by row
  11822. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  11823. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_size);
  11824. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  11825. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*v_row_stride, v_row_size);
  11826. inp += v_row_size;
  11827. }
  11828. }
  11829. }
  11830. GGML_ASSERT(kv_self.size == kv_size);
  11831. ctx->kv_self.head = kv_head;
  11832. ctx->kv_self.size = kv_size;
  11833. ctx->kv_self.used = kv_used;
  11834. ctx->kv_self.cells.resize(kv_size);
  11835. for (uint32_t i = 0; i < kv_head; ++i) {
  11836. llama_pos pos;
  11837. size_t seq_id_size;
  11838. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  11839. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  11840. ctx->kv_self.cells[i].pos = pos;
  11841. llama_seq_id seq_id;
  11842. for (size_t j = 0; j < seq_id_size; ++j) {
  11843. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  11844. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  11845. }
  11846. }
  11847. for (uint32_t i = kv_head; i < kv_size; ++i) {
  11848. ctx->kv_self.cells[i].pos = -1;
  11849. ctx->kv_self.cells[i].seq_id.clear();
  11850. }
  11851. }
  11852. const size_t nread = inp - src;
  11853. const size_t max_size = llama_get_state_size(ctx);
  11854. GGML_ASSERT(nread <= max_size);
  11855. return nread;
  11856. }
  11857. 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) {
  11858. llama_file file(path_session, "rb");
  11859. // sanity checks
  11860. {
  11861. const uint32_t magic = file.read_u32();
  11862. const uint32_t version = file.read_u32();
  11863. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  11864. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  11865. return false;
  11866. }
  11867. llama_hparams session_hparams;
  11868. file.read_raw(&session_hparams, sizeof(llama_hparams));
  11869. if (session_hparams != ctx->model.hparams) {
  11870. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  11871. return false;
  11872. }
  11873. }
  11874. // load the prompt
  11875. {
  11876. const uint32_t n_token_count = file.read_u32();
  11877. if (n_token_count > n_token_capacity) {
  11878. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  11879. return false;
  11880. }
  11881. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  11882. *n_token_count_out = n_token_count;
  11883. }
  11884. // restore the context state
  11885. {
  11886. const size_t n_state_size_cur = file.size - file.tell();
  11887. const size_t n_state_size_max = llama_get_state_size(ctx);
  11888. if (n_state_size_cur > n_state_size_max) {
  11889. 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);
  11890. return false;
  11891. }
  11892. std::vector<uint8_t> state_data(n_state_size_max);
  11893. file.read_raw(state_data.data(), n_state_size_cur);
  11894. llama_set_state_data(ctx, state_data.data());
  11895. }
  11896. return true;
  11897. }
  11898. 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) {
  11899. try {
  11900. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  11901. } catch (const std::exception & err) {
  11902. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  11903. return false;
  11904. }
  11905. }
  11906. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  11907. llama_file file(path_session, "wb");
  11908. file.write_u32(LLAMA_SESSION_MAGIC);
  11909. file.write_u32(LLAMA_SESSION_VERSION);
  11910. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  11911. // save the prompt
  11912. file.write_u32((uint32_t) n_token_count);
  11913. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  11914. // save the context state using stream saving
  11915. llama_data_file_context data_ctx(&file);
  11916. llama_copy_state_data_internal(ctx, &data_ctx);
  11917. return true;
  11918. }
  11919. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  11920. ctx->cparams.n_threads = n_threads;
  11921. ctx->cparams.n_threads_batch = n_threads_batch;
  11922. }
  11923. void llama_set_abort_callback(struct llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
  11924. ctx->abort_callback = abort_callback;
  11925. ctx->abort_callback_data = abort_callback_data;
  11926. }
  11927. void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn) {
  11928. ctx->cparams.causal_attn = causal_attn;
  11929. }
  11930. struct llama_batch llama_batch_get_one(
  11931. llama_token * tokens,
  11932. int32_t n_tokens,
  11933. llama_pos pos_0,
  11934. llama_seq_id seq_id) {
  11935. return {
  11936. /*n_tokens =*/ n_tokens,
  11937. /*tokens =*/ tokens,
  11938. /*embd =*/ nullptr,
  11939. /*pos =*/ nullptr,
  11940. /*n_seq_id =*/ nullptr,
  11941. /*seq_id =*/ nullptr,
  11942. /*logits =*/ nullptr,
  11943. /*all_pos_0 =*/ pos_0,
  11944. /*all_pos_1 =*/ 1,
  11945. /*all_seq_id =*/ seq_id,
  11946. };
  11947. }
  11948. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  11949. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  11950. if (embd) {
  11951. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  11952. } else {
  11953. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  11954. }
  11955. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  11956. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  11957. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  11958. for (int i = 0; i < n_tokens_alloc; ++i) {
  11959. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  11960. }
  11961. batch.seq_id[n_tokens_alloc] = nullptr;
  11962. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  11963. return batch;
  11964. }
  11965. void llama_batch_free(struct llama_batch batch) {
  11966. if (batch.token) free(batch.token);
  11967. if (batch.embd) free(batch.embd);
  11968. if (batch.pos) free(batch.pos);
  11969. if (batch.n_seq_id) free(batch.n_seq_id);
  11970. if (batch.seq_id) {
  11971. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  11972. free(batch.seq_id[i]);
  11973. }
  11974. free(batch.seq_id);
  11975. }
  11976. if (batch.logits) free(batch.logits);
  11977. }
  11978. int32_t llama_decode(
  11979. struct llama_context * ctx,
  11980. struct llama_batch batch) {
  11981. const int ret = llama_decode_internal(*ctx, batch);
  11982. if (ret < 0) {
  11983. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  11984. }
  11985. return ret;
  11986. }
  11987. void llama_synchronize(struct llama_context * ctx) {
  11988. ggml_backend_sched_synchronize(ctx->sched);
  11989. // FIXME: if multiple single tokens are evaluated without a synchronization,
  11990. // the stats will be added to the prompt evaluation stats
  11991. // this should only happen when using batch size 1 to evaluate a batch
  11992. // add the evaluation to the stats
  11993. if (ctx->n_queued_tokens == 1) {
  11994. ctx->t_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  11995. ctx->n_eval++;
  11996. } else if (ctx->n_queued_tokens > 1) {
  11997. ctx->t_p_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  11998. ctx->n_p_eval += ctx->n_queued_tokens;
  11999. }
  12000. // get a more accurate load time, upon first eval
  12001. if (ctx->n_queued_tokens > 0 && !ctx->has_evaluated_once) {
  12002. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  12003. ctx->has_evaluated_once = true;
  12004. }
  12005. ctx->n_queued_tokens = 0;
  12006. ctx->t_compute_start_us = 0;
  12007. }
  12008. float * llama_get_logits(struct llama_context * ctx) {
  12009. llama_synchronize(ctx);
  12010. return ctx->logits;
  12011. }
  12012. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  12013. assert(ctx->logits_valid.at(i));
  12014. llama_synchronize(ctx);
  12015. return ctx->logits + i*ctx->model.hparams.n_vocab;
  12016. }
  12017. float * llama_get_embeddings(struct llama_context * ctx) {
  12018. llama_synchronize(ctx);
  12019. return ctx->embd;
  12020. }
  12021. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  12022. llama_synchronize(ctx);
  12023. return ctx->embd + i*ctx->model.hparams.n_embd;
  12024. }
  12025. float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id) {
  12026. llama_synchronize(ctx);
  12027. auto it = ctx->embd_seq.find(seq_id);
  12028. if (it == ctx->embd_seq.end()) {
  12029. return nullptr;
  12030. }
  12031. return it->second.data();
  12032. }
  12033. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  12034. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  12035. return model->vocab.id_to_token[token].text.c_str();
  12036. }
  12037. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  12038. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  12039. return model->vocab.id_to_token[token].score;
  12040. }
  12041. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  12042. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  12043. return model->vocab.id_to_token[token].type;
  12044. }
  12045. llama_token llama_token_bos(const struct llama_model * model) {
  12046. return model->vocab.special_bos_id;
  12047. }
  12048. llama_token llama_token_eos(const struct llama_model * model) {
  12049. return model->vocab.special_eos_id;
  12050. }
  12051. llama_token llama_token_nl(const struct llama_model * model) {
  12052. return model->vocab.linefeed_id;
  12053. }
  12054. int32_t llama_add_bos_token(const struct llama_model * model) {
  12055. return model->vocab.special_add_bos;
  12056. }
  12057. int32_t llama_add_eos_token(const struct llama_model * model) {
  12058. return model->vocab.special_add_eos;
  12059. }
  12060. llama_token llama_token_prefix(const struct llama_model * model) {
  12061. return model->vocab.special_prefix_id;
  12062. }
  12063. llama_token llama_token_middle(const struct llama_model * model) {
  12064. return model->vocab.special_middle_id;
  12065. }
  12066. llama_token llama_token_suffix(const struct llama_model * model) {
  12067. return model->vocab.special_suffix_id;
  12068. }
  12069. llama_token llama_token_eot(const struct llama_model * model) {
  12070. return model->vocab.special_eot_id;
  12071. }
  12072. int32_t llama_tokenize(
  12073. const struct llama_model * model,
  12074. const char * text,
  12075. int32_t text_len,
  12076. llama_token * tokens,
  12077. int32_t n_tokens_max,
  12078. bool add_bos,
  12079. bool special) {
  12080. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  12081. if (n_tokens_max < (int) res.size()) {
  12082. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  12083. return -((int) res.size());
  12084. }
  12085. for (size_t i = 0; i < res.size(); i++) {
  12086. tokens[i] = res[i];
  12087. }
  12088. return res.size();
  12089. }
  12090. static std::string llama_decode_text(const std::string & text) {
  12091. std::string decoded_text;
  12092. auto unicode_sequences = unicode_cpts_from_utf8(text);
  12093. for (auto & unicode_sequence : unicode_sequences) {
  12094. decoded_text += unicode_utf8_to_byte(unicode_cpt_to_utf8(unicode_sequence));
  12095. }
  12096. return decoded_text;
  12097. }
  12098. // does not write null-terminator to buf
  12099. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  12100. if (0 <= token && token < llama_n_vocab(model)) {
  12101. switch (llama_vocab_get_type(model->vocab)) {
  12102. case LLAMA_VOCAB_TYPE_WPM:
  12103. case LLAMA_VOCAB_TYPE_SPM: {
  12104. // NOTE: we accept all unsupported token types,
  12105. // suppressing them like CONTROL tokens.
  12106. if (llama_is_normal_token(model->vocab, token)) {
  12107. std::string result = model->vocab.id_to_token[token].text;
  12108. llama_unescape_whitespace(result);
  12109. if (length < (int) result.length()) {
  12110. return -(int) result.length();
  12111. }
  12112. memcpy(buf, result.c_str(), result.length());
  12113. return result.length();
  12114. } else if (llama_is_user_defined_token(model->vocab, token)) {
  12115. std::string result = model->vocab.id_to_token[token].text;
  12116. if (length < (int) result.length()) {
  12117. return -(int) result.length();
  12118. }
  12119. memcpy(buf, result.c_str(), result.length());
  12120. return result.length();
  12121. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  12122. if (length < 3) {
  12123. return -3;
  12124. }
  12125. memcpy(buf, "\xe2\x96\x85", 3);
  12126. return 3;
  12127. } else if (llama_is_control_token(model->vocab, token)) {
  12128. ;
  12129. } else if (llama_is_byte_token(model->vocab, token)) {
  12130. if (length < 1) {
  12131. return -1;
  12132. }
  12133. buf[0] = llama_token_to_byte(model->vocab, token);
  12134. return 1;
  12135. }
  12136. break;
  12137. }
  12138. case LLAMA_VOCAB_TYPE_BPE: {
  12139. // NOTE: we accept all unsupported token types,
  12140. // suppressing them like CONTROL tokens.
  12141. if (llama_is_normal_token(model->vocab, token)) {
  12142. std::string result = model->vocab.id_to_token[token].text;
  12143. result = llama_decode_text(result);
  12144. if (length < (int) result.length()) {
  12145. return -(int) result.length();
  12146. }
  12147. memcpy(buf, result.c_str(), result.length());
  12148. return result.length();
  12149. } else if (llama_is_user_defined_token(model->vocab, token)) {
  12150. std::string result = model->vocab.id_to_token[token].text;
  12151. if (length < (int) result.length()) {
  12152. return -(int) result.length();
  12153. }
  12154. memcpy(buf, result.c_str(), result.length());
  12155. return result.length();
  12156. } else if (llama_is_control_token(model->vocab, token)) {
  12157. ;
  12158. }
  12159. break;
  12160. }
  12161. default:
  12162. GGML_ASSERT(false);
  12163. }
  12164. }
  12165. return 0;
  12166. }
  12167. // trim whitespace from the beginning and end of a string
  12168. static std::string trim(const std::string & str) {
  12169. size_t start = 0;
  12170. size_t end = str.size();
  12171. while (start < end && isspace(str[start])) {
  12172. start += 1;
  12173. }
  12174. while (end > start && isspace(str[end - 1])) {
  12175. end -= 1;
  12176. }
  12177. return str.substr(start, end - start);
  12178. }
  12179. // Simple version of "llama_apply_chat_template" that only works with strings
  12180. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  12181. static int32_t llama_chat_apply_template_internal(
  12182. const std::string & tmpl,
  12183. const std::vector<const llama_chat_message *> & chat,
  12184. std::string & dest, bool add_ass) {
  12185. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  12186. std::stringstream ss;
  12187. if (tmpl == "chatml" || tmpl.find("<|im_start|>") != std::string::npos) {
  12188. // chatml template
  12189. for (auto message : chat) {
  12190. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  12191. }
  12192. if (add_ass) {
  12193. ss << "<|im_start|>assistant\n";
  12194. }
  12195. } else if (tmpl == "llama2" || tmpl.find("[INST]") != std::string::npos) {
  12196. // llama2 template and its variants
  12197. // [variant] support system message
  12198. bool support_system_message = tmpl.find("<<SYS>>") != std::string::npos;
  12199. // [variant] space before + after response
  12200. bool space_around_response = tmpl.find("' ' + eos_token") != std::string::npos;
  12201. // [variant] add BOS inside history
  12202. bool add_bos_inside_history = tmpl.find("bos_token + '[INST]") != std::string::npos;
  12203. // [variant] trim spaces from the input message
  12204. bool strip_message = tmpl.find("content.strip()") != std::string::npos;
  12205. // construct the prompt
  12206. bool is_inside_turn = true; // skip BOS at the beginning
  12207. ss << "[INST] ";
  12208. for (auto message : chat) {
  12209. std::string content = strip_message ? trim(message->content) : message->content;
  12210. std::string role(message->role);
  12211. if (!is_inside_turn) {
  12212. is_inside_turn = true;
  12213. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  12214. }
  12215. if (role == "system") {
  12216. if (support_system_message) {
  12217. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  12218. } else {
  12219. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  12220. ss << content << "\n";
  12221. }
  12222. } else if (role == "user") {
  12223. ss << content << " [/INST]";
  12224. } else {
  12225. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  12226. is_inside_turn = false;
  12227. }
  12228. }
  12229. // llama2 templates seem to not care about "add_generation_prompt"
  12230. } else if (tmpl == "zephyr" || tmpl.find("<|user|>") != std::string::npos) {
  12231. // zephyr template
  12232. for (auto message : chat) {
  12233. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  12234. }
  12235. if (add_ass) {
  12236. ss << "<|assistant|>\n";
  12237. }
  12238. } else if (tmpl == "monarch" || tmpl.find("bos_token + message['role']") != std::string::npos) {
  12239. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  12240. for (auto message : chat) {
  12241. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  12242. ss << bos << message->role << "\n" << message->content << "</s>\n";
  12243. }
  12244. if (add_ass) {
  12245. ss << "<s>assistant\n";
  12246. }
  12247. } else if (tmpl == "gemma" || tmpl.find("<start_of_turn>") != std::string::npos) {
  12248. // google/gemma-7b-it
  12249. std::string system_prompt = "";
  12250. for (auto message : chat) {
  12251. std::string role(message->role);
  12252. if (role == "system") {
  12253. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  12254. system_prompt = trim(message->content);
  12255. continue;
  12256. }
  12257. // in gemma, "assistant" is "model"
  12258. role = role == "assistant" ? "model" : message->role;
  12259. ss << "<start_of_turn>" << role << "\n";
  12260. if (!system_prompt.empty() && role != "model") {
  12261. ss << system_prompt << "\n\n";
  12262. system_prompt = "";
  12263. }
  12264. ss << trim(message->content) << "<end_of_turn>\n";
  12265. }
  12266. if (add_ass) {
  12267. ss << "<start_of_turn>model\n";
  12268. }
  12269. } else if (tmpl == "orion" || tmpl.find("'\\n\\nAssistant: ' + eos_token") != std::string::npos) {
  12270. // OrionStarAI/Orion-14B-Chat
  12271. std::string system_prompt = "";
  12272. for (auto message : chat) {
  12273. std::string role(message->role);
  12274. if (role == "system") {
  12275. // there is no system message support, we will merge it with user prompt
  12276. system_prompt = message->content;
  12277. continue;
  12278. } else if (role == "user") {
  12279. ss << "Human: ";
  12280. if (!system_prompt.empty()) {
  12281. ss << system_prompt << "\n\n";
  12282. system_prompt = "";
  12283. }
  12284. ss << message->content << "\n\nAssistant: </s>";
  12285. } else {
  12286. ss << message->content << "</s>";
  12287. }
  12288. }
  12289. } else {
  12290. // template not supported
  12291. return -1;
  12292. }
  12293. dest = ss.str();
  12294. return dest.size();
  12295. }
  12296. LLAMA_API int32_t llama_chat_apply_template(
  12297. const struct llama_model * model,
  12298. const char * tmpl,
  12299. const struct llama_chat_message * chat,
  12300. size_t n_msg,
  12301. bool add_ass,
  12302. char * buf,
  12303. int32_t length) {
  12304. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  12305. if (tmpl == nullptr) {
  12306. GGML_ASSERT(model != nullptr);
  12307. // load template from model
  12308. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  12309. std::string template_key = "tokenizer.chat_template";
  12310. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  12311. if (res < 0) {
  12312. // worst case: there is no information about template, we will use chatml by default
  12313. curr_tmpl = "chatml"; // see llama_chat_apply_template_internal
  12314. } else {
  12315. curr_tmpl = std::string(model_template.data(), model_template.size());
  12316. }
  12317. }
  12318. // format the chat to string
  12319. std::vector<const llama_chat_message *> chat_vec;
  12320. chat_vec.resize(n_msg);
  12321. for (size_t i = 0; i < n_msg; i++) {
  12322. chat_vec[i] = &chat[i];
  12323. }
  12324. std::string formatted_chat;
  12325. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  12326. if (res < 0) {
  12327. return res;
  12328. }
  12329. if (buf && length > 0) {
  12330. strncpy(buf, formatted_chat.c_str(), length);
  12331. }
  12332. return res;
  12333. }
  12334. LLAMA_API int llama_split_path(char * split_path, size_t maxlen, const char * path_prefix, int split_no, int split_count) {
  12335. static const char * const SPLIT_PATH_FORMAT = "%s-%05d-of-%05d.gguf";
  12336. if (snprintf(split_path, maxlen, SPLIT_PATH_FORMAT, path_prefix, split_no + 1, split_count)) {
  12337. return strlen(split_path);
  12338. }
  12339. return 0;
  12340. }
  12341. int llama_split_prefix(char * dest, size_t maxlen, const char * split_path, int split_no, int split_count) {
  12342. std::string str_split_path(split_path);
  12343. char postfix[32];
  12344. snprintf(postfix, 32, "-%05d-of-%05d.gguf", split_no + 1, split_count);
  12345. std::string str_postfix(postfix);
  12346. // check if dest ends with postfix
  12347. int size_prefix = str_split_path.size() - str_postfix.size();
  12348. if (size_prefix > 0 && str_split_path.find(str_postfix, size_prefix) != std::string::npos) {
  12349. snprintf(dest, std::min((size_t) size_prefix, maxlen), "%s", split_path);
  12350. return size_prefix;
  12351. }
  12352. return 0;
  12353. }
  12354. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  12355. struct llama_timings result = {
  12356. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  12357. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  12358. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  12359. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  12360. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  12361. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  12362. /*.n_sample =*/ std::max(1, ctx->n_sample),
  12363. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  12364. /*.n_eval =*/ std::max(1, ctx->n_eval),
  12365. };
  12366. return result;
  12367. }
  12368. void llama_print_timings(struct llama_context * ctx) {
  12369. const llama_timings timings = llama_get_timings(ctx);
  12370. LLAMA_LOG_INFO("\n");
  12371. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  12372. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  12373. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  12374. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  12375. __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);
  12376. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  12377. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  12378. LLAMA_LOG_INFO("%s: total time = %10.2f ms / %5d tokens\n", __func__, (timings.t_end_ms - timings.t_start_ms), (timings.n_p_eval + timings.n_eval));
  12379. }
  12380. void llama_reset_timings(struct llama_context * ctx) {
  12381. ctx->t_start_us = ggml_time_us();
  12382. ctx->t_sample_us = ctx->n_sample = 0;
  12383. ctx->t_eval_us = ctx->n_eval = 0;
  12384. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  12385. }
  12386. const char * llama_print_system_info(void) {
  12387. static std::string s;
  12388. s = "";
  12389. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  12390. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  12391. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  12392. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  12393. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  12394. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  12395. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  12396. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  12397. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  12398. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  12399. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  12400. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  12401. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  12402. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  12403. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  12404. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  12405. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  12406. return s.c_str();
  12407. }
  12408. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  12409. fprintf(stream, "\n");
  12410. fprintf(stream, "###########\n");
  12411. fprintf(stream, "# Timings #\n");
  12412. fprintf(stream, "###########\n");
  12413. fprintf(stream, "\n");
  12414. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  12415. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  12416. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  12417. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  12418. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  12419. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  12420. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  12421. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  12422. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  12423. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  12424. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  12425. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  12426. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  12427. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  12428. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  12429. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  12430. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  12431. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  12432. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  12433. }
  12434. // For internal test use
  12435. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  12436. struct llama_context * ctx
  12437. ) {
  12438. return ctx->model.tensors_by_name;
  12439. }
  12440. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  12441. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  12442. g_state.log_callback_user_data = user_data;
  12443. #ifdef GGML_USE_METAL
  12444. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  12445. #endif
  12446. }
  12447. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  12448. va_list args_copy;
  12449. va_copy(args_copy, args);
  12450. char buffer[128];
  12451. int len = vsnprintf(buffer, 128, format, args);
  12452. if (len < 128) {
  12453. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  12454. } else {
  12455. char* buffer2 = new char[len+1];
  12456. vsnprintf(buffer2, len+1, format, args_copy);
  12457. buffer2[len] = 0;
  12458. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  12459. delete[] buffer2;
  12460. }
  12461. va_end(args_copy);
  12462. }
  12463. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  12464. va_list args;
  12465. va_start(args, format);
  12466. llama_log_internal_v(level, format, args);
  12467. va_end(args);
  12468. }
  12469. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  12470. (void) level;
  12471. (void) user_data;
  12472. fputs(text, stderr);
  12473. fflush(stderr);
  12474. }