llama.cpp 532 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696
  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. #include <io.h>
  50. #endif
  51. #include <algorithm>
  52. #include <array>
  53. #include <cassert>
  54. #include <cfloat>
  55. #include <cinttypes>
  56. #include <climits>
  57. #include <cmath>
  58. #include <cstdarg>
  59. #include <cstddef>
  60. #include <cstdint>
  61. #include <cstdio>
  62. #include <cstring>
  63. #include <ctime>
  64. #include <cwctype>
  65. #include <forward_list>
  66. #include <fstream>
  67. #include <functional>
  68. #include <initializer_list>
  69. #include <locale>
  70. #include <map>
  71. #include <memory>
  72. #include <mutex>
  73. #include <numeric>
  74. #include <queue>
  75. #include <random>
  76. #include <regex>
  77. #include <set>
  78. #include <sstream>
  79. #include <thread>
  80. #include <type_traits>
  81. #include <unordered_map>
  82. #if defined(_MSC_VER)
  83. #pragma warning(disable: 4244 4267) // possible loss of data
  84. #endif
  85. #ifdef __GNUC__
  86. #ifdef __MINGW32__
  87. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  88. #else
  89. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  90. #endif
  91. #else
  92. #define LLAMA_ATTRIBUTE_FORMAT(...)
  93. #endif
  94. #define LLAMA_MAX_NODES 8192
  95. #define LLAMA_MAX_EXPERTS 8
  96. //
  97. // logging
  98. //
  99. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  100. static void llama_log_internal (ggml_log_level level, const char* format, ...);
  101. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
  102. #define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  103. #define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  104. #define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  105. //
  106. // helpers
  107. //
  108. static size_t utf8_len(char src) {
  109. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  110. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  111. return lookup[highbits];
  112. }
  113. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  114. std::string result;
  115. for (size_t pos = 0; ; pos += search.length()) {
  116. auto new_pos = s.find(search, pos);
  117. if (new_pos == std::string::npos) {
  118. result += s.substr(pos, s.size() - pos);
  119. break;
  120. }
  121. result += s.substr(pos, new_pos - pos) + replace;
  122. pos = new_pos;
  123. }
  124. s = std::move(result);
  125. }
  126. static bool is_float_close(float a, float b, float abs_tol) {
  127. // Check for non-negative tolerance
  128. if (abs_tol < 0.0) {
  129. throw std::invalid_argument("Tolerance must be non-negative");
  130. }
  131. // Exact equality check
  132. if (a == b) {
  133. return true;
  134. }
  135. // Check for infinities
  136. if (std::isinf(a) || std::isinf(b)) {
  137. return false;
  138. }
  139. // Regular comparison using the provided absolute tolerance
  140. return std::fabs(b - a) <= abs_tol;
  141. }
  142. static void zeros(std::ofstream & file, size_t n) {
  143. char zero = 0;
  144. for (size_t i = 0; i < n; ++i) {
  145. file.write(&zero, 1);
  146. }
  147. }
  148. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  149. static std::string format(const char * fmt, ...) {
  150. va_list ap;
  151. va_list ap2;
  152. va_start(ap, fmt);
  153. va_copy(ap2, ap);
  154. int size = vsnprintf(NULL, 0, fmt, ap);
  155. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  156. std::vector<char> buf(size + 1);
  157. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  158. GGML_ASSERT(size2 == size);
  159. va_end(ap2);
  160. va_end(ap);
  161. return std::string(buf.data(), size);
  162. }
  163. //
  164. // gguf constants (sync with gguf.py)
  165. //
  166. enum llm_arch {
  167. LLM_ARCH_LLAMA,
  168. LLM_ARCH_FALCON,
  169. LLM_ARCH_BAICHUAN,
  170. LLM_ARCH_GPT2,
  171. LLM_ARCH_GPTJ,
  172. LLM_ARCH_GPTNEOX,
  173. LLM_ARCH_MPT,
  174. LLM_ARCH_STARCODER,
  175. LLM_ARCH_PERSIMMON,
  176. LLM_ARCH_REFACT,
  177. LLM_ARCH_BERT,
  178. LLM_ARCH_NOMIC_BERT,
  179. LLM_ARCH_BLOOM,
  180. LLM_ARCH_STABLELM,
  181. LLM_ARCH_QWEN,
  182. LLM_ARCH_QWEN2,
  183. LLM_ARCH_PHI2,
  184. LLM_ARCH_PLAMO,
  185. LLM_ARCH_CODESHELL,
  186. LLM_ARCH_ORION,
  187. LLM_ARCH_INTERNLM2,
  188. LLM_ARCH_MINICPM,
  189. LLM_ARCH_GEMMA,
  190. LLM_ARCH_STARCODER2,
  191. LLM_ARCH_UNKNOWN,
  192. };
  193. static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  194. { LLM_ARCH_LLAMA, "llama" },
  195. { LLM_ARCH_FALCON, "falcon" },
  196. { LLM_ARCH_GPT2, "gpt2" },
  197. { LLM_ARCH_GPTJ, "gptj" },
  198. { LLM_ARCH_GPTNEOX, "gptneox" },
  199. { LLM_ARCH_MPT, "mpt" },
  200. { LLM_ARCH_BAICHUAN, "baichuan" },
  201. { LLM_ARCH_STARCODER, "starcoder" },
  202. { LLM_ARCH_PERSIMMON, "persimmon" },
  203. { LLM_ARCH_REFACT, "refact" },
  204. { LLM_ARCH_BERT, "bert" },
  205. { LLM_ARCH_NOMIC_BERT, "nomic-bert" },
  206. { LLM_ARCH_BLOOM, "bloom" },
  207. { LLM_ARCH_STABLELM, "stablelm" },
  208. { LLM_ARCH_QWEN, "qwen" },
  209. { LLM_ARCH_QWEN2, "qwen2" },
  210. { LLM_ARCH_PHI2, "phi2" },
  211. { LLM_ARCH_PLAMO, "plamo" },
  212. { LLM_ARCH_CODESHELL, "codeshell" },
  213. { LLM_ARCH_ORION, "orion" },
  214. { LLM_ARCH_INTERNLM2, "internlm2" },
  215. { LLM_ARCH_MINICPM, "minicpm" },
  216. { LLM_ARCH_GEMMA, "gemma" },
  217. { LLM_ARCH_STARCODER2, "starcoder2" },
  218. { LLM_ARCH_UNKNOWN, "(unknown)" },
  219. };
  220. enum llm_kv {
  221. LLM_KV_GENERAL_ARCHITECTURE,
  222. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  223. LLM_KV_GENERAL_ALIGNMENT,
  224. LLM_KV_GENERAL_NAME,
  225. LLM_KV_GENERAL_AUTHOR,
  226. LLM_KV_GENERAL_URL,
  227. LLM_KV_GENERAL_DESCRIPTION,
  228. LLM_KV_GENERAL_LICENSE,
  229. LLM_KV_GENERAL_SOURCE_URL,
  230. LLM_KV_GENERAL_SOURCE_HF_REPO,
  231. LLM_KV_CONTEXT_LENGTH,
  232. LLM_KV_EMBEDDING_LENGTH,
  233. LLM_KV_BLOCK_COUNT,
  234. LLM_KV_FEED_FORWARD_LENGTH,
  235. LLM_KV_USE_PARALLEL_RESIDUAL,
  236. LLM_KV_TENSOR_DATA_LAYOUT,
  237. LLM_KV_EXPERT_COUNT,
  238. LLM_KV_EXPERT_USED_COUNT,
  239. LLM_KV_POOLING_TYPE,
  240. LLM_KV_ATTENTION_HEAD_COUNT,
  241. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  242. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  243. LLM_KV_ATTENTION_CLAMP_KQV,
  244. LLM_KV_ATTENTION_KEY_LENGTH,
  245. LLM_KV_ATTENTION_VALUE_LENGTH,
  246. LLM_KV_ATTENTION_LAYERNORM_EPS,
  247. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  248. LLM_KV_ATTENTION_CAUSAL,
  249. LLM_KV_ROPE_DIMENSION_COUNT,
  250. LLM_KV_ROPE_FREQ_BASE,
  251. LLM_KV_ROPE_SCALE_LINEAR,
  252. LLM_KV_ROPE_SCALING_TYPE,
  253. LLM_KV_ROPE_SCALING_FACTOR,
  254. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  255. LLM_KV_ROPE_SCALING_FINETUNED,
  256. LLM_KV_TOKENIZER_MODEL,
  257. LLM_KV_TOKENIZER_LIST,
  258. LLM_KV_TOKENIZER_TOKEN_TYPE,
  259. LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT,
  260. LLM_KV_TOKENIZER_SCORES,
  261. LLM_KV_TOKENIZER_MERGES,
  262. LLM_KV_TOKENIZER_BOS_ID,
  263. LLM_KV_TOKENIZER_EOS_ID,
  264. LLM_KV_TOKENIZER_UNK_ID,
  265. LLM_KV_TOKENIZER_SEP_ID,
  266. LLM_KV_TOKENIZER_PAD_ID,
  267. LLM_KV_TOKENIZER_ADD_BOS,
  268. LLM_KV_TOKENIZER_ADD_EOS,
  269. LLM_KV_TOKENIZER_ADD_PREFIX,
  270. LLM_KV_TOKENIZER_HF_JSON,
  271. LLM_KV_TOKENIZER_RWKV,
  272. };
  273. static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
  274. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  275. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  276. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  277. { LLM_KV_GENERAL_NAME, "general.name" },
  278. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  279. { LLM_KV_GENERAL_URL, "general.url" },
  280. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  281. { LLM_KV_GENERAL_LICENSE, "general.license" },
  282. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  283. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  284. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  285. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  286. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  287. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  288. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  289. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  290. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  291. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  292. { LLM_KV_POOLING_TYPE , "%s.pooling_type" },
  293. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  294. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  295. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  296. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  297. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  298. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  299. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  300. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  301. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  302. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  303. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  304. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  305. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  306. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  307. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  308. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  309. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  310. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  311. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  312. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  313. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  314. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  315. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  316. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  317. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  318. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  319. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  320. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  321. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  322. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  323. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  324. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  325. };
  326. struct LLM_KV {
  327. LLM_KV(llm_arch arch) : arch(arch) {}
  328. llm_arch arch;
  329. std::string operator()(llm_kv kv) const {
  330. return ::format(LLM_KV_NAMES.at(kv), LLM_ARCH_NAMES.at(arch));
  331. }
  332. };
  333. enum llm_tensor {
  334. LLM_TENSOR_TOKEN_EMBD,
  335. LLM_TENSOR_TOKEN_EMBD_NORM,
  336. LLM_TENSOR_TOKEN_TYPES,
  337. LLM_TENSOR_POS_EMBD,
  338. LLM_TENSOR_OUTPUT,
  339. LLM_TENSOR_OUTPUT_NORM,
  340. LLM_TENSOR_ROPE_FREQS,
  341. LLM_TENSOR_ATTN_Q,
  342. LLM_TENSOR_ATTN_K,
  343. LLM_TENSOR_ATTN_V,
  344. LLM_TENSOR_ATTN_QKV,
  345. LLM_TENSOR_ATTN_OUT,
  346. LLM_TENSOR_ATTN_NORM,
  347. LLM_TENSOR_ATTN_NORM_2,
  348. LLM_TENSOR_ATTN_OUT_NORM,
  349. LLM_TENSOR_ATTN_ROT_EMBD,
  350. LLM_TENSOR_FFN_GATE_INP,
  351. LLM_TENSOR_FFN_NORM,
  352. LLM_TENSOR_FFN_GATE,
  353. LLM_TENSOR_FFN_DOWN,
  354. LLM_TENSOR_FFN_UP,
  355. LLM_TENSOR_FFN_ACT,
  356. LLM_TENSOR_FFN_DOWN_EXP,
  357. LLM_TENSOR_FFN_GATE_EXP,
  358. LLM_TENSOR_FFN_UP_EXP,
  359. LLM_TENSOR_ATTN_Q_NORM,
  360. LLM_TENSOR_ATTN_K_NORM,
  361. LLM_TENSOR_LAYER_OUT_NORM,
  362. };
  363. static const std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  364. {
  365. LLM_ARCH_LLAMA,
  366. {
  367. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  368. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  369. { LLM_TENSOR_OUTPUT, "output" },
  370. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  371. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  372. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  373. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  374. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  375. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  376. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  377. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  378. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  379. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  380. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  381. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  382. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  383. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  384. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  385. },
  386. },
  387. {
  388. LLM_ARCH_BAICHUAN,
  389. {
  390. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  391. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  392. { LLM_TENSOR_OUTPUT, "output" },
  393. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  394. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  395. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  396. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  397. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  398. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  399. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  400. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  401. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  402. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  403. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  404. },
  405. },
  406. {
  407. LLM_ARCH_FALCON,
  408. {
  409. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  410. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  411. { LLM_TENSOR_OUTPUT, "output" },
  412. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  413. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  414. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  415. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  416. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  417. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  418. },
  419. },
  420. {
  421. LLM_ARCH_GPT2,
  422. {
  423. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  424. { LLM_TENSOR_POS_EMBD, "position_embd" },
  425. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  426. { LLM_TENSOR_OUTPUT, "output" },
  427. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  428. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  429. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  430. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  431. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  432. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  433. },
  434. },
  435. {
  436. LLM_ARCH_GPTJ,
  437. {
  438. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  439. },
  440. },
  441. {
  442. LLM_ARCH_GPTNEOX,
  443. {
  444. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  445. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  446. { LLM_TENSOR_OUTPUT, "output" },
  447. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  448. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  449. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  450. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  451. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  452. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  453. },
  454. },
  455. {
  456. LLM_ARCH_PERSIMMON,
  457. {
  458. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  459. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  460. { LLM_TENSOR_OUTPUT, "output"},
  461. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  462. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  463. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  464. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  465. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  466. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  467. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  468. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  469. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  470. },
  471. },
  472. {
  473. LLM_ARCH_MPT,
  474. {
  475. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  476. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  477. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  478. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  479. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  480. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  481. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  482. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  483. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  484. },
  485. },
  486. {
  487. LLM_ARCH_STARCODER,
  488. {
  489. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  490. { LLM_TENSOR_POS_EMBD, "position_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_FFN_NORM, "blk.%d.ffn_norm" },
  497. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  498. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  499. },
  500. },
  501. {
  502. LLM_ARCH_REFACT,
  503. {
  504. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  505. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  506. { LLM_TENSOR_OUTPUT, "output" },
  507. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  508. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  509. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  510. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  511. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  512. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  513. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  514. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  515. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  516. },
  517. },
  518. {
  519. LLM_ARCH_BERT,
  520. {
  521. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  522. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  523. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  524. { LLM_TENSOR_POS_EMBD, "position_embd" },
  525. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  526. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  527. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  528. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  529. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  530. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  531. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  532. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  533. },
  534. },
  535. {
  536. LLM_ARCH_NOMIC_BERT,
  537. {
  538. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  539. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  540. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  541. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  542. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  543. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  544. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  545. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  546. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  547. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  548. },
  549. },
  550. {
  551. LLM_ARCH_BLOOM,
  552. {
  553. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  554. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  555. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  556. { LLM_TENSOR_OUTPUT, "output" },
  557. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  558. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  559. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  560. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  561. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  562. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  563. },
  564. },
  565. {
  566. LLM_ARCH_STABLELM,
  567. {
  568. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  569. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  570. { LLM_TENSOR_OUTPUT, "output" },
  571. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  572. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  573. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  574. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  575. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  576. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  577. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_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_QWEN,
  585. {
  586. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  587. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  588. { LLM_TENSOR_OUTPUT, "output" },
  589. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  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_GATE, "blk.%d.ffn_gate" },
  595. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  596. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  597. },
  598. },
  599. {
  600. LLM_ARCH_QWEN2,
  601. {
  602. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  603. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  604. { LLM_TENSOR_OUTPUT, "output" },
  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_PHI2,
  618. {
  619. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  620. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  621. { LLM_TENSOR_OUTPUT, "output" },
  622. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  623. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  624. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  625. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  626. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  627. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  628. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  629. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  630. },
  631. },
  632. {
  633. LLM_ARCH_PLAMO,
  634. {
  635. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  636. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  637. { LLM_TENSOR_OUTPUT, "output" },
  638. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  639. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  640. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  641. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  642. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  643. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  644. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  645. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  646. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  647. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  648. },
  649. },
  650. {
  651. LLM_ARCH_CODESHELL,
  652. {
  653. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  654. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  655. { LLM_TENSOR_OUTPUT, "output" },
  656. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  657. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  658. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  659. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  660. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  661. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  662. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  663. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  664. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  665. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  666. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  667. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  668. },
  669. },
  670. {
  671. LLM_ARCH_ORION,
  672. {
  673. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  674. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  675. { LLM_TENSOR_OUTPUT, "output" },
  676. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  677. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  678. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  679. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  680. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  681. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  682. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  683. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  684. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  685. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  686. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  687. },
  688. },
  689. {
  690. LLM_ARCH_INTERNLM2,
  691. {
  692. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  693. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  694. { LLM_TENSOR_OUTPUT, "output" },
  695. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  696. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  697. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  698. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  699. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  700. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  701. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  702. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  703. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  704. },
  705. },
  706. {
  707. LLM_ARCH_MINICPM,
  708. {
  709. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  710. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  711. { LLM_TENSOR_OUTPUT, "output" },
  712. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  713. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  714. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  715. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  716. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  717. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  718. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  719. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  720. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  721. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  722. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  723. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  724. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  725. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  726. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  727. },
  728. },
  729. {
  730. LLM_ARCH_GEMMA,
  731. {
  732. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  733. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  734. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  735. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  736. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  737. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  738. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  739. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  740. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  741. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  742. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  743. },
  744. },
  745. {
  746. LLM_ARCH_STARCODER2,
  747. {
  748. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  749. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  750. { LLM_TENSOR_OUTPUT, "output" },
  751. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  752. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  753. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  754. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  755. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  756. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  757. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  758. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  759. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  760. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  761. },
  762. },
  763. {
  764. LLM_ARCH_UNKNOWN,
  765. {
  766. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  767. },
  768. },
  769. };
  770. static llm_arch llm_arch_from_string(const std::string & name) {
  771. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  772. if (kv.second == name) {
  773. return kv.first;
  774. }
  775. }
  776. return LLM_ARCH_UNKNOWN;
  777. }
  778. // helper to handle gguf constants
  779. // usage:
  780. //
  781. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  782. //
  783. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  784. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  785. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  786. //
  787. struct LLM_TN {
  788. LLM_TN(llm_arch arch) : arch(arch) {}
  789. llm_arch arch;
  790. std::string operator()(llm_tensor tensor) const {
  791. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  792. return "__missing__";
  793. }
  794. return LLM_TENSOR_NAMES.at(arch).at(tensor);
  795. }
  796. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  797. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  798. return "__missing__";
  799. }
  800. return LLM_TENSOR_NAMES.at(arch).at(tensor) + "." + suffix;
  801. }
  802. std::string operator()(llm_tensor tensor, int bid) const {
  803. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  804. return "__missing__";
  805. }
  806. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid);
  807. }
  808. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  809. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  810. return "__missing__";
  811. }
  812. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid) + "." + suffix;
  813. }
  814. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  815. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  816. return "__missing__";
  817. }
  818. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid, xid) + "." + suffix;
  819. }
  820. };
  821. //
  822. // gguf helpers
  823. //
  824. static const std::map<llama_rope_scaling_type, const char *> LLAMA_ROPE_SCALING_TYPES = {
  825. { LLAMA_ROPE_SCALING_TYPE_NONE, "none" },
  826. { LLAMA_ROPE_SCALING_TYPE_LINEAR, "linear" },
  827. { LLAMA_ROPE_SCALING_TYPE_YARN, "yarn" },
  828. };
  829. static llama_rope_scaling_type llama_rope_scaling_type_from_string(const std::string & name) {
  830. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  831. if (kv.second == name) {
  832. return (llama_rope_scaling_type) kv.first;
  833. }
  834. }
  835. return LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
  836. }
  837. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  838. switch (type) {
  839. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  840. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  841. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  842. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  843. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  844. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  845. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  846. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  847. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  848. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  849. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  850. default: return format("unknown type %d", type);
  851. }
  852. }
  853. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  854. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  855. switch (type) {
  856. case GGUF_TYPE_STRING:
  857. return gguf_get_val_str(ctx_gguf, i);
  858. case GGUF_TYPE_ARRAY:
  859. {
  860. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  861. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  862. const void * data = gguf_get_arr_data(ctx_gguf, i);
  863. std::stringstream ss;
  864. ss << "[";
  865. for (int j = 0; j < arr_n; j++) {
  866. if (arr_type == GGUF_TYPE_STRING) {
  867. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  868. // escape quotes
  869. replace_all(val, "\\", "\\\\");
  870. replace_all(val, "\"", "\\\"");
  871. ss << '"' << val << '"';
  872. } else if (arr_type == GGUF_TYPE_ARRAY) {
  873. ss << "???";
  874. } else {
  875. ss << gguf_data_to_str(arr_type, data, j);
  876. }
  877. if (j < arr_n - 1) {
  878. ss << ", ";
  879. }
  880. }
  881. ss << "]";
  882. return ss.str();
  883. }
  884. default:
  885. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  886. }
  887. }
  888. //
  889. // ggml helpers
  890. //
  891. static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
  892. struct ggml_cplan plan = ggml_graph_plan(graph, n_threads);
  893. if (plan.work_size > 0) {
  894. buf.resize(plan.work_size);
  895. plan.work_data = buf.data();
  896. }
  897. ggml_graph_compute(graph, &plan);
  898. }
  899. //
  900. // llama helpers
  901. //
  902. #if defined(_WIN32)
  903. static std::string llama_format_win_err(DWORD err) {
  904. LPSTR buf;
  905. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  906. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  907. if (!size) {
  908. return "FormatMessageA failed";
  909. }
  910. std::string ret(buf, size);
  911. LocalFree(buf);
  912. return ret;
  913. }
  914. #endif
  915. template <typename T>
  916. struct no_init {
  917. T value;
  918. no_init() { /* do nothing */ }
  919. };
  920. struct llama_file {
  921. // use FILE * so we don't have to re-open the file to mmap
  922. FILE * fp;
  923. size_t size;
  924. llama_file(const char * fname, const char * mode) {
  925. fp = std::fopen(fname, mode);
  926. if (fp == NULL) {
  927. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  928. }
  929. seek(0, SEEK_END);
  930. size = tell();
  931. seek(0, SEEK_SET);
  932. }
  933. size_t tell() const {
  934. #ifdef _WIN32
  935. __int64 ret = _ftelli64(fp);
  936. #else
  937. long ret = std::ftell(fp);
  938. #endif
  939. GGML_ASSERT(ret != -1); // this really shouldn't fail
  940. return (size_t) ret;
  941. }
  942. void seek(size_t offset, int whence) const {
  943. #ifdef _WIN32
  944. int ret = _fseeki64(fp, (__int64) offset, whence);
  945. #else
  946. int ret = std::fseek(fp, (long) offset, whence);
  947. #endif
  948. GGML_ASSERT(ret == 0); // same
  949. }
  950. void read_raw(void * ptr, size_t len) const {
  951. if (len == 0) {
  952. return;
  953. }
  954. errno = 0;
  955. std::size_t ret = std::fread(ptr, len, 1, fp);
  956. if (ferror(fp)) {
  957. throw std::runtime_error(format("read error: %s", strerror(errno)));
  958. }
  959. if (ret != 1) {
  960. throw std::runtime_error("unexpectedly reached end of file");
  961. }
  962. }
  963. uint32_t read_u32() const {
  964. uint32_t ret;
  965. read_raw(&ret, sizeof(ret));
  966. return ret;
  967. }
  968. void write_raw(const void * ptr, size_t len) const {
  969. if (len == 0) {
  970. return;
  971. }
  972. errno = 0;
  973. size_t ret = std::fwrite(ptr, len, 1, fp);
  974. if (ret != 1) {
  975. throw std::runtime_error(format("write error: %s", strerror(errno)));
  976. }
  977. }
  978. void write_u32(std::uint32_t val) const {
  979. write_raw(&val, sizeof(val));
  980. }
  981. ~llama_file() {
  982. if (fp) {
  983. std::fclose(fp);
  984. }
  985. }
  986. };
  987. struct llama_mmap {
  988. void * addr;
  989. size_t size;
  990. llama_mmap(const llama_mmap &) = delete;
  991. #ifdef _POSIX_MAPPED_FILES
  992. static constexpr bool SUPPORTED = true;
  993. // list of mapped fragments (first_offset, last_offset)
  994. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  995. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  996. size = file->size;
  997. int fd = fileno(file->fp);
  998. int flags = MAP_SHARED;
  999. // prefetch/readahead impairs performance on NUMA systems
  1000. if (numa) { prefetch = 0; }
  1001. #ifdef __linux__
  1002. // advise the kernel to read the file sequentially (increases readahead)
  1003. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  1004. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  1005. strerror(errno));
  1006. }
  1007. if (prefetch) { flags |= MAP_POPULATE; }
  1008. #endif
  1009. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  1010. if (addr == MAP_FAILED) { // NOLINT
  1011. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  1012. }
  1013. if (prefetch > 0) {
  1014. // advise the kernel to preload the mapped memory
  1015. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  1016. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  1017. strerror(errno));
  1018. }
  1019. }
  1020. if (numa) {
  1021. // advise the kernel not to use readahead
  1022. // (because the next page might not belong on the same node)
  1023. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  1024. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  1025. strerror(errno));
  1026. }
  1027. }
  1028. // initialize list of mapped_fragments
  1029. mapped_fragments.emplace_back(0, file->size);
  1030. }
  1031. static void align_range(size_t * first, size_t * last, size_t page_size) {
  1032. // align first to the next page
  1033. size_t offset_in_page = *first & (page_size - 1);
  1034. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  1035. *first += offset_to_page;
  1036. // align last to the previous page
  1037. *last = *last & ~(page_size - 1);
  1038. if (*last <= *first) {
  1039. *last = *first;
  1040. }
  1041. }
  1042. // partially unmap the file in the range [first, last)
  1043. void unmap_fragment(size_t first, size_t last) {
  1044. // note: this function must not be called multiple times with overlapping ranges
  1045. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  1046. int page_size = sysconf(_SC_PAGESIZE);
  1047. align_range(&first, &last, page_size);
  1048. size_t len = last - first;
  1049. if (len == 0) {
  1050. return;
  1051. }
  1052. GGML_ASSERT(first % page_size == 0);
  1053. GGML_ASSERT(last % page_size == 0);
  1054. GGML_ASSERT(last > first);
  1055. void * next_page_start = (uint8_t *) addr + first;
  1056. // unmap the range
  1057. if (munmap(next_page_start, len)) {
  1058. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1059. }
  1060. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  1061. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  1062. for (const auto & frag : mapped_fragments) {
  1063. if (frag.first < first && frag.second > last) {
  1064. // the range is in the middle of the fragment, split it
  1065. new_mapped_fragments.emplace_back(frag.first, first);
  1066. new_mapped_fragments.emplace_back(last, frag.second);
  1067. } else if (frag.first < first && frag.second > first) {
  1068. // the range starts in the middle of the fragment
  1069. new_mapped_fragments.emplace_back(frag.first, first);
  1070. } else if (frag.first < last && frag.second > last) {
  1071. // the range ends in the middle of the fragment
  1072. new_mapped_fragments.emplace_back(last, frag.second);
  1073. } else if (frag.first >= first && frag.second <= last) {
  1074. // the range covers the entire fragment
  1075. } else {
  1076. // the range is outside the fragment
  1077. new_mapped_fragments.push_back(frag);
  1078. }
  1079. }
  1080. mapped_fragments = std::move(new_mapped_fragments);
  1081. }
  1082. ~llama_mmap() {
  1083. for (const auto & frag : mapped_fragments) {
  1084. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  1085. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1086. }
  1087. }
  1088. }
  1089. #elif defined(_WIN32)
  1090. static constexpr bool SUPPORTED = true;
  1091. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  1092. GGML_UNUSED(numa);
  1093. size = file->size;
  1094. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  1095. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  1096. if (hMapping == NULL) {
  1097. DWORD error = GetLastError();
  1098. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  1099. }
  1100. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  1101. DWORD error = GetLastError();
  1102. CloseHandle(hMapping);
  1103. if (addr == NULL) {
  1104. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  1105. }
  1106. if (prefetch > 0) {
  1107. #if _WIN32_WINNT >= 0x602
  1108. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  1109. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  1110. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  1111. // may fail on pre-Windows 8 systems
  1112. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  1113. if (pPrefetchVirtualMemory) {
  1114. // advise the kernel to preload the mapped memory
  1115. WIN32_MEMORY_RANGE_ENTRY range;
  1116. range.VirtualAddress = addr;
  1117. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  1118. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  1119. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  1120. llama_format_win_err(GetLastError()).c_str());
  1121. }
  1122. }
  1123. #else
  1124. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  1125. #endif
  1126. }
  1127. }
  1128. void unmap_fragment(size_t first, size_t last) {
  1129. // not supported
  1130. GGML_UNUSED(first);
  1131. GGML_UNUSED(last);
  1132. }
  1133. ~llama_mmap() {
  1134. if (!UnmapViewOfFile(addr)) {
  1135. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  1136. llama_format_win_err(GetLastError()).c_str());
  1137. }
  1138. }
  1139. #else
  1140. static constexpr bool SUPPORTED = false;
  1141. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  1142. GGML_UNUSED(file);
  1143. GGML_UNUSED(prefetch);
  1144. GGML_UNUSED(numa);
  1145. throw std::runtime_error("mmap not supported");
  1146. }
  1147. void unmap_fragment(size_t first, size_t last) {
  1148. GGML_UNUSED(first);
  1149. GGML_UNUSED(last);
  1150. throw std::runtime_error("mmap not supported");
  1151. }
  1152. #endif
  1153. };
  1154. // Represents some region of memory being locked using mlock or VirtualLock;
  1155. // will automatically unlock on destruction.
  1156. struct llama_mlock {
  1157. void * addr = NULL;
  1158. size_t size = 0;
  1159. bool failed_already = false;
  1160. llama_mlock() {}
  1161. llama_mlock(const llama_mlock &) = delete;
  1162. ~llama_mlock() {
  1163. if (size) {
  1164. raw_unlock(addr, size);
  1165. }
  1166. }
  1167. void init(void * ptr) {
  1168. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1169. addr = ptr;
  1170. }
  1171. void grow_to(size_t target_size) {
  1172. GGML_ASSERT(addr);
  1173. if (failed_already) {
  1174. return;
  1175. }
  1176. size_t granularity = lock_granularity();
  1177. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1178. if (target_size > size) {
  1179. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1180. size = target_size;
  1181. } else {
  1182. failed_already = true;
  1183. }
  1184. }
  1185. }
  1186. #ifdef _POSIX_MEMLOCK_RANGE
  1187. static constexpr bool SUPPORTED = true;
  1188. static size_t lock_granularity() {
  1189. return (size_t) sysconf(_SC_PAGESIZE);
  1190. }
  1191. #ifdef __APPLE__
  1192. #define MLOCK_SUGGESTION \
  1193. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1194. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  1195. #else
  1196. #define MLOCK_SUGGESTION \
  1197. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  1198. #endif
  1199. bool raw_lock(const void * addr, size_t size) const {
  1200. if (!mlock(addr, size)) {
  1201. return true;
  1202. }
  1203. char* errmsg = std::strerror(errno);
  1204. bool suggest = (errno == ENOMEM);
  1205. // Check if the resource limit is fine after all
  1206. struct rlimit lock_limit;
  1207. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1208. suggest = false;
  1209. }
  1210. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1211. suggest = false;
  1212. }
  1213. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1214. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1215. return false;
  1216. }
  1217. #undef MLOCK_SUGGESTION
  1218. static void raw_unlock(void * addr, size_t size) {
  1219. if (munlock(addr, size)) {
  1220. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1221. }
  1222. }
  1223. #elif defined(_WIN32)
  1224. static constexpr bool SUPPORTED = true;
  1225. static size_t lock_granularity() {
  1226. SYSTEM_INFO si;
  1227. GetSystemInfo(&si);
  1228. return (size_t) si.dwPageSize;
  1229. }
  1230. bool raw_lock(void * ptr, size_t len) const {
  1231. for (int tries = 1; ; tries++) {
  1232. if (VirtualLock(ptr, len)) {
  1233. return true;
  1234. }
  1235. if (tries == 2) {
  1236. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1237. len, size, llama_format_win_err(GetLastError()).c_str());
  1238. return false;
  1239. }
  1240. // It failed but this was only the first try; increase the working
  1241. // set size and try again.
  1242. SIZE_T min_ws_size, max_ws_size;
  1243. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1244. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1245. llama_format_win_err(GetLastError()).c_str());
  1246. return false;
  1247. }
  1248. // Per MSDN: "The maximum number of pages that a process can lock
  1249. // is equal to the number of pages in its minimum working set minus
  1250. // a small overhead."
  1251. // Hopefully a megabyte is enough overhead:
  1252. size_t increment = len + 1048576;
  1253. // The minimum must be <= the maximum, so we need to increase both:
  1254. min_ws_size += increment;
  1255. max_ws_size += increment;
  1256. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1257. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1258. llama_format_win_err(GetLastError()).c_str());
  1259. return false;
  1260. }
  1261. }
  1262. }
  1263. static void raw_unlock(void * ptr, size_t len) {
  1264. if (!VirtualUnlock(ptr, len)) {
  1265. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1266. llama_format_win_err(GetLastError()).c_str());
  1267. }
  1268. }
  1269. #else
  1270. static constexpr bool SUPPORTED = false;
  1271. static size_t lock_granularity() {
  1272. return (size_t) 65536;
  1273. }
  1274. bool raw_lock(const void * addr, size_t len) const {
  1275. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1276. return false;
  1277. }
  1278. static void raw_unlock(const void * addr, size_t len) {}
  1279. #endif
  1280. };
  1281. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1282. std::vector<char> result(8, 0);
  1283. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1284. if (n_tokens < 0) {
  1285. result.resize(-n_tokens);
  1286. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1287. GGML_ASSERT(check == -n_tokens);
  1288. }
  1289. else {
  1290. result.resize(n_tokens);
  1291. }
  1292. return std::string(result.data(), result.size());
  1293. }
  1294. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1295. ggml_backend_buffer_type_t buft = nullptr;
  1296. #if defined(GGML_USE_CUBLAS)
  1297. // host buffers should only be used when data is expected to be copied to/from the GPU
  1298. if (host_buffer) {
  1299. buft = ggml_backend_cuda_host_buffer_type();
  1300. }
  1301. #elif defined(GGML_USE_SYCL)
  1302. if (host_buffer) {
  1303. buft = ggml_backend_sycl_host_buffer_type();
  1304. }
  1305. #elif defined(GGML_USE_CPU_HBM)
  1306. buft = ggml_backend_cpu_hbm_buffer_type();
  1307. #elif defined(GGML_USE_VULKAN)
  1308. if (host_buffer) {
  1309. buft = ggml_backend_vk_host_buffer_type();
  1310. }
  1311. #endif
  1312. if (buft == nullptr) {
  1313. buft = ggml_backend_cpu_buffer_type();
  1314. }
  1315. return buft;
  1316. GGML_UNUSED(host_buffer);
  1317. }
  1318. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(int gpu) {
  1319. ggml_backend_buffer_type_t buft = nullptr;
  1320. #ifdef GGML_USE_METAL
  1321. buft = ggml_backend_metal_buffer_type();
  1322. #elif defined(GGML_USE_CUBLAS)
  1323. buft = ggml_backend_cuda_buffer_type(gpu);
  1324. #elif defined(GGML_USE_VULKAN)
  1325. buft = ggml_backend_vk_buffer_type(gpu);
  1326. #elif defined(GGML_USE_SYCL)
  1327. buft = ggml_backend_sycl_buffer_type(gpu);
  1328. #elif defined(GGML_USE_CLBLAST)
  1329. buft = ggml_backend_opencl_buffer_type();
  1330. #elif defined(GGML_USE_KOMPUTE)
  1331. buft = ggml_backend_kompute_buffer_type(gpu);
  1332. if (buft == nullptr) {
  1333. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, gpu);
  1334. }
  1335. #endif
  1336. if (buft == nullptr) {
  1337. buft = llama_default_buffer_type_cpu(true);
  1338. }
  1339. return buft;
  1340. GGML_UNUSED(gpu);
  1341. }
  1342. static ggml_backend_buffer_type_t llama_default_buffer_type_split(int fallback_gpu, const float * tensor_split) {
  1343. ggml_backend_buffer_type_t buft = nullptr;
  1344. #ifdef GGML_USE_CUBLAS
  1345. if (ggml_backend_cuda_get_device_count() > 1) {
  1346. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  1347. }
  1348. #endif
  1349. #ifdef GGML_USE_SYCL
  1350. if (ggml_backend_sycl_get_device_count() > 1) {
  1351. buft = ggml_backend_sycl_split_buffer_type(tensor_split);
  1352. }
  1353. #endif
  1354. if (buft == nullptr) {
  1355. buft = llama_default_buffer_type_offload(fallback_gpu);
  1356. }
  1357. return buft;
  1358. GGML_UNUSED(tensor_split);
  1359. }
  1360. static size_t llama_get_device_count() {
  1361. #if defined(GGML_USE_CUBLAS)
  1362. return ggml_backend_cuda_get_device_count();
  1363. #elif defined(GGML_USE_SYCL)
  1364. return ggml_backend_sycl_get_device_count();
  1365. #elif defined(GGML_USE_VULKAN)
  1366. return ggml_backend_vk_get_device_count();
  1367. #else
  1368. return 1;
  1369. #endif
  1370. }
  1371. static size_t llama_get_device_memory(int device) {
  1372. #if defined(GGML_USE_CUBLAS)
  1373. size_t total;
  1374. size_t free;
  1375. ggml_backend_cuda_get_device_memory(device, &total, &free);
  1376. return free;
  1377. #elif defined(GGML_USE_SYCL)
  1378. size_t total;
  1379. size_t free;
  1380. ggml_backend_sycl_get_device_memory(device, &total, &free);
  1381. return free;
  1382. #elif defined(GGML_USE_VULKAN)
  1383. size_t total;
  1384. size_t free;
  1385. ggml_backend_vk_get_device_memory(device, &total, &free);
  1386. return free;
  1387. #else
  1388. return 1;
  1389. GGML_UNUSED(device);
  1390. #endif
  1391. }
  1392. //
  1393. // globals
  1394. //
  1395. struct llama_state {
  1396. llama_state() {
  1397. #ifdef GGML_USE_METAL
  1398. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1399. #endif
  1400. }
  1401. // We save the log callback globally
  1402. ggml_log_callback log_callback = llama_log_callback_default;
  1403. void * log_callback_user_data = nullptr;
  1404. };
  1405. static llama_state g_state;
  1406. // available llama models
  1407. enum e_model {
  1408. MODEL_UNKNOWN,
  1409. MODEL_17M,
  1410. MODEL_22M,
  1411. MODEL_33M,
  1412. MODEL_109M,
  1413. MODEL_137M,
  1414. MODEL_335M,
  1415. MODEL_0_5B,
  1416. MODEL_1B,
  1417. MODEL_2B,
  1418. MODEL_3B,
  1419. MODEL_4B,
  1420. MODEL_7B,
  1421. MODEL_8B,
  1422. MODEL_13B,
  1423. MODEL_14B,
  1424. MODEL_15B,
  1425. MODEL_20B,
  1426. MODEL_30B,
  1427. MODEL_34B,
  1428. MODEL_40B,
  1429. MODEL_65B,
  1430. MODEL_70B,
  1431. MODEL_SMALL,
  1432. MODEL_MEDIUM,
  1433. MODEL_LARGE,
  1434. MODEL_XL,
  1435. };
  1436. static const size_t kiB = 1024;
  1437. static const size_t MiB = 1024*kiB;
  1438. static const size_t GiB = 1024*MiB;
  1439. struct llama_hparams {
  1440. bool vocab_only;
  1441. bool rope_finetuned;
  1442. uint32_t n_vocab;
  1443. uint32_t n_ctx_train; // context size the model was trained on
  1444. uint32_t n_embd;
  1445. uint32_t n_head;
  1446. uint32_t n_head_kv;
  1447. uint32_t n_layer;
  1448. uint32_t n_rot;
  1449. 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
  1450. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1451. uint32_t n_ff;
  1452. uint32_t n_expert = 0;
  1453. uint32_t n_expert_used = 0;
  1454. uint32_t n_vocab_type = 0; // for BERT-style token types
  1455. float f_norm_eps;
  1456. float f_norm_rms_eps;
  1457. float rope_freq_base_train;
  1458. float rope_freq_scale_train;
  1459. uint32_t n_yarn_orig_ctx;
  1460. float f_clamp_kqv = 0.0f;
  1461. float f_max_alibi_bias = 0.0f;
  1462. bool causal_attn = true;
  1463. bool need_kq_pos = false;
  1464. enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_NONE;
  1465. enum llama_rope_type rope_type = LLAMA_ROPE_TYPE_NONE;
  1466. enum llama_rope_scaling_type rope_scaling_type_train = LLAMA_ROPE_SCALING_TYPE_NONE;
  1467. bool operator!=(const llama_hparams & other) const {
  1468. if (this->vocab_only != other.vocab_only) return true;
  1469. if (this->n_vocab != other.n_vocab) return true;
  1470. if (this->n_ctx_train != other.n_ctx_train) return true;
  1471. if (this->n_embd != other.n_embd) return true;
  1472. if (this->n_head != other.n_head) return true;
  1473. if (this->n_head_kv != other.n_head_kv) return true;
  1474. if (this->n_layer != other.n_layer) return true;
  1475. if (this->n_rot != other.n_rot) return true;
  1476. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1477. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1478. if (this->n_ff != other.n_ff) return true;
  1479. if (this->n_expert != other.n_expert) return true;
  1480. if (this->n_expert_used != other.n_expert_used) return true;
  1481. if (this->rope_finetuned != other.rope_finetuned) return true;
  1482. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1483. const float EPSILON = 1e-9f;
  1484. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1485. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1486. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1487. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1488. return false;
  1489. }
  1490. uint32_t n_gqa() const {
  1491. return n_head/n_head_kv;
  1492. }
  1493. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1494. return n_embd_head_k * n_head_kv;
  1495. }
  1496. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1497. return n_embd_head_v * n_head_kv;
  1498. }
  1499. };
  1500. struct llama_cparams {
  1501. uint32_t n_ctx; // context size used during inference
  1502. uint32_t n_batch;
  1503. uint32_t n_threads; // number of threads to use for generation
  1504. uint32_t n_threads_batch; // number of threads to use for batch processing
  1505. float rope_freq_base;
  1506. float rope_freq_scale;
  1507. uint32_t n_yarn_orig_ctx;
  1508. // These hyperparameters are not exposed in GGUF, because all
  1509. // existing YaRN models use the same values for them.
  1510. float yarn_ext_factor;
  1511. float yarn_attn_factor;
  1512. float yarn_beta_fast;
  1513. float yarn_beta_slow;
  1514. float defrag_thold;
  1515. bool embeddings;
  1516. bool offload_kqv;
  1517. enum llama_pooling_type pooling_type;
  1518. ggml_backend_sched_eval_callback cb_eval;
  1519. void * cb_eval_user_data;
  1520. };
  1521. struct llama_layer {
  1522. // normalization
  1523. struct ggml_tensor * attn_norm;
  1524. struct ggml_tensor * attn_norm_b;
  1525. struct ggml_tensor * attn_norm_2;
  1526. struct ggml_tensor * attn_norm_2_b;
  1527. struct ggml_tensor * attn_q_norm;
  1528. struct ggml_tensor * attn_q_norm_b;
  1529. struct ggml_tensor * attn_k_norm;
  1530. struct ggml_tensor * attn_k_norm_b;
  1531. struct ggml_tensor * attn_out_norm;
  1532. struct ggml_tensor * attn_out_norm_b;
  1533. // attention
  1534. struct ggml_tensor * wq;
  1535. struct ggml_tensor * wk;
  1536. struct ggml_tensor * wv;
  1537. struct ggml_tensor * wo;
  1538. struct ggml_tensor * wqkv;
  1539. // attention bias
  1540. struct ggml_tensor * bq;
  1541. struct ggml_tensor * bk;
  1542. struct ggml_tensor * bv;
  1543. struct ggml_tensor * bo;
  1544. struct ggml_tensor * bqkv;
  1545. // normalization
  1546. struct ggml_tensor * ffn_norm;
  1547. struct ggml_tensor * ffn_norm_b;
  1548. struct ggml_tensor * layer_out_norm;
  1549. struct ggml_tensor * layer_out_norm_b;
  1550. // ff
  1551. struct ggml_tensor * ffn_gate; // w1
  1552. struct ggml_tensor * ffn_down; // w2
  1553. struct ggml_tensor * ffn_up; // w3
  1554. // ff MoE
  1555. struct ggml_tensor * ffn_gate_inp;
  1556. struct ggml_tensor * ffn_gate_exp[LLAMA_MAX_EXPERTS];
  1557. struct ggml_tensor * ffn_down_exp[LLAMA_MAX_EXPERTS];
  1558. struct ggml_tensor * ffn_up_exp [LLAMA_MAX_EXPERTS];
  1559. // ff bias
  1560. struct ggml_tensor * ffn_down_b; // b2
  1561. struct ggml_tensor * ffn_up_b; // b3
  1562. struct ggml_tensor * ffn_act;
  1563. };
  1564. struct llama_kv_cell {
  1565. llama_pos pos = -1;
  1566. llama_pos delta = 0;
  1567. std::set<llama_seq_id> seq_id;
  1568. bool has_seq_id(const llama_seq_id & id) const {
  1569. return seq_id.find(id) != seq_id.end();
  1570. }
  1571. bool is_empty() const {
  1572. return seq_id.empty();
  1573. }
  1574. bool is_same_seq(const llama_kv_cell & other) const {
  1575. return seq_id == other.seq_id;
  1576. }
  1577. };
  1578. // ring-buffer of cached KV data
  1579. struct llama_kv_cache {
  1580. bool has_shift = false;
  1581. bool do_defrag = false;
  1582. // Note: The value of head isn't only used to optimize searching
  1583. // for a free KV slot. llama_decode_internal also uses it, so it
  1584. // cannot be freely changed after a slot has been allocated.
  1585. uint32_t head = 0;
  1586. uint32_t size = 0;
  1587. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1588. // computed before each graph build
  1589. uint32_t n = 0;
  1590. ggml_type type_k = GGML_TYPE_F16;
  1591. ggml_type type_v = GGML_TYPE_F16;
  1592. std::vector<llama_kv_cell> cells;
  1593. std::vector<struct ggml_tensor *> k_l; // per layer
  1594. std::vector<struct ggml_tensor *> v_l;
  1595. std::vector<struct ggml_context *> ctxs;
  1596. std::vector<ggml_backend_buffer_t> bufs;
  1597. size_t total_size() const {
  1598. size_t size = 0;
  1599. for (ggml_backend_buffer_t buf : bufs) {
  1600. size += ggml_backend_buffer_get_size(buf);
  1601. }
  1602. return size;
  1603. }
  1604. ~llama_kv_cache() {
  1605. for (struct ggml_context * ctx : ctxs) {
  1606. ggml_free(ctx);
  1607. }
  1608. for (ggml_backend_buffer_t buf : bufs) {
  1609. ggml_backend_buffer_free(buf);
  1610. }
  1611. }
  1612. };
  1613. struct llama_vocab {
  1614. using id = int32_t;
  1615. using token = std::string;
  1616. using ttype = llama_token_type;
  1617. struct token_data {
  1618. token text;
  1619. float score;
  1620. ttype type;
  1621. };
  1622. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1623. std::unordered_map<token, id> token_to_id;
  1624. std::vector<token_data> id_to_token;
  1625. std::unordered_map<token, id> special_tokens_cache;
  1626. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1627. // default LLaMA special tokens
  1628. id special_bos_id = 1;
  1629. id special_eos_id = 2;
  1630. id special_unk_id = 0;
  1631. id special_sep_id = -1;
  1632. id special_pad_id = -1;
  1633. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1634. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1635. id linefeed_id = 13;
  1636. id special_prefix_id = 32007;
  1637. id special_middle_id = 32009;
  1638. id special_suffix_id = 32008;
  1639. id special_eot_id = 32010;
  1640. bool add_space_prefix = true;
  1641. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1642. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1643. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1644. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1645. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1646. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1647. if (it == bpe_ranks.end()) {
  1648. return -1;
  1649. }
  1650. return it->second;
  1651. }
  1652. };
  1653. struct llama_model {
  1654. e_model type = MODEL_UNKNOWN;
  1655. llm_arch arch = LLM_ARCH_UNKNOWN;
  1656. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1657. std::string name = "n/a";
  1658. llama_hparams hparams = {};
  1659. llama_vocab vocab;
  1660. struct ggml_tensor * tok_embd;
  1661. struct ggml_tensor * type_embd;
  1662. struct ggml_tensor * pos_embd;
  1663. struct ggml_tensor * tok_norm;
  1664. struct ggml_tensor * tok_norm_b;
  1665. struct ggml_tensor * output_norm;
  1666. struct ggml_tensor * output_norm_b;
  1667. struct ggml_tensor * output;
  1668. struct ggml_tensor * output_b;
  1669. std::vector<llama_layer> layers;
  1670. llama_split_mode split_mode;
  1671. int main_gpu;
  1672. int n_gpu_layers;
  1673. // gguf metadata
  1674. std::unordered_map<std::string, std::string> gguf_kv;
  1675. // layer -> buffer type mapping
  1676. struct layer_buft {
  1677. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1678. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1679. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1680. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1681. ggml_backend_buffer_type_t buft; // everything else
  1682. };
  1683. layer_buft buft_input;
  1684. layer_buft buft_output;
  1685. std::vector<layer_buft> buft_layer;
  1686. // contexts where the model tensors metadata is stored
  1687. std::vector<struct ggml_context *> ctxs;
  1688. // the model memory buffers for the tensor data
  1689. std::vector<ggml_backend_buffer_t> bufs;
  1690. // model memory mapped file
  1691. std::unique_ptr<llama_mmap> mapping;
  1692. // objects representing data potentially being locked in memory
  1693. std::vector<std::unique_ptr<llama_mlock>> mlock_bufs;
  1694. llama_mlock mlock_mmap;
  1695. // for quantize-stats only
  1696. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1697. int64_t t_load_us = 0;
  1698. int64_t t_start_us = 0;
  1699. ~llama_model() {
  1700. for (struct ggml_context * ctx : ctxs) {
  1701. ggml_free(ctx);
  1702. }
  1703. for (ggml_backend_buffer_t buf : bufs) {
  1704. ggml_backend_buffer_free(buf);
  1705. }
  1706. }
  1707. };
  1708. struct llama_context {
  1709. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1710. ~llama_context() {
  1711. ggml_backend_sched_free(sched);
  1712. for (ggml_backend_t backend : backends) {
  1713. ggml_backend_free(backend);
  1714. }
  1715. #ifdef GGML_USE_VULKAN
  1716. ggml_vk_free_cpu_assist();
  1717. #endif
  1718. ggml_backend_buffer_free(buf_input);
  1719. ggml_free(ctx_input);
  1720. }
  1721. llama_cparams cparams;
  1722. std::vector<ggml_backend_t> backends;
  1723. #ifdef GGML_USE_METAL
  1724. ggml_backend_t backend_metal = nullptr;
  1725. #endif
  1726. ggml_backend_t backend_cpu = nullptr;
  1727. const llama_model & model;
  1728. // key + value cache for the self attention
  1729. struct llama_kv_cache kv_self;
  1730. std::mt19937 rng;
  1731. bool has_evaluated_once = false;
  1732. int64_t t_start_us;
  1733. int64_t t_load_us;
  1734. int64_t t_sample_us = 0;
  1735. int64_t t_p_eval_us = 0;
  1736. int64_t t_eval_us = 0;
  1737. int32_t n_sample = 0; // number of tokens sampled
  1738. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1739. int32_t n_eval = 0; // number of eval calls
  1740. // logits output (2-dimensional array: [n_tokens][n_vocab])
  1741. std::vector<float> logits;
  1742. #ifndef NDEBUG
  1743. // guard against access to unset logits
  1744. std::vector<bool> logits_valid;
  1745. #endif
  1746. bool logits_all = false;
  1747. // embeddings output (2-dimensional array: [n_tokens][n_embd])
  1748. // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE
  1749. std::vector<float> embd;
  1750. // sequence embeddings output (map of [n_embd] vectors)
  1751. // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE
  1752. std::map<llama_seq_id, std::vector<float>> embd_seq;
  1753. // memory buffers used to evaluate the model
  1754. std::vector<uint8_t> buf_compute_meta;
  1755. ggml_backend_sched_t sched = nullptr;
  1756. ggml_abort_callback abort_callback = nullptr;
  1757. void * abort_callback_data = nullptr;
  1758. // input tensors
  1759. ggml_backend_buffer_t buf_input = nullptr;
  1760. ggml_context * ctx_input = nullptr;
  1761. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  1762. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  1763. struct ggml_tensor * inp_pos; // I32 [n_batch]
  1764. struct ggml_tensor * inp_KQ_mask; // F32 [n_ctx, n_batch]
  1765. struct ggml_tensor * inp_KQ_pos; // F32 [n_ctx]
  1766. struct ggml_tensor * inp_K_shift; // I32 [n_ctx]
  1767. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  1768. struct ggml_tensor * inp_cls; // I32 [n_batch]
  1769. #ifdef GGML_USE_MPI
  1770. ggml_mpi_context * ctx_mpi = NULL;
  1771. #endif
  1772. };
  1773. //
  1774. // kv cache helpers
  1775. //
  1776. static bool llama_kv_cache_init(
  1777. struct llama_kv_cache & cache,
  1778. const llama_model & model,
  1779. ggml_type type_k,
  1780. ggml_type type_v,
  1781. uint32_t n_ctx,
  1782. bool offload) {
  1783. const struct llama_hparams & hparams = model.hparams;
  1784. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  1785. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  1786. const int64_t n_layer = hparams.n_layer;
  1787. cache.has_shift = false;
  1788. cache.head = 0;
  1789. cache.size = n_ctx;
  1790. cache.used = 0;
  1791. cache.type_k = type_k;
  1792. cache.type_v = type_v;
  1793. cache.cells.clear();
  1794. cache.cells.resize(n_ctx);
  1795. #ifdef GGML_USE_CLBLAST
  1796. offload = false;
  1797. #endif
  1798. // count used buffer types
  1799. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  1800. if (offload) {
  1801. for (int64_t i = 0; i < n_layer; ++i) {
  1802. buft_layer_count[model.buft_layer[i].buft]++;
  1803. }
  1804. } else {
  1805. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  1806. }
  1807. // create a context for each buffer type
  1808. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  1809. for (auto & it : buft_layer_count) {
  1810. int n_layers = it.second;
  1811. struct ggml_init_params params = {
  1812. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  1813. /*.mem_buffer =*/ NULL,
  1814. /*.no_alloc =*/ true,
  1815. };
  1816. ggml_context * ctx = ggml_init(params);
  1817. if (!ctx) {
  1818. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  1819. return false;
  1820. }
  1821. ctx_map[it.first] = ctx;
  1822. cache.ctxs.push_back(ctx);
  1823. }
  1824. cache.k_l.reserve(n_layer);
  1825. cache.v_l.reserve(n_layer);
  1826. for (int i = 0; i < (int) n_layer; i++) {
  1827. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  1828. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*n_ctx);
  1829. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*n_ctx);
  1830. ggml_format_name(k, "cache_k_l%d", i);
  1831. ggml_format_name(v, "cache_v_l%d", i);
  1832. cache.k_l.push_back(k);
  1833. cache.v_l.push_back(v);
  1834. }
  1835. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  1836. for (auto it : ctx_map) {
  1837. ggml_backend_buffer_type_t buft = it.first;
  1838. ggml_context * ctx = it.second;
  1839. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  1840. if (!buf) {
  1841. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  1842. return false;
  1843. }
  1844. ggml_backend_buffer_clear(buf, 0);
  1845. 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);
  1846. cache.bufs.push_back(buf);
  1847. }
  1848. return true;
  1849. }
  1850. // find an empty slot of size "n_tokens" in the cache
  1851. // updates the cache head
  1852. // Note: On success, it's important that cache.head points
  1853. // to the first cell of the slot.
  1854. static bool llama_kv_cache_find_slot(
  1855. struct llama_kv_cache & cache,
  1856. const struct llama_batch & batch) {
  1857. const uint32_t n_ctx = cache.size;
  1858. const uint32_t n_tokens = batch.n_tokens;
  1859. if (n_tokens > n_ctx) {
  1860. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  1861. return false;
  1862. }
  1863. uint32_t n_tested = 0;
  1864. while (true) {
  1865. if (cache.head + n_tokens > n_ctx) {
  1866. n_tested += n_ctx - cache.head;
  1867. cache.head = 0;
  1868. continue;
  1869. }
  1870. bool found = true;
  1871. for (uint32_t i = 0; i < n_tokens; i++) {
  1872. if (cache.cells[cache.head + i].pos >= 0) {
  1873. found = false;
  1874. cache.head += i + 1;
  1875. n_tested += i + 1;
  1876. break;
  1877. }
  1878. }
  1879. if (found) {
  1880. break;
  1881. }
  1882. if (n_tested >= n_ctx) {
  1883. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  1884. return false;
  1885. }
  1886. }
  1887. for (uint32_t i = 0; i < n_tokens; i++) {
  1888. cache.cells[cache.head + i].pos = batch.pos[i];
  1889. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  1890. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  1891. }
  1892. }
  1893. cache.used += n_tokens;
  1894. return true;
  1895. }
  1896. // find how many cells are currently in use
  1897. static uint32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  1898. for (uint32_t i = cache.size; i > 0; --i) {
  1899. const llama_kv_cell & cell = cache.cells[i - 1];
  1900. if (cell.pos >= 0 && !cell.is_empty()) {
  1901. return i;
  1902. }
  1903. }
  1904. return 0;
  1905. }
  1906. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  1907. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  1908. cache.cells[i].pos = -1;
  1909. cache.cells[i].seq_id.clear();
  1910. }
  1911. cache.head = 0;
  1912. cache.used = 0;
  1913. }
  1914. static void llama_kv_cache_seq_rm(
  1915. struct llama_kv_cache & cache,
  1916. llama_seq_id seq_id,
  1917. llama_pos p0,
  1918. llama_pos p1) {
  1919. uint32_t new_head = cache.size;
  1920. if (p0 < 0) p0 = 0;
  1921. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1922. for (uint32_t i = 0; i < cache.size; ++i) {
  1923. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1924. if (seq_id < 0) {
  1925. cache.cells[i].seq_id.clear();
  1926. } else if (cache.cells[i].has_seq_id(seq_id)) {
  1927. cache.cells[i].seq_id.erase(seq_id);
  1928. } else {
  1929. continue;
  1930. }
  1931. if (cache.cells[i].is_empty()) {
  1932. // keep count of the number of used cells
  1933. if (cache.cells[i].pos >= 0) cache.used--;
  1934. cache.cells[i].pos = -1;
  1935. if (new_head == cache.size) new_head = i;
  1936. }
  1937. }
  1938. }
  1939. // If we freed up a slot, set head to it so searching can start there.
  1940. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1941. }
  1942. static void llama_kv_cache_seq_cp(
  1943. struct llama_kv_cache & cache,
  1944. llama_seq_id seq_id_src,
  1945. llama_seq_id seq_id_dst,
  1946. llama_pos p0,
  1947. llama_pos p1) {
  1948. if (p0 < 0) p0 = 0;
  1949. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1950. cache.head = 0;
  1951. for (uint32_t i = 0; i < cache.size; ++i) {
  1952. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1953. cache.cells[i].seq_id.insert(seq_id_dst);
  1954. }
  1955. }
  1956. }
  1957. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  1958. uint32_t new_head = cache.size;
  1959. for (uint32_t i = 0; i < cache.size; ++i) {
  1960. if (!cache.cells[i].has_seq_id(seq_id)) {
  1961. if (cache.cells[i].pos >= 0) cache.used--;
  1962. cache.cells[i].pos = -1;
  1963. cache.cells[i].seq_id.clear();
  1964. if (new_head == cache.size) new_head = i;
  1965. } else {
  1966. cache.cells[i].seq_id.clear();
  1967. cache.cells[i].seq_id.insert(seq_id);
  1968. }
  1969. }
  1970. // If we freed up a slot, set head to it so searching can start there.
  1971. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1972. }
  1973. static void llama_kv_cache_seq_add(
  1974. struct llama_kv_cache & cache,
  1975. llama_seq_id seq_id,
  1976. llama_pos p0,
  1977. llama_pos p1,
  1978. llama_pos delta) {
  1979. uint32_t new_head = cache.size;
  1980. if (p0 < 0) p0 = 0;
  1981. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1982. for (uint32_t i = 0; i < cache.size; ++i) {
  1983. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1984. cache.has_shift = true;
  1985. cache.cells[i].pos += delta;
  1986. cache.cells[i].delta += delta;
  1987. if (cache.cells[i].pos < 0) {
  1988. if (!cache.cells[i].is_empty()) {
  1989. cache.used--;
  1990. }
  1991. cache.cells[i].pos = -1;
  1992. cache.cells[i].seq_id.clear();
  1993. if (new_head == cache.size) {
  1994. new_head = i;
  1995. }
  1996. }
  1997. }
  1998. }
  1999. // If we freed up a slot, set head to it so searching can start there.
  2000. // Otherwise we just start the next search from the beginning.
  2001. cache.head = new_head != cache.size ? new_head : 0;
  2002. }
  2003. static void llama_kv_cache_seq_div(
  2004. struct llama_kv_cache & cache,
  2005. llama_seq_id seq_id,
  2006. llama_pos p0,
  2007. llama_pos p1,
  2008. int d) {
  2009. if (p0 < 0) p0 = 0;
  2010. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2011. for (uint32_t i = 0; i < cache.size; ++i) {
  2012. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2013. cache.has_shift = true;
  2014. {
  2015. llama_pos p_old = cache.cells[i].pos;
  2016. cache.cells[i].pos /= d;
  2017. cache.cells[i].delta += cache.cells[i].pos - p_old;
  2018. }
  2019. }
  2020. }
  2021. }
  2022. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2023. llama_pos result = 0;
  2024. for (uint32_t i = 0; i < cache.size; ++i) {
  2025. if (cache.cells[i].has_seq_id(seq_id)) {
  2026. result = std::max(result, cache.cells[i].pos);
  2027. }
  2028. }
  2029. return result;
  2030. }
  2031. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  2032. cache.do_defrag = true;
  2033. }
  2034. //
  2035. // model loading and saving
  2036. //
  2037. enum llama_fver {
  2038. GGUF_FILE_VERSION_V1 = 1,
  2039. GGUF_FILE_VERSION_V2 = 2,
  2040. GGUF_FILE_VERSION_V3 = 3,
  2041. };
  2042. static const char * llama_file_version_name(llama_fver version) {
  2043. switch (version) {
  2044. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  2045. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  2046. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  2047. }
  2048. return "unknown";
  2049. }
  2050. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  2051. char buf[256];
  2052. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  2053. for (size_t i = 1; i < ne.size(); i++) {
  2054. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  2055. }
  2056. return buf;
  2057. }
  2058. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  2059. char buf[256];
  2060. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  2061. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  2062. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  2063. }
  2064. return buf;
  2065. }
  2066. namespace GGUFMeta {
  2067. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  2068. struct GKV_Base_Type {
  2069. static constexpr gguf_type gt = gt_;
  2070. static T getter(const gguf_context * ctx, const int kid) {
  2071. return gfun(ctx, kid);
  2072. }
  2073. };
  2074. template<typename T> struct GKV_Base;
  2075. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  2076. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  2077. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  2078. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  2079. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  2080. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  2081. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  2082. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  2083. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  2084. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  2085. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  2086. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  2087. template<> struct GKV_Base<std::string> {
  2088. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  2089. static std::string getter(const gguf_context * ctx, const int kid) {
  2090. return gguf_get_val_str(ctx, kid);
  2091. }
  2092. };
  2093. struct ArrayInfo {
  2094. const gguf_type gt;
  2095. const size_t length;
  2096. const void * data;
  2097. };
  2098. template<> struct GKV_Base<ArrayInfo> {
  2099. public:
  2100. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  2101. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  2102. return ArrayInfo {
  2103. gguf_get_arr_type(ctx, k),
  2104. size_t(gguf_get_arr_n(ctx, k)),
  2105. gguf_get_arr_data(ctx, k),
  2106. };
  2107. }
  2108. };
  2109. template<typename T>
  2110. class GKV : public GKV_Base<T> {
  2111. GKV() = delete;
  2112. public:
  2113. static T get_kv(const gguf_context * ctx, const int k) {
  2114. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  2115. if (kt != GKV::gt) {
  2116. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  2117. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  2118. }
  2119. return GKV::getter(ctx, k);
  2120. }
  2121. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  2122. switch (ty) {
  2123. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  2124. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  2125. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  2126. }
  2127. return "unknown";
  2128. }
  2129. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  2130. if (!ovrd) { return false; }
  2131. if (ovrd->tag == expected_type) {
  2132. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  2133. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  2134. switch (ovrd->tag) {
  2135. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  2136. LLAMA_LOG_INFO("%s\n", ovrd->bool_value ? "true" : "false");
  2137. } break;
  2138. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  2139. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->int_value);
  2140. } break;
  2141. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  2142. LLAMA_LOG_INFO("%.6f\n", ovrd->float_value);
  2143. } break;
  2144. default:
  2145. // Shouldn't be possible to end up here, but just in case...
  2146. throw std::runtime_error(
  2147. format("Unsupported attempt to override %s type for metadata key %s\n",
  2148. override_type_to_str(ovrd->tag), ovrd->key));
  2149. }
  2150. return true;
  2151. }
  2152. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  2153. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  2154. return false;
  2155. }
  2156. template<typename OT>
  2157. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  2158. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2159. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  2160. target = ovrd->bool_value;
  2161. return true;
  2162. }
  2163. return false;
  2164. }
  2165. template<typename OT>
  2166. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  2167. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2168. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  2169. target = ovrd->int_value;
  2170. return true;
  2171. }
  2172. return false;
  2173. }
  2174. template<typename OT>
  2175. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  2176. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2177. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  2178. target = ovrd->float_value;
  2179. return true;
  2180. }
  2181. return false;
  2182. }
  2183. template<typename OT>
  2184. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  2185. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2186. (void)target;
  2187. (void)ovrd;
  2188. if (!ovrd) { return false; }
  2189. // Currently, we should never end up here so it would be a bug if we do.
  2190. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  2191. ovrd ? ovrd->key : "NULL"));
  2192. }
  2193. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2194. if (try_override<T>(target, ovrd)) {
  2195. return true;
  2196. }
  2197. if (k < 0) { return false; }
  2198. target = get_kv(ctx, k);
  2199. return true;
  2200. }
  2201. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2202. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  2203. }
  2204. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2205. return set(ctx, key.c_str(), target, ovrd);
  2206. }
  2207. };
  2208. }
  2209. struct llama_model_loader {
  2210. int n_kv = 0;
  2211. int n_tensors = 0;
  2212. int n_created = 0;
  2213. int64_t n_elements = 0;
  2214. size_t n_bytes = 0;
  2215. bool use_mmap = false;
  2216. llama_file file;
  2217. llama_ftype ftype;
  2218. llama_fver fver;
  2219. std::unique_ptr<llama_mmap> mapping;
  2220. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  2221. struct gguf_context * ctx_gguf = NULL;
  2222. struct ggml_context * ctx_meta = NULL;
  2223. std::string arch_name;
  2224. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  2225. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) : file(fname.c_str(), "rb") {
  2226. int trace = 0;
  2227. if (getenv("LLAMA_TRACE")) {
  2228. trace = atoi(getenv("LLAMA_TRACE"));
  2229. }
  2230. struct gguf_init_params params = {
  2231. /*.no_alloc = */ true,
  2232. /*.ctx = */ &ctx_meta,
  2233. };
  2234. if (param_overrides_p != nullptr) {
  2235. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  2236. kv_overrides.insert({std::string(p->key), *p});
  2237. }
  2238. }
  2239. ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  2240. if (!ctx_gguf) {
  2241. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  2242. }
  2243. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  2244. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  2245. n_kv = gguf_get_n_kv(ctx_gguf);
  2246. n_tensors = gguf_get_n_tensors(ctx_gguf);
  2247. fver = (enum llama_fver ) gguf_get_version(ctx_gguf);
  2248. for (int i = 0; i < n_tensors; i++) {
  2249. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  2250. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, name);
  2251. n_elements += ggml_nelements(t);
  2252. n_bytes += ggml_nbytes(t);
  2253. }
  2254. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  2255. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  2256. // determine file type based on the number of tensors for each quantization and print meta data
  2257. // TODO: make optional
  2258. {
  2259. std::map<enum ggml_type, uint32_t> n_type;
  2260. uint32_t n_type_max = 0;
  2261. enum ggml_type type_max = GGML_TYPE_F32;
  2262. for (int i = 0; i < n_tensors; i++) {
  2263. enum ggml_type type = gguf_get_tensor_type(ctx_gguf, i);
  2264. n_type[type]++;
  2265. if (n_type_max < n_type[type]) {
  2266. n_type_max = n_type[type];
  2267. type_max = type;
  2268. }
  2269. if (trace > 0) {
  2270. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2271. LLAMA_LOG_INFO("%s: - tensor %4d: %32s %-8s [ %s ]\n", __func__, i, ggml_get_name(meta), ggml_type_name(type), llama_format_tensor_shape(meta).c_str());
  2272. }
  2273. }
  2274. switch (type_max) {
  2275. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  2276. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  2277. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  2278. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  2279. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  2280. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  2281. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  2282. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  2283. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  2284. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  2285. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  2286. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  2287. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  2288. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  2289. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  2290. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  2291. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  2292. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  2293. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  2294. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  2295. default:
  2296. {
  2297. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  2298. ftype = LLAMA_FTYPE_ALL_F32;
  2299. } break;
  2300. }
  2301. // this is a way to mark that we have "guessed" the file type
  2302. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  2303. {
  2304. const int kid = gguf_find_key(ctx_gguf, "general.file_type");
  2305. if (kid >= 0) {
  2306. ftype = (llama_ftype) gguf_get_val_u32(ctx_gguf, kid);
  2307. }
  2308. }
  2309. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2310. for (int i = 0; i < n_kv; i++) {
  2311. const char * name = gguf_get_key(ctx_gguf, i);
  2312. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  2313. const std::string type_name =
  2314. type == GGUF_TYPE_ARRAY
  2315. ? format("%s[%s,%d]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(ctx_gguf, i)), gguf_get_arr_n(ctx_gguf, i))
  2316. : gguf_type_name(type);
  2317. std::string value = gguf_kv_to_str(ctx_gguf, i);
  2318. const size_t MAX_VALUE_LEN = 40;
  2319. if (value.size() > MAX_VALUE_LEN) {
  2320. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2321. }
  2322. replace_all(value, "\n", "\\n");
  2323. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2324. }
  2325. // print type counts
  2326. for (auto & kv : n_type) {
  2327. if (kv.second == 0) {
  2328. continue;
  2329. }
  2330. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2331. }
  2332. }
  2333. if (!llama_mmap::SUPPORTED) {
  2334. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2335. use_mmap = false;
  2336. }
  2337. this->use_mmap = use_mmap;
  2338. }
  2339. ~llama_model_loader() {
  2340. if (ctx_gguf) {
  2341. gguf_free(ctx_gguf);
  2342. }
  2343. if (ctx_meta) {
  2344. ggml_free(ctx_meta);
  2345. }
  2346. }
  2347. template<typename T>
  2348. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2349. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2350. const int kid = gguf_find_key(ctx_gguf, key.c_str());
  2351. if (kid < 0) {
  2352. if (required) {
  2353. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2354. }
  2355. return false;
  2356. }
  2357. struct GGUFMeta::ArrayInfo arr_info =
  2358. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(ctx_gguf, kid);
  2359. result = arr_info.length;
  2360. return true;
  2361. }
  2362. template<typename T>
  2363. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2364. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2365. return get_arr_n(llm_kv(kid), result, required);
  2366. }
  2367. template<typename T>
  2368. bool get_key(const std::string & key, T & result, const bool required = true) {
  2369. auto it = kv_overrides.find(key);
  2370. const struct llama_model_kv_override * override =
  2371. it != kv_overrides.end() ? &it->second : nullptr;
  2372. const bool found = GGUFMeta::GKV<T>::set(ctx_gguf, key, result, override);
  2373. if (required && !found) {
  2374. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2375. }
  2376. return found;
  2377. }
  2378. template<typename T>
  2379. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2380. return get_key(llm_kv(kid), result, required);
  2381. }
  2382. std::string get_arch_name() const {
  2383. return arch_name;
  2384. }
  2385. enum llm_arch get_arch() const {
  2386. return llm_kv.arch;
  2387. }
  2388. const char * get_tensor_name(int i) const {
  2389. return gguf_get_tensor_name(ctx_gguf, i);
  2390. }
  2391. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2392. return ggml_get_tensor(ctx_meta, name);
  2393. }
  2394. struct ggml_tensor * get_tensor_meta(int i) const {
  2395. return get_tensor_meta(get_tensor_name(i));
  2396. }
  2397. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, struct ggml_tensor * meta) {
  2398. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
  2399. ggml_set_name(tensor, ggml_get_name(meta));
  2400. n_created++;
  2401. return tensor;
  2402. }
  2403. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  2404. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, name.c_str());
  2405. if (cur == NULL) {
  2406. if (!required) {
  2407. return NULL;
  2408. }
  2409. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2410. }
  2411. {
  2412. bool is_ok = true;
  2413. for (size_t i = 0; i < ne.size(); ++i) {
  2414. if (ne[i] != cur->ne[i]) {
  2415. is_ok = false;
  2416. break;
  2417. }
  2418. }
  2419. if (!is_ok) {
  2420. throw std::runtime_error(
  2421. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2422. __func__, name.c_str(),
  2423. llama_format_tensor_shape(ne).c_str(),
  2424. llama_format_tensor_shape(cur).c_str()));
  2425. }
  2426. }
  2427. return create_tensor_for(ctx, cur);
  2428. }
  2429. void done_getting_tensors() const {
  2430. if (n_created != n_tensors) {
  2431. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  2432. }
  2433. }
  2434. size_t file_offset(const char * name) const {
  2435. const int idx = gguf_find_tensor(ctx_gguf, name);
  2436. if (idx < 0) {
  2437. throw std::runtime_error(format("%s: tensor '%s' not found in the file", __func__, name));
  2438. }
  2439. return gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, idx);
  2440. }
  2441. void init_mapping(bool prefetch = true, llama_mlock * lmlock = nullptr) {
  2442. // prefetch the whole file - all the data is needed anyway
  2443. if (use_mmap) {
  2444. mapping.reset(new llama_mmap(&file, prefetch ? -1 : 0, ggml_is_numa()));
  2445. }
  2446. // compute the total size of all tensors for progress reporting
  2447. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2448. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2449. size_data += ggml_nbytes(cur);
  2450. }
  2451. if (use_mmap && mapping) {
  2452. if (lmlock) {
  2453. lmlock->init(mapping->addr);
  2454. }
  2455. mmap_used_first = mapping->size;
  2456. }
  2457. }
  2458. void get_mapping_range(size_t * first, size_t * last, ggml_context * ctx) const {
  2459. GGML_ASSERT(mapping);
  2460. *first = mapping->size;
  2461. *last = 0;
  2462. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  2463. const size_t offs = file_offset(ggml_get_name(tensor));
  2464. *first = std::min(*first, offs);
  2465. *last = std::max(*last, offs + ggml_nbytes(tensor));
  2466. }
  2467. }
  2468. // for backwards compatibility, does not support ggml-backend
  2469. void load_data_for(struct ggml_tensor * cur) const {
  2470. const size_t offs = file_offset(ggml_get_name(cur));
  2471. if (use_mmap && mapping) {
  2472. if (cur->data == nullptr) {
  2473. cur->data = (uint8_t *)mapping->addr + offs;
  2474. } else {
  2475. memcpy(cur->data, (uint8_t *)mapping->addr + offs, ggml_nbytes(cur));
  2476. }
  2477. } else {
  2478. GGML_ASSERT(cur->data != nullptr);
  2479. file.seek(offs, SEEK_SET);
  2480. file.read_raw(cur->data, ggml_nbytes(cur));
  2481. }
  2482. }
  2483. size_t size_done = 0;
  2484. size_t size_data = 0;
  2485. size_t mmap_used_first = -1;
  2486. size_t mmap_used_last = 0;
  2487. // Returns false if cancelled by progress_callback
  2488. bool load_all_data(struct ggml_context * ctx, llama_progress_callback progress_callback, void * progress_callback_user_data, ggml_backend_buffer_t buf_mmap, llama_mlock * lmlock) {
  2489. GGML_ASSERT(size_data != 0 && "call init_mapping() first");
  2490. std::vector<no_init<uint8_t>> read_buf;
  2491. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  2492. if (progress_callback) {
  2493. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2494. return false;
  2495. }
  2496. }
  2497. const size_t offs = file_offset(ggml_get_name(cur));
  2498. if (use_mmap && mapping) {
  2499. if (buf_mmap && cur->data == nullptr) {
  2500. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + offs);
  2501. if (lmlock) {
  2502. lmlock->grow_to(offs + ggml_nbytes(cur));
  2503. }
  2504. mmap_used_first = std::min(mmap_used_first, offs);
  2505. mmap_used_last = std::max(mmap_used_last, offs + ggml_nbytes(cur));
  2506. } else {
  2507. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + offs, 0, ggml_nbytes(cur));
  2508. }
  2509. } else {
  2510. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2511. file.seek(offs, SEEK_SET);
  2512. file.read_raw(cur->data, ggml_nbytes(cur));
  2513. } else {
  2514. read_buf.resize(ggml_nbytes(cur));
  2515. file.seek(offs, SEEK_SET);
  2516. file.read_raw(read_buf.data(), ggml_nbytes(cur));
  2517. ggml_backend_tensor_set(cur, read_buf.data(), 0, ggml_nbytes(cur));
  2518. }
  2519. }
  2520. size_done += ggml_nbytes(cur);
  2521. }
  2522. // check if this is the last call and do final cleanup
  2523. if (size_done >= size_data) {
  2524. // unmap offloaded tensors and metadata
  2525. if (use_mmap && mapping) {
  2526. mapping->unmap_fragment(0, mmap_used_first);
  2527. if (mmap_used_last != 0) {
  2528. mapping->unmap_fragment(mmap_used_last, mapping->size);
  2529. }
  2530. }
  2531. if (progress_callback) {
  2532. // Even though the model is done loading, we still honor
  2533. // cancellation since we need to free allocations.
  2534. return progress_callback(1.0f, progress_callback_user_data);
  2535. }
  2536. }
  2537. return true;
  2538. }
  2539. };
  2540. template<>
  2541. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  2542. uint32_t tmp;
  2543. const bool found = get_key(kid, tmp, required);
  2544. if (found) {
  2545. result = (enum llama_pooling_type) tmp;
  2546. } else {
  2547. result = LLAMA_POOLING_TYPE_UNSPECIFIED;
  2548. }
  2549. return found;
  2550. }
  2551. //
  2552. // load LLaMA models
  2553. //
  2554. static const char * llama_model_arch_name(llm_arch arch) {
  2555. auto it = LLM_ARCH_NAMES.find(arch);
  2556. if (it == LLM_ARCH_NAMES.end()) {
  2557. return "unknown";
  2558. }
  2559. return it->second;
  2560. }
  2561. static std::string llama_model_ftype_name(llama_ftype ftype) {
  2562. if (ftype & LLAMA_FTYPE_GUESSED) {
  2563. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  2564. }
  2565. switch (ftype) {
  2566. case LLAMA_FTYPE_ALL_F32: return "all F32";
  2567. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  2568. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  2569. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  2570. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  2571. return "Q4_1, some F16";
  2572. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  2573. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  2574. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  2575. // K-quants
  2576. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  2577. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  2578. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  2579. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  2580. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  2581. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  2582. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  2583. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  2584. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  2585. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  2586. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XXS - 2.0625 bpw";
  2587. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  2588. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  2589. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  2590. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  2591. case LLAMA_FTYPE_MOSTLY_IQ3_XXS:return "IQ3_XXS - 3.0625 bpw";
  2592. case LLAMA_FTYPE_MOSTLY_IQ1_S :return "IQ1_S - 1.5625 bpw";
  2593. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  2594. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  2595. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  2596. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  2597. default: return "unknown, may not work";
  2598. }
  2599. }
  2600. static const char * llama_model_type_name(e_model type) {
  2601. switch (type) {
  2602. case MODEL_22M: return "22M";
  2603. case MODEL_33M: return "33M";
  2604. case MODEL_109M: return "109M";
  2605. case MODEL_137M: return "137M";
  2606. case MODEL_0_5B: return "0.5B";
  2607. case MODEL_1B: return "1B";
  2608. case MODEL_2B: return "2B";
  2609. case MODEL_3B: return "3B";
  2610. case MODEL_7B: return "7B";
  2611. case MODEL_8B: return "8B";
  2612. case MODEL_13B: return "13B";
  2613. case MODEL_14B: return "14B";
  2614. case MODEL_15B: return "15B";
  2615. case MODEL_20B: return "20B";
  2616. case MODEL_30B: return "30B";
  2617. case MODEL_34B: return "34B";
  2618. case MODEL_40B: return "40B";
  2619. case MODEL_65B: return "65B";
  2620. case MODEL_70B: return "70B";
  2621. case MODEL_SMALL: return "0.1B";
  2622. case MODEL_MEDIUM: return "0.4B";
  2623. case MODEL_LARGE: return "0.8B";
  2624. case MODEL_XL: return "1.5B";
  2625. default: return "?B";
  2626. }
  2627. }
  2628. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  2629. switch (type) {
  2630. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  2631. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  2632. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  2633. default: return "unknown";
  2634. }
  2635. }
  2636. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  2637. model.arch = ml.get_arch();
  2638. if (model.arch == LLM_ARCH_UNKNOWN) {
  2639. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  2640. }
  2641. }
  2642. static void llm_load_hparams(
  2643. llama_model_loader & ml,
  2644. llama_model & model) {
  2645. auto & hparams = model.hparams;
  2646. const gguf_context * ctx = ml.ctx_gguf;
  2647. // get metadata as string
  2648. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  2649. enum gguf_type type = gguf_get_kv_type(ctx, i);
  2650. if (type == GGUF_TYPE_ARRAY) {
  2651. continue;
  2652. }
  2653. const char * name = gguf_get_key(ctx, i);
  2654. const std::string value = gguf_kv_to_str(ctx, i);
  2655. model.gguf_kv.emplace(name, value);
  2656. }
  2657. // get general kv
  2658. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  2659. // get hparams kv
  2660. ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  2661. ml.get_key (LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  2662. ml.get_key (LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  2663. ml.get_key (LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  2664. ml.get_key (LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  2665. ml.get_key (LLM_KV_BLOCK_COUNT, hparams.n_layer);
  2666. ml.get_key (LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  2667. ml.get_key (LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  2668. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  2669. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  2670. if (hparams.n_expert > 0) {
  2671. GGML_ASSERT(hparams.n_expert_used > 0);
  2672. } else {
  2673. GGML_ASSERT(hparams.n_expert_used == 0);
  2674. }
  2675. // n_head_kv is optional, default to n_head
  2676. hparams.n_head_kv = hparams.n_head;
  2677. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  2678. bool rope_finetuned = false;
  2679. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  2680. hparams.rope_finetuned = rope_finetuned;
  2681. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  2682. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  2683. // rope_freq_base (optional)
  2684. hparams.rope_freq_base_train = 10000.0f;
  2685. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  2686. std::string rope_scaling("linear");
  2687. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  2688. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  2689. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  2690. // rope_freq_scale (inverse of the kv) is optional
  2691. float ropescale = 0.0f;
  2692. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  2693. // try the old key name
  2694. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  2695. }
  2696. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  2697. // sanity check for n_rot (optional)
  2698. {
  2699. hparams.n_rot = hparams.n_embd / hparams.n_head;
  2700. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  2701. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  2702. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  2703. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  2704. }
  2705. }
  2706. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  2707. // gpt-j n_rot = rotary_dim
  2708. }
  2709. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head;
  2710. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  2711. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head;
  2712. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  2713. // arch-specific KVs
  2714. switch (model.arch) {
  2715. case LLM_ARCH_LLAMA:
  2716. {
  2717. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2718. switch (hparams.n_layer) {
  2719. case 22: model.type = e_model::MODEL_1B; break;
  2720. case 26: model.type = e_model::MODEL_3B; break;
  2721. case 32: model.type = e_model::MODEL_7B; break;
  2722. case 40: model.type = e_model::MODEL_13B; break;
  2723. case 48: model.type = e_model::MODEL_34B; break;
  2724. case 60: model.type = e_model::MODEL_30B; break;
  2725. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  2726. default: model.type = e_model::MODEL_UNKNOWN;
  2727. }
  2728. } break;
  2729. case LLM_ARCH_MINICPM:
  2730. {
  2731. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2732. switch (hparams.n_layer) {
  2733. case 40: model.type = e_model::MODEL_2B; break;
  2734. default: model.type = e_model::MODEL_UNKNOWN;
  2735. }
  2736. } break;
  2737. case LLM_ARCH_FALCON:
  2738. {
  2739. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2740. switch (hparams.n_layer) {
  2741. case 32: model.type = e_model::MODEL_7B; break;
  2742. case 60: model.type = e_model::MODEL_40B; break;
  2743. default: model.type = e_model::MODEL_UNKNOWN;
  2744. }
  2745. } break;
  2746. case LLM_ARCH_BAICHUAN:
  2747. {
  2748. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2749. switch (hparams.n_layer) {
  2750. case 32: model.type = e_model::MODEL_7B; break;
  2751. case 40: model.type = e_model::MODEL_13B; break;
  2752. default: model.type = e_model::MODEL_UNKNOWN;
  2753. }
  2754. if (model.type == e_model::MODEL_13B) {
  2755. // TODO: become GGUF KV parameter
  2756. hparams.f_max_alibi_bias = 8.0f;
  2757. }
  2758. } break;
  2759. case LLM_ARCH_STARCODER:
  2760. {
  2761. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2762. switch (hparams.n_layer) {
  2763. case 24: model.type = e_model::MODEL_1B; break;
  2764. case 36: model.type = e_model::MODEL_3B; break;
  2765. case 42: model.type = e_model::MODEL_7B; break;
  2766. case 40: model.type = e_model::MODEL_15B; break;
  2767. default: model.type = e_model::MODEL_UNKNOWN;
  2768. }
  2769. } break;
  2770. case LLM_ARCH_PERSIMMON:
  2771. {
  2772. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2773. switch (hparams.n_layer) {
  2774. case 36: model.type = e_model::MODEL_8B; break;
  2775. default: model.type = e_model::MODEL_UNKNOWN;
  2776. }
  2777. } break;
  2778. case LLM_ARCH_REFACT:
  2779. {
  2780. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2781. switch (hparams.n_layer) {
  2782. case 32: model.type = e_model::MODEL_1B; break;
  2783. default: model.type = e_model::MODEL_UNKNOWN;
  2784. }
  2785. // TODO: become GGUF KV parameter
  2786. hparams.f_max_alibi_bias = 8.0f;
  2787. } break;
  2788. case LLM_ARCH_BERT:
  2789. {
  2790. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2791. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  2792. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  2793. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  2794. switch (hparams.n_layer) {
  2795. case 3:
  2796. model.type = e_model::MODEL_17M; break; // bge-micro
  2797. case 6:
  2798. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  2799. case 12:
  2800. switch (hparams.n_embd) {
  2801. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  2802. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  2803. } break;
  2804. case 24:
  2805. model.type = e_model::MODEL_335M; break; // bge-large
  2806. }
  2807. } break;
  2808. case LLM_ARCH_NOMIC_BERT:
  2809. {
  2810. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2811. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  2812. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  2813. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  2814. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  2815. model.type = e_model::MODEL_137M;
  2816. }
  2817. } break;
  2818. case LLM_ARCH_BLOOM:
  2819. {
  2820. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2821. switch (hparams.n_layer) {
  2822. case 24: model.type = e_model::MODEL_1B; break;
  2823. case 30:
  2824. switch (hparams.n_embd) {
  2825. case 2560: model.type = e_model::MODEL_3B; break;
  2826. case 4096: model.type = e_model::MODEL_7B; break;
  2827. } break;
  2828. }
  2829. // TODO: become GGUF KV parameter
  2830. hparams.f_max_alibi_bias = 8.0f;
  2831. } break;
  2832. case LLM_ARCH_MPT:
  2833. {
  2834. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2835. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  2836. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  2837. switch (hparams.n_layer) {
  2838. case 32: model.type = e_model::MODEL_7B; break;
  2839. case 48: model.type = e_model::MODEL_30B; break;
  2840. default: model.type = e_model::MODEL_UNKNOWN;
  2841. }
  2842. } break;
  2843. case LLM_ARCH_STABLELM:
  2844. {
  2845. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2846. switch (hparams.n_layer) {
  2847. case 24: model.type = e_model::MODEL_1B; break;
  2848. case 32: model.type = e_model::MODEL_3B; break;
  2849. default: model.type = e_model::MODEL_UNKNOWN;
  2850. }
  2851. } break;
  2852. case LLM_ARCH_QWEN:
  2853. {
  2854. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2855. switch (hparams.n_layer) {
  2856. case 32: model.type = e_model::MODEL_7B; break;
  2857. case 40: model.type = e_model::MODEL_13B; break;
  2858. default: model.type = e_model::MODEL_UNKNOWN;
  2859. }
  2860. } break;
  2861. case LLM_ARCH_QWEN2:
  2862. {
  2863. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2864. switch (hparams.n_layer) {
  2865. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  2866. case 32: model.type = e_model::MODEL_7B; break;
  2867. case 40: model.type = hparams.n_head == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  2868. case 80: model.type = e_model::MODEL_70B; break;
  2869. default: model.type = e_model::MODEL_UNKNOWN;
  2870. }
  2871. } break;
  2872. case LLM_ARCH_PHI2:
  2873. {
  2874. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2875. switch (hparams.n_layer) {
  2876. case 24: model.type = e_model::MODEL_1B; break;
  2877. case 32: model.type = e_model::MODEL_3B; break;
  2878. default: model.type = e_model::MODEL_UNKNOWN;
  2879. }
  2880. } break;
  2881. case LLM_ARCH_PLAMO:
  2882. {
  2883. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2884. switch (hparams.n_layer) {
  2885. case 40: model.type = e_model::MODEL_13B; break;
  2886. default: model.type = e_model::MODEL_UNKNOWN;
  2887. }
  2888. } break;
  2889. case LLM_ARCH_GPT2:
  2890. {
  2891. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2892. switch (hparams.n_layer) {
  2893. case 12: model.type = e_model::MODEL_SMALL; break;
  2894. case 24: model.type = e_model::MODEL_MEDIUM; break;
  2895. case 36: model.type = e_model::MODEL_LARGE; break;
  2896. case 48: model.type = e_model::MODEL_XL; break;
  2897. default: model.type = e_model::MODEL_UNKNOWN;
  2898. }
  2899. } break;
  2900. case LLM_ARCH_CODESHELL:
  2901. {
  2902. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2903. switch (hparams.n_layer) {
  2904. case 42: model.type = e_model::MODEL_SMALL; break;
  2905. default: model.type = e_model::MODEL_UNKNOWN;
  2906. }
  2907. } break;
  2908. case LLM_ARCH_ORION:
  2909. {
  2910. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2911. switch (hparams.n_layer) {
  2912. case 40: model.type = e_model::MODEL_14B; break;
  2913. default: model.type = e_model::MODEL_UNKNOWN;
  2914. }
  2915. } break;
  2916. case LLM_ARCH_INTERNLM2:
  2917. {
  2918. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2919. switch (hparams.n_layer) {
  2920. case 32: model.type = e_model::MODEL_7B; break;
  2921. case 48: model.type = e_model::MODEL_20B; break;
  2922. default: model.type = e_model::MODEL_UNKNOWN;
  2923. }
  2924. } break;
  2925. case LLM_ARCH_GEMMA:
  2926. {
  2927. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2928. switch (hparams.n_layer) {
  2929. case 18: model.type = e_model::MODEL_2B; break;
  2930. case 28: model.type = e_model::MODEL_7B; break;
  2931. default: model.type = e_model::MODEL_UNKNOWN;
  2932. }
  2933. } break;
  2934. case LLM_ARCH_STARCODER2:
  2935. {
  2936. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2937. switch (hparams.n_layer) {
  2938. case 30: model.type = e_model::MODEL_3B; break;
  2939. case 32: model.type = e_model::MODEL_7B; break;
  2940. case 40: model.type = e_model::MODEL_15B; break;
  2941. default: model.type = e_model::MODEL_UNKNOWN;
  2942. }
  2943. } break;
  2944. default: (void)0;
  2945. }
  2946. model.ftype = ml.ftype;
  2947. if (hparams.f_max_alibi_bias > 0.0f) {
  2948. hparams.need_kq_pos = true;
  2949. }
  2950. hparams.rope_type = llama_rope_type(&model);
  2951. }
  2952. // TODO: This should probably be in llama.h
  2953. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  2954. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  2955. static void llm_load_vocab(
  2956. llama_model_loader & ml,
  2957. llama_model & model) {
  2958. auto & vocab = model.vocab;
  2959. struct gguf_context * ctx = ml.ctx_gguf;
  2960. const auto kv = LLM_KV(model.arch);
  2961. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  2962. if (token_idx == -1) {
  2963. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  2964. }
  2965. const float * scores = nullptr;
  2966. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  2967. if (score_idx != -1) {
  2968. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  2969. }
  2970. const int * toktypes = nullptr;
  2971. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  2972. if (toktype_idx != -1) {
  2973. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  2974. }
  2975. // determine vocab type
  2976. {
  2977. std::string tokenizer_name;
  2978. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  2979. if (tokenizer_name == "llama") {
  2980. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2981. // default special tokens
  2982. vocab.special_bos_id = 1;
  2983. vocab.special_eos_id = 2;
  2984. vocab.special_unk_id = 0;
  2985. vocab.special_sep_id = -1;
  2986. vocab.special_pad_id = -1;
  2987. const int add_space_prefix_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_ADD_PREFIX).c_str());
  2988. if (add_space_prefix_keyidx != -1) {
  2989. vocab.add_space_prefix = gguf_get_val_bool(ctx, add_space_prefix_keyidx);
  2990. } // The default value of add_space_prefix is true.
  2991. } else if (tokenizer_name == "gpt2") {
  2992. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  2993. // read bpe merges and populate bpe ranks
  2994. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  2995. if (merges_keyidx == -1) {
  2996. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  2997. }
  2998. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  2999. for (int i = 0; i < n_merges; i++) {
  3000. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  3001. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  3002. std::string first;
  3003. std::string second;
  3004. const size_t pos = word.find(' ', 1);
  3005. if (pos != std::string::npos) {
  3006. first = word.substr(0, pos);
  3007. second = word.substr(pos + 1);
  3008. }
  3009. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  3010. }
  3011. // default special tokens
  3012. vocab.special_bos_id = 11;
  3013. vocab.special_eos_id = 11;
  3014. vocab.special_unk_id = -1;
  3015. vocab.special_sep_id = -1;
  3016. vocab.special_pad_id = -1;
  3017. } else if (tokenizer_name == "bert") {
  3018. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  3019. // default special tokens
  3020. vocab.special_bos_id = 101;
  3021. vocab.special_eos_id = 102;
  3022. vocab.special_unk_id = 100;
  3023. vocab.special_sep_id = -1;
  3024. vocab.special_pad_id = -1;
  3025. vocab.add_space_prefix = false;
  3026. } else {
  3027. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  3028. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  3029. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  3030. }
  3031. }
  3032. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  3033. vocab.id_to_token.resize(n_vocab);
  3034. for (uint32_t i = 0; i < n_vocab; i++) {
  3035. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  3036. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  3037. vocab.token_to_id[word] = i;
  3038. auto & token_data = vocab.id_to_token[i];
  3039. token_data.text = std::move(word);
  3040. token_data.score = scores ? scores[i] : 0.0f;
  3041. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  3042. }
  3043. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  3044. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  3045. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  3046. try {
  3047. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  3048. } catch (const std::exception & e) {
  3049. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  3050. vocab.linefeed_id = vocab.special_pad_id;
  3051. }
  3052. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  3053. vocab.linefeed_id = vocab.special_pad_id;
  3054. } else {
  3055. const std::vector<int> ids = llama_tokenize_internal(vocab, "\u010A", false);
  3056. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  3057. vocab.linefeed_id = ids[0];
  3058. }
  3059. // special tokens
  3060. {
  3061. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  3062. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  3063. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  3064. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  3065. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  3066. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  3067. };
  3068. for (const auto & it : special_token_types) {
  3069. const std::string & key = kv(std::get<0>(it));
  3070. int32_t & id = std::get<1>(it);
  3071. uint32_t new_id;
  3072. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  3073. continue;
  3074. }
  3075. if (new_id >= vocab.id_to_token.size()) {
  3076. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  3077. __func__, key.c_str(), new_id, id);
  3078. } else {
  3079. id = new_id;
  3080. }
  3081. }
  3082. // Handle add_bos_token and add_eos_token
  3083. {
  3084. bool temp = true;
  3085. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  3086. vocab.special_add_bos = int(temp);
  3087. }
  3088. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  3089. vocab.special_add_eos = int(temp);
  3090. }
  3091. }
  3092. }
  3093. // build special tokens cache
  3094. {
  3095. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  3096. // and will always be correctly labeled in 'added_tokens.json' etc.
  3097. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  3098. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  3099. // are special tokens.
  3100. // From testing, this appears to correlate 1:1 with special tokens.
  3101. //
  3102. // Counting special tokens and verifying in only one direction
  3103. // is sufficient to detect difference in those two sets.
  3104. //
  3105. uint32_t special_tokens_count_by_type = 0;
  3106. uint32_t special_tokens_count_from_verification = 0;
  3107. bool special_tokens_definition_mismatch = false;
  3108. for (const auto & t : vocab.token_to_id) {
  3109. const auto & token = t.first;
  3110. const auto & id = t.second;
  3111. // Count all non-normal tokens in the vocab while iterating
  3112. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  3113. special_tokens_count_by_type++;
  3114. }
  3115. // Skip single character tokens
  3116. if (token.length() > 1) {
  3117. bool is_tokenizable = false;
  3118. // Split token string representation in two, in all possible ways
  3119. // and check if both halves can be matched to a valid token
  3120. for (unsigned i = 1; i < token.length();) {
  3121. const auto left = token.substr(0, i);
  3122. const auto right = token.substr(i);
  3123. // check if we didnt partition in the middle of a utf sequence
  3124. auto utf = utf8_len(left.at(left.length() - 1));
  3125. if (utf == 1) {
  3126. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  3127. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  3128. is_tokenizable = true;
  3129. break;
  3130. }
  3131. i++;
  3132. } else {
  3133. // skip over the rest of multibyte utf sequence
  3134. i += utf - 1;
  3135. }
  3136. }
  3137. if (!is_tokenizable) {
  3138. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  3139. // it's faster to re-filter them here, since there are way less candidates now
  3140. // Calculate a total "utf" length of a token string representation
  3141. size_t utf8_str_len = 0;
  3142. for (unsigned i = 0; i < token.length();) {
  3143. utf8_str_len++;
  3144. i += utf8_len(token.at(i));
  3145. }
  3146. // And skip the ones which are one character
  3147. if (utf8_str_len > 1) {
  3148. // At this point what we have left are special tokens only
  3149. vocab.special_tokens_cache[token] = id;
  3150. // Count manually found special tokens
  3151. special_tokens_count_from_verification++;
  3152. // If this manually found special token is not marked as such, flag a mismatch
  3153. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  3154. special_tokens_definition_mismatch = true;
  3155. }
  3156. }
  3157. }
  3158. }
  3159. }
  3160. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  3161. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  3162. __func__,
  3163. special_tokens_count_from_verification, vocab.id_to_token.size(),
  3164. special_tokens_count_by_type, vocab.id_to_token.size()
  3165. );
  3166. } else {
  3167. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  3168. __func__,
  3169. special_tokens_count_from_verification, vocab.id_to_token.size()
  3170. );
  3171. }
  3172. }
  3173. }
  3174. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  3175. const auto & hparams = model.hparams;
  3176. const auto & vocab = model.vocab;
  3177. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  3178. // hparams
  3179. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  3180. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  3181. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  3182. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  3183. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  3184. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  3185. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  3186. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  3187. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  3188. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  3189. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  3190. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  3191. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  3192. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  3193. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  3194. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  3195. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  3196. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  3197. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  3198. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  3199. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  3200. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  3201. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  3202. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  3203. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  3204. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  3205. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  3206. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  3207. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  3208. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  3209. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  3210. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  3211. if (ml.n_elements >= 1e12) {
  3212. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  3213. } else if (ml.n_elements >= 1e9) {
  3214. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  3215. } else if (ml.n_elements >= 1e6) {
  3216. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  3217. } else {
  3218. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  3219. }
  3220. if (ml.n_bytes < GiB) {
  3221. 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);
  3222. } else {
  3223. 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);
  3224. }
  3225. // general kv
  3226. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  3227. // special tokens
  3228. 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() ); }
  3229. 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() ); }
  3230. 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() ); }
  3231. 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() ); }
  3232. 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() ); }
  3233. 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() ); }
  3234. }
  3235. // Returns false if cancelled by progress_callback
  3236. static bool llm_load_tensors(
  3237. llama_model_loader & ml,
  3238. llama_model & model,
  3239. int n_gpu_layers,
  3240. enum llama_split_mode split_mode,
  3241. int main_gpu,
  3242. const float * tensor_split,
  3243. bool use_mlock,
  3244. llama_progress_callback progress_callback,
  3245. void * progress_callback_user_data) {
  3246. model.t_start_us = ggml_time_us();
  3247. auto & hparams = model.hparams;
  3248. model.split_mode = split_mode;
  3249. model.main_gpu = main_gpu;
  3250. model.n_gpu_layers = n_gpu_layers;
  3251. const int64_t n_layer = hparams.n_layer;
  3252. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  3253. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  3254. model.buft_input = llama_default_buffer_type_cpu(true);
  3255. model.buft_layer.resize(n_layer);
  3256. // assign cpu layers
  3257. for (int64_t i = 0; i < i_gpu_start; ++i) {
  3258. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  3259. }
  3260. if (split_mode == LLAMA_SPLIT_MODE_LAYER) {
  3261. // calculate the split points
  3262. int device_count = llama_get_device_count();
  3263. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  3264. std::vector<float> splits(device_count);
  3265. if (all_zero) {
  3266. // default split, by free memory
  3267. for (int i = 0; i < device_count; ++i) {
  3268. splits[i] = llama_get_device_memory(i);
  3269. }
  3270. } else {
  3271. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  3272. }
  3273. // sum and normalize the splits to get the split points
  3274. float split_sum = 0.0f;
  3275. for (int i = 0; i < device_count; ++i) {
  3276. split_sum += splits[i];
  3277. splits[i] = split_sum;
  3278. }
  3279. for (int i = 0; i < device_count; ++i) {
  3280. splits[i] /= split_sum;
  3281. }
  3282. // assign the repeating layers to the devices according to the splits
  3283. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  3284. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3285. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  3286. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  3287. }
  3288. // assign the output layer
  3289. if (n_gpu_layers > n_layer) {
  3290. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  3291. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  3292. } else {
  3293. model.buft_output = llama_default_buffer_type_cpu(true);
  3294. }
  3295. } else {
  3296. ggml_backend_buffer_type_t split_buft;
  3297. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  3298. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  3299. } else {
  3300. // LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_LAYER in backends where it is not supported
  3301. split_buft = llama_default_buffer_type_offload(main_gpu);
  3302. }
  3303. // assign the repeating layers
  3304. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3305. model.buft_layer[i] = {
  3306. split_buft,
  3307. llama_default_buffer_type_offload(main_gpu)
  3308. };
  3309. }
  3310. // assign the output layer
  3311. if (n_gpu_layers > n_layer) {
  3312. model.buft_output = {
  3313. split_buft,
  3314. llama_default_buffer_type_offload(main_gpu)
  3315. };
  3316. } else {
  3317. model.buft_output = llama_default_buffer_type_cpu(true);
  3318. }
  3319. }
  3320. // count used buffer types
  3321. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  3322. buft_layer_count[model.buft_input.buft]++;
  3323. buft_layer_count[model.buft_input.buft_matrix]++;
  3324. buft_layer_count[model.buft_output.buft]++;
  3325. buft_layer_count[model.buft_output.buft_matrix]++;
  3326. for (int64_t i = 0; i < n_layer; ++i) {
  3327. buft_layer_count[model.buft_layer[i].buft]++;
  3328. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  3329. }
  3330. // create one context per buffer type
  3331. size_t ctx_size = ggml_tensor_overhead()*(ml.n_tensors + 1); // +1 for models where tok_embd is duplicated as output
  3332. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3333. for (auto & it : buft_layer_count) {
  3334. struct ggml_init_params params = {
  3335. /*.mem_size =*/ ctx_size,
  3336. /*.mem_buffer =*/ NULL,
  3337. /*.no_alloc =*/ true,
  3338. };
  3339. ggml_context * ctx = ggml_init(params);
  3340. if (!ctx) {
  3341. throw std::runtime_error(format("failed to create context"));
  3342. }
  3343. ctx_map[it.first] = ctx;
  3344. model.ctxs.push_back(ctx);
  3345. }
  3346. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  3347. // create tensors for the weights
  3348. {
  3349. const int64_t n_embd = hparams.n_embd;
  3350. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3351. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3352. const int64_t n_embd_gqa = n_embd_v_gqa;
  3353. const int64_t n_vocab = hparams.n_vocab;
  3354. const int64_t n_vocab_type = hparams.n_vocab_type;
  3355. const int64_t n_ff = hparams.n_ff;
  3356. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  3357. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  3358. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  3359. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  3360. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  3361. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  3362. model.layers.resize(n_layer);
  3363. const auto tn = LLM_TN(model.arch);
  3364. switch (model.arch) {
  3365. case LLM_ARCH_LLAMA:
  3366. case LLM_ARCH_REFACT:
  3367. case LLM_ARCH_MINICPM:
  3368. {
  3369. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3370. // output
  3371. {
  3372. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3373. if (model.arch != LLM_ARCH_MINICPM){
  3374. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  3375. // if output is NULL, init from the input tok embed
  3376. if (model.output == NULL) {
  3377. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3378. ml.n_created--; // artificial tensor
  3379. ml.size_data += ggml_nbytes(model.output);
  3380. }
  3381. }
  3382. }
  3383. for (int i = 0; i < n_layer; ++i) {
  3384. ggml_context * ctx_layer = ctx_for_layer(i);
  3385. ggml_context * ctx_split = ctx_for_layer_split(i);
  3386. auto & layer = model.layers[i];
  3387. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3388. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3389. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3390. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3391. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3392. // optional bias tensors
  3393. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3394. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3395. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3396. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3397. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3398. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd}, false);
  3399. if (layer.ffn_gate_inp == nullptr) {
  3400. GGML_ASSERT(hparams.n_expert == 0);
  3401. GGML_ASSERT(hparams.n_expert_used == 0);
  3402. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3403. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3404. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3405. } else {
  3406. GGML_ASSERT(hparams.n_expert > 0);
  3407. GGML_ASSERT(hparams.n_expert_used > 0);
  3408. // MoE branch
  3409. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  3410. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  3411. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  3412. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  3413. }
  3414. }
  3415. }
  3416. } break;
  3417. case LLM_ARCH_BAICHUAN:
  3418. {
  3419. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3420. {
  3421. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3422. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3423. }
  3424. for (int i = 0; i < n_layer; ++i) {
  3425. ggml_context * ctx_layer = ctx_for_layer(i);
  3426. ggml_context * ctx_split = ctx_for_layer_split(i);
  3427. auto & layer = model.layers[i];
  3428. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3429. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3430. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3431. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3432. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3433. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3434. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3435. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3436. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3437. }
  3438. } break;
  3439. case LLM_ARCH_FALCON:
  3440. {
  3441. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3442. // output
  3443. {
  3444. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3445. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3446. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_OUTPUT, "weight").c_str()) >= 0) {
  3447. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3448. } else {
  3449. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  3450. ml.n_created--; // artificial tensor
  3451. ml.size_data += ggml_nbytes(model.output);
  3452. }
  3453. }
  3454. for (int i = 0; i < n_layer; ++i) {
  3455. ggml_context * ctx_layer = ctx_for_layer(i);
  3456. ggml_context * ctx_split = ctx_for_layer_split(i);
  3457. auto & layer = model.layers[i];
  3458. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3459. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3460. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i).c_str()) >= 0) {
  3461. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd});
  3462. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd});
  3463. }
  3464. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3465. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3466. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3467. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3468. }
  3469. } break;
  3470. case LLM_ARCH_STARCODER:
  3471. {
  3472. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3473. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3474. // output
  3475. {
  3476. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3477. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3478. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3479. }
  3480. for (int i = 0; i < n_layer; ++i) {
  3481. ggml_context * ctx_layer = ctx_for_layer(i);
  3482. ggml_context * ctx_split = ctx_for_layer_split(i);
  3483. auto & layer = model.layers[i];
  3484. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3485. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3486. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3487. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3488. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3489. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3490. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3491. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3492. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3493. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3494. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3495. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3496. }
  3497. } break;
  3498. case LLM_ARCH_PERSIMMON:
  3499. {
  3500. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3501. {
  3502. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3503. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3504. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3505. }
  3506. for (int i = 0; i < n_layer; ++i) {
  3507. ggml_context * ctx_layer = ctx_for_layer(i);
  3508. ggml_context * ctx_split = ctx_for_layer_split(i);
  3509. auto & layer = model.layers[i];
  3510. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3511. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3512. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3513. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3514. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3515. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3516. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3517. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3518. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3519. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3520. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3521. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3522. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  3523. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  3524. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  3525. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  3526. }
  3527. } break;
  3528. case LLM_ARCH_BERT:
  3529. case LLM_ARCH_NOMIC_BERT:
  3530. {
  3531. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3532. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  3533. if (model.arch == LLM_ARCH_BERT) {
  3534. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3535. }
  3536. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3537. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3538. for (int i = 0; i < n_layer; ++i) {
  3539. ggml_context * ctx_layer = ctx_for_layer(i);
  3540. ggml_context * ctx_split = ctx_for_layer_split(i);
  3541. auto & layer = model.layers[i];
  3542. if (model.arch == LLM_ARCH_BERT) {
  3543. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3544. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3545. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3546. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3547. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3548. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3549. } else {
  3550. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3551. }
  3552. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3553. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  3554. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  3555. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3556. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3557. if (model.arch == LLM_ARCH_BERT) {
  3558. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3559. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3560. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3561. } else {
  3562. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3563. }
  3564. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  3565. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  3566. }
  3567. } break;
  3568. case LLM_ARCH_BLOOM:
  3569. {
  3570. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3571. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3572. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3573. // output
  3574. {
  3575. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3576. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3577. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3578. }
  3579. for (int i = 0; i < n_layer; ++i) {
  3580. ggml_context * ctx_layer = ctx_for_layer(i);
  3581. ggml_context * ctx_split = ctx_for_layer_split(i);
  3582. auto & layer = model.layers[i];
  3583. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3584. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3585. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3586. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3587. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3588. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3589. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3590. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3591. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3592. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3593. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3594. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3595. }
  3596. } break;
  3597. case LLM_ARCH_MPT:
  3598. {
  3599. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3600. // output
  3601. {
  3602. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3603. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, false);
  3604. // same as tok_embd, duplicated to allow offloading
  3605. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3606. ml.n_created--; // artificial tensor
  3607. ml.size_data += ggml_nbytes(model.output);
  3608. }
  3609. for (int i = 0; i < n_layer; ++i) {
  3610. ggml_context * ctx_layer = ctx_for_layer(i);
  3611. ggml_context * ctx_split = ctx_for_layer_split(i);
  3612. auto & layer = model.layers[i];
  3613. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3614. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, false);
  3615. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3616. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3617. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3618. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3619. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3620. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, false);
  3621. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3622. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, false);
  3623. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3624. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, false);
  3625. // AWQ ScaleActivation layer
  3626. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  3627. }
  3628. } break;
  3629. case LLM_ARCH_STABLELM:
  3630. {
  3631. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3632. // output
  3633. {
  3634. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3635. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3636. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3637. }
  3638. for (int i = 0; i < n_layer; ++i) {
  3639. ggml_context * ctx_layer = ctx_for_layer(i);
  3640. ggml_context * ctx_split = ctx_for_layer_split(i);
  3641. auto & layer = model.layers[i];
  3642. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3643. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3644. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3645. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3646. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3647. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3648. // optional bias tensors, present in Stable LM 2 1.6B
  3649. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3650. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3651. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3652. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3653. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3654. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3655. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3656. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3657. }
  3658. } break;
  3659. case LLM_ARCH_QWEN:
  3660. {
  3661. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3662. // output
  3663. {
  3664. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3665. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3666. }
  3667. for (int i = 0; i < n_layer; ++i) {
  3668. ggml_context * ctx_layer = ctx_for_layer(i);
  3669. ggml_context * ctx_split = ctx_for_layer_split(i);
  3670. auto & layer = model.layers[i];
  3671. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3672. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  3673. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  3674. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3675. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3676. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  3677. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  3678. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  3679. }
  3680. } break;
  3681. case LLM_ARCH_QWEN2:
  3682. {
  3683. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3684. // output
  3685. {
  3686. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3687. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3688. }
  3689. for (int i = 0; i < n_layer; ++i) {
  3690. ggml_context * ctx_layer = ctx_for_layer(i);
  3691. ggml_context * ctx_split = ctx_for_layer_split(i);
  3692. auto & layer = model.layers[i];
  3693. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3694. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3695. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3696. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3697. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3698. // optional bias tensors
  3699. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3700. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3701. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3702. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3703. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3704. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3705. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3706. }
  3707. } break;
  3708. case LLM_ARCH_PHI2:
  3709. {
  3710. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3711. // output
  3712. {
  3713. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3714. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3715. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3716. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  3717. }
  3718. for (int i = 0; i < n_layer; ++i) {
  3719. ggml_context * ctx_layer = ctx_for_layer(i);
  3720. ggml_context * ctx_split = ctx_for_layer_split(i);
  3721. auto & layer = model.layers[i];
  3722. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3723. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3724. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  3725. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3726. if (layer.wqkv == nullptr) {
  3727. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3728. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3729. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3730. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3731. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3732. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3733. }
  3734. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3735. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3736. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3737. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3738. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3739. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3740. }
  3741. } break;
  3742. case LLM_ARCH_PLAMO:
  3743. {
  3744. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3745. // output
  3746. {
  3747. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3748. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3749. }
  3750. for (int i = 0; i < n_layer; ++i) {
  3751. ggml_context * ctx_layer = ctx_for_layer(i);
  3752. ggml_context * ctx_split = ctx_for_layer_split(i);
  3753. auto & layer = model.layers[i];
  3754. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3755. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3756. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3757. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3758. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3759. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3760. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3761. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3762. }
  3763. } break;
  3764. case LLM_ARCH_GPT2:
  3765. {
  3766. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3767. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3768. // output
  3769. {
  3770. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3771. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3772. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3773. }
  3774. for (int i = 0; i < n_layer; ++i) {
  3775. ggml_context * ctx_layer = ctx_for_layer(i);
  3776. ggml_context * ctx_split = ctx_for_layer_split(i);
  3777. auto & layer = model.layers[i];
  3778. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3779. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3780. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3781. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3782. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3783. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3784. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3785. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3786. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3787. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3788. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3789. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3790. }
  3791. } break;
  3792. case LLM_ARCH_CODESHELL:
  3793. {
  3794. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3795. // output
  3796. {
  3797. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3798. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3799. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3800. }
  3801. for (int i = 0; i < n_layer; ++i) {
  3802. ggml_context * ctx_layer = ctx_for_layer(i);
  3803. ggml_context * ctx_split = ctx_for_layer_split(i);
  3804. auto & layer = model.layers[i];
  3805. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3806. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3807. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3808. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3809. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3810. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3811. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3812. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3813. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3814. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3815. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3816. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3817. }
  3818. } break;
  3819. case LLM_ARCH_ORION:
  3820. {
  3821. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3822. {
  3823. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3824. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {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.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3833. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3834. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3835. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3836. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3837. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3838. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3839. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3840. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3841. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3842. }
  3843. } break;
  3844. case LLM_ARCH_INTERNLM2:
  3845. {
  3846. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3847. // output
  3848. {
  3849. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3850. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3851. }
  3852. for (int i = 0; i < n_layer; ++i) {
  3853. ggml_context * ctx_layer = ctx_for_layer(i);
  3854. ggml_context * ctx_split = ctx_for_layer_split(i);
  3855. auto & layer = model.layers[i];
  3856. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3857. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3858. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3859. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3860. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3861. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3862. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3863. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3864. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3865. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3866. }
  3867. } break;
  3868. case LLM_ARCH_GEMMA:
  3869. {
  3870. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3871. // output
  3872. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3873. 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
  3874. ml.n_created--; // artificial tensor
  3875. ml.size_data += ggml_nbytes(model.output);
  3876. const int64_t n_ff = hparams.n_ff;
  3877. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3878. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3879. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3880. for (uint32_t 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.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * hparams.n_head});
  3886. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  3887. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  3888. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * hparams.n_head, n_embd});
  3889. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3890. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3891. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3892. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3893. }
  3894. } break;
  3895. case LLM_ARCH_STARCODER2:
  3896. {
  3897. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3898. // output
  3899. {
  3900. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3901. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3902. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  3903. // if output is NULL, init from the input tok embed
  3904. if (model.output == NULL) {
  3905. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3906. ml.n_created--; // artificial tensor
  3907. ml.size_data += ggml_nbytes(model.output);
  3908. }
  3909. }
  3910. for (int i = 0; i < n_layer; ++i) {
  3911. ggml_context * ctx_layer = ctx_for_layer(i);
  3912. ggml_context * ctx_split = ctx_for_layer_split(i);
  3913. auto & layer = model.layers[i];
  3914. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3915. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3916. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3917. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3918. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3919. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3920. // optional bias tensors
  3921. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3922. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3923. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3924. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3925. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3926. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3927. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3928. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3929. // optional bias tensors
  3930. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3931. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP , "bias", i), { n_ff});
  3932. }
  3933. } break;
  3934. default:
  3935. throw std::runtime_error("unknown architecture");
  3936. }
  3937. }
  3938. ml.done_getting_tensors();
  3939. ml.init_mapping(true, use_mlock ? &model.mlock_mmap : nullptr);
  3940. // create the backend buffers
  3941. std::vector<std::pair<ggml_context *, ggml_backend_buffer_t>> ctx_bufs;
  3942. for (auto & it : ctx_map) {
  3943. ggml_backend_buffer_type_t buft = it.first;
  3944. ggml_context * ctx = it.second;
  3945. ggml_backend_buffer_t buf = nullptr;
  3946. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  3947. // 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
  3948. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  3949. if (ml.use_mmap && buft == llama_default_buffer_type_cpu(true)) {
  3950. size_t first, last;
  3951. ml.get_mapping_range(&first, &last, ctx);
  3952. buf = ggml_backend_cpu_buffer_from_ptr((char *) ml.mapping->addr + first, last - first);
  3953. }
  3954. #ifdef GGML_USE_METAL
  3955. else if (ml.use_mmap && buft == ggml_backend_metal_buffer_type()) {
  3956. const size_t max_size = ggml_get_max_tensor_size(ctx);
  3957. size_t first, last;
  3958. ml.get_mapping_range(&first, &last, ctx);
  3959. buf = ggml_backend_metal_buffer_from_ptr((char *) ml.mapping->addr + first, last - first, max_size);
  3960. }
  3961. #endif
  3962. else {
  3963. buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  3964. if (buf != nullptr && use_mlock && ggml_backend_buffer_is_host(buf)) {
  3965. model.mlock_bufs.emplace_back(new llama_mlock);
  3966. auto & mlock_buf = model.mlock_bufs.back();
  3967. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  3968. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  3969. }
  3970. }
  3971. if (buf == nullptr) {
  3972. throw std::runtime_error("failed to allocate buffer");
  3973. }
  3974. // indicate that this buffer contains weights
  3975. // 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
  3976. ggml_backend_buffer_set_usage(buf, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  3977. model.bufs.push_back(buf);
  3978. ctx_bufs.emplace_back(ctx, buf);
  3979. }
  3980. if (llama_supports_gpu_offload()) {
  3981. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  3982. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  3983. if (n_gpu_layers > (int) hparams.n_layer) {
  3984. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  3985. }
  3986. const int max_backend_supported_layers = hparams.n_layer + 1;
  3987. const int max_offloadable_layers = hparams.n_layer + 1;
  3988. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  3989. }
  3990. // print memory requirements
  3991. for (ggml_backend_buffer_t buf : model.bufs) {
  3992. 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);
  3993. }
  3994. // populate tensors_by_name
  3995. for (ggml_context * ctx : model.ctxs) {
  3996. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  3997. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  3998. }
  3999. }
  4000. // load tensor data
  4001. for (auto & it : ctx_bufs) {
  4002. ggml_context * ctx = it.first;
  4003. ggml_backend_buffer_t buf = it.second;
  4004. if (!ml.load_all_data(ctx, progress_callback, progress_callback_user_data, buf, use_mlock ? &model.mlock_mmap : NULL)) {
  4005. return false;
  4006. }
  4007. }
  4008. model.mapping = std::move(ml.mapping);
  4009. // loading time will be recalculate after the first eval, so
  4010. // we take page faults deferred by mmap() into consideration
  4011. model.t_load_us = ggml_time_us() - model.t_start_us;
  4012. return true;
  4013. }
  4014. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  4015. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  4016. try {
  4017. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  4018. model.hparams.vocab_only = params.vocab_only;
  4019. try {
  4020. llm_load_arch(ml, model);
  4021. } catch(const std::exception & e) {
  4022. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  4023. }
  4024. try {
  4025. llm_load_hparams(ml, model);
  4026. } catch(const std::exception & e) {
  4027. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  4028. }
  4029. try {
  4030. llm_load_vocab(ml, model);
  4031. } catch(const std::exception & e) {
  4032. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  4033. }
  4034. llm_load_print_meta(ml, model);
  4035. if (model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  4036. throw std::runtime_error("vocab size mismatch");
  4037. }
  4038. if (params.vocab_only) {
  4039. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  4040. return 0;
  4041. }
  4042. #ifdef GGML_USE_KOMPUTE
  4043. if (params.n_gpu_layers > 0 && (
  4044. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  4045. || !(
  4046. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  4047. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  4048. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  4049. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  4050. )
  4051. )) {
  4052. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  4053. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  4054. params.n_gpu_layers = 0;
  4055. }
  4056. #endif
  4057. if (!llm_load_tensors(
  4058. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  4059. params.progress_callback, params.progress_callback_user_data
  4060. )) {
  4061. return -2;
  4062. }
  4063. } catch (const std::exception & err) {
  4064. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  4065. return -1;
  4066. }
  4067. return 0;
  4068. }
  4069. //
  4070. // llm_build
  4071. //
  4072. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  4073. enum llm_ffn_op_type {
  4074. LLM_FFN_SILU,
  4075. LLM_FFN_GELU,
  4076. LLM_FFN_RELU,
  4077. LLM_FFN_RELU_SQR,
  4078. };
  4079. enum llm_ffn_gate_type {
  4080. LLM_FFN_SEQ,
  4081. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  4082. };
  4083. enum llm_norm_type {
  4084. LLM_NORM,
  4085. LLM_NORM_RMS,
  4086. };
  4087. static struct ggml_tensor * llm_build_inp_embd(
  4088. struct ggml_context * ctx,
  4089. const llama_hparams & hparams,
  4090. const llama_batch & batch,
  4091. struct ggml_tensor * tok_embd,
  4092. struct ggml_tensor * inp_tokens,
  4093. struct ggml_tensor * inp_embd,
  4094. const llm_build_cb & cb) {
  4095. const int64_t n_embd = hparams.n_embd;
  4096. struct ggml_tensor * inpL;
  4097. if (batch.token) {
  4098. struct ggml_tensor * inp_tokens_v = ggml_view_1d(ctx, inp_tokens, batch.n_tokens, 0);
  4099. cb(inp_tokens, "inp_tokens", -1);
  4100. inpL = ggml_get_rows(ctx, tok_embd, inp_tokens_v);
  4101. } else {
  4102. #ifdef GGML_USE_MPI
  4103. GGML_ASSERT(false && "not implemented");
  4104. #endif
  4105. inpL = ggml_view_2d(ctx, inp_embd, n_embd, batch.n_tokens, inp_embd->nb[1], 0);
  4106. }
  4107. return inpL;
  4108. }
  4109. static void llm_build_kv_store(
  4110. struct ggml_context * ctx,
  4111. const llama_hparams & hparams,
  4112. const llama_kv_cache & kv,
  4113. struct ggml_cgraph * graph,
  4114. struct ggml_tensor * k_cur,
  4115. struct ggml_tensor * v_cur,
  4116. int64_t n_ctx,
  4117. int32_t n_tokens,
  4118. int32_t kv_head,
  4119. const llm_build_cb & cb,
  4120. int64_t il) {
  4121. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4122. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4123. // compute the transposed [n_tokens, n_embd] V matrix
  4124. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, ggml_reshape_2d(ctx, v_cur, n_embd_v_gqa, n_tokens));
  4125. //struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur); // TODO: reshape above is likely not needed
  4126. cb(v_cur_t, "v_cur_t", il);
  4127. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  4128. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  4129. cb(k_cache_view, "k_cache_view", il);
  4130. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  4131. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  4132. (kv_head)*ggml_element_size(kv.v_l[il]));
  4133. cb(v_cache_view, "v_cache_view", il);
  4134. // important: storing RoPE-ed version of K in the KV cache!
  4135. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  4136. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  4137. }
  4138. static struct ggml_tensor * llm_build_norm(
  4139. struct ggml_context * ctx,
  4140. struct ggml_tensor * cur,
  4141. const llama_hparams & hparams,
  4142. struct ggml_tensor * mw,
  4143. struct ggml_tensor * mb,
  4144. llm_norm_type type,
  4145. const llm_build_cb & cb,
  4146. int il) {
  4147. switch (type) {
  4148. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  4149. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  4150. }
  4151. if (mw || mb) {
  4152. cb(cur, "norm", il);
  4153. }
  4154. if (mw) {
  4155. cur = ggml_mul(ctx, cur, mw);
  4156. if (mb) {
  4157. cb(cur, "norm_w", il);
  4158. }
  4159. }
  4160. if (mb) {
  4161. cur = ggml_add(ctx, cur, mb);
  4162. }
  4163. return cur;
  4164. }
  4165. static struct ggml_tensor * llm_build_ffn(
  4166. struct ggml_context * ctx,
  4167. struct ggml_tensor * cur,
  4168. struct ggml_tensor * up,
  4169. struct ggml_tensor * up_b,
  4170. struct ggml_tensor * gate,
  4171. struct ggml_tensor * gate_b,
  4172. struct ggml_tensor * down,
  4173. struct ggml_tensor * down_b,
  4174. struct ggml_tensor * act_scales,
  4175. llm_ffn_op_type type_op,
  4176. llm_ffn_gate_type type_gate,
  4177. const llm_build_cb & cb,
  4178. int il) {
  4179. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  4180. cb(tmp, "ffn_up", il);
  4181. if (up_b) {
  4182. tmp = ggml_add(ctx, tmp, up_b);
  4183. cb(tmp, "ffn_up_b", il);
  4184. }
  4185. if (gate) {
  4186. switch (type_gate) {
  4187. case LLM_FFN_SEQ:
  4188. {
  4189. cur = ggml_mul_mat(ctx, gate, tmp);
  4190. cb(cur, "ffn_gate", il);
  4191. } break;
  4192. case LLM_FFN_PAR:
  4193. {
  4194. cur = ggml_mul_mat(ctx, gate, cur);
  4195. cb(cur, "ffn_gate", il);
  4196. } break;
  4197. }
  4198. if (gate_b) {
  4199. cur = ggml_add(ctx, cur, gate_b);
  4200. cb(cur, "ffn_gate_b", il);
  4201. }
  4202. } else {
  4203. cur = tmp;
  4204. }
  4205. switch (type_op) {
  4206. case LLM_FFN_SILU:
  4207. {
  4208. cur = ggml_silu(ctx, cur);
  4209. cb(cur, "ffn_silu", il);
  4210. } break;
  4211. case LLM_FFN_GELU:
  4212. {
  4213. cur = ggml_gelu(ctx, cur);
  4214. cb(cur, "ffn_gelu", il);
  4215. if (act_scales != NULL) {
  4216. cur = ggml_div(ctx, cur, act_scales);
  4217. cb(cur, "ffn_act", il);
  4218. }
  4219. } break;
  4220. case LLM_FFN_RELU:
  4221. {
  4222. cur = ggml_relu(ctx, cur);
  4223. cb(cur, "ffn_relu", il);
  4224. } break;
  4225. case LLM_FFN_RELU_SQR:
  4226. {
  4227. cur = ggml_relu(ctx, cur);
  4228. cb(cur, "ffn_relu", il);
  4229. cur = ggml_sqr(ctx, cur);
  4230. cb(cur, "ffn_sqr(relu)", il);
  4231. } break;
  4232. }
  4233. if (type_gate == LLM_FFN_PAR) {
  4234. cur = ggml_mul(ctx, cur, tmp);
  4235. cb(cur, "ffn_gate_par", il);
  4236. }
  4237. cur = ggml_mul_mat(ctx, down, cur);
  4238. if (down_b) {
  4239. cb(cur, "ffn_down", il);
  4240. }
  4241. if (down_b) {
  4242. cur = ggml_add(ctx, cur, down_b);
  4243. }
  4244. return cur;
  4245. }
  4246. // if max_alibi_bias > 0 then apply ALiBi
  4247. static struct ggml_tensor * llm_build_kqv(
  4248. struct ggml_context * ctx,
  4249. const llama_model & model,
  4250. const llama_hparams & hparams,
  4251. const llama_kv_cache & kv,
  4252. struct ggml_cgraph * graph,
  4253. struct ggml_tensor * wo,
  4254. struct ggml_tensor * wo_b,
  4255. struct ggml_tensor * q_cur,
  4256. struct ggml_tensor * kq_mask,
  4257. struct ggml_tensor * kq_pos,
  4258. int64_t n_ctx,
  4259. int32_t n_tokens,
  4260. int32_t n_kv,
  4261. float kq_scale,
  4262. const llm_build_cb & cb,
  4263. int il) {
  4264. const int64_t n_head = hparams.n_head;
  4265. const int64_t n_head_kv = hparams.n_head_kv;
  4266. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  4267. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4268. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  4269. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  4270. cb(q, "q", il);
  4271. struct ggml_tensor * k =
  4272. ggml_view_3d(ctx, kv.k_l[il],
  4273. n_embd_head_k, n_kv, n_head_kv,
  4274. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  4275. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  4276. 0);
  4277. cb(k, "k", il);
  4278. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  4279. cb(kq, "kq", il);
  4280. if (model.arch == LLM_ARCH_PHI2) {
  4281. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  4282. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  4283. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  4284. }
  4285. #if defined(GGML_USE_KOMPUTE)
  4286. #pragma message("TODO: ALiBi support in ggml_soft_max_ext is not implemented for Kompute")
  4287. #pragma message(" Falling back to ggml_alibi(). Will become an error in Mar 2024")
  4288. #pragma message("ref: https://github.com/ggerganov/llama.cpp/pull/5488")
  4289. if (hparams.f_max_alibi_bias > 0.0f) {
  4290. kq = ggml_scale(ctx, kq, kq_scale);
  4291. cb(kq, "kq_scaled", il);
  4292. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, hparams.f_max_alibi_bias);
  4293. cb(kq, "kq_scaled_alibi", il);
  4294. kq = ggml_add(ctx, kq, kq_mask);
  4295. cb(kq, "kq_masked", il);
  4296. kq = ggml_soft_max(ctx, kq);
  4297. cb(kq, "kq_soft_max", il);
  4298. } else
  4299. #endif
  4300. {
  4301. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_pos, kq_scale, hparams.f_max_alibi_bias);
  4302. cb(kq, "kq_soft_max_ext", il);
  4303. }
  4304. // split cached v into n_head heads
  4305. struct ggml_tensor * v =
  4306. ggml_view_3d(ctx, kv.v_l[il],
  4307. n_kv, n_embd_head_v, n_head_kv,
  4308. ggml_element_size(kv.v_l[il])*n_ctx,
  4309. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  4310. 0);
  4311. cb(v, "v", il);
  4312. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  4313. cb(kqv, "kqv", il);
  4314. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  4315. cb(kqv_merged, "kqv_merged", il);
  4316. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  4317. cb(cur, "kqv_merged_cont", il);
  4318. ggml_build_forward_expand(graph, cur);
  4319. cur = ggml_mul_mat(ctx, wo, cur);
  4320. if (wo_b) {
  4321. cb(cur, "kqv_wo", il);
  4322. }
  4323. if (wo_b) {
  4324. cur = ggml_add(ctx, cur, wo_b);
  4325. }
  4326. return cur;
  4327. }
  4328. static struct ggml_tensor * llm_build_kv(
  4329. struct ggml_context * ctx,
  4330. const llama_model & model,
  4331. const llama_hparams & hparams,
  4332. const llama_kv_cache & kv,
  4333. struct ggml_cgraph * graph,
  4334. struct ggml_tensor * wo,
  4335. struct ggml_tensor * wo_b,
  4336. struct ggml_tensor * k_cur,
  4337. struct ggml_tensor * v_cur,
  4338. struct ggml_tensor * q_cur,
  4339. struct ggml_tensor * kq_mask,
  4340. struct ggml_tensor * kq_pos,
  4341. int64_t n_ctx,
  4342. int32_t n_tokens,
  4343. int32_t kv_head,
  4344. int32_t n_kv,
  4345. float kq_scale,
  4346. const llm_build_cb & cb,
  4347. int il) {
  4348. // these nodes are added to the graph together so that they are not reordered
  4349. // by doing so, the number of splits in the graph is reduced
  4350. ggml_build_forward_expand(graph, q_cur);
  4351. ggml_build_forward_expand(graph, k_cur);
  4352. ggml_build_forward_expand(graph, v_cur);
  4353. llm_build_kv_store(ctx, hparams, kv, graph, k_cur, v_cur, n_ctx, n_tokens, kv_head, cb, il);
  4354. struct ggml_tensor * cur;
  4355. cur = llm_build_kqv(ctx, model, hparams, kv, graph, wo, wo_b,
  4356. q_cur, kq_mask, kq_pos, n_ctx, n_tokens, n_kv, kq_scale, cb, il);
  4357. cb(cur, "kqv_out", il);
  4358. return cur;
  4359. }
  4360. struct llm_build_context {
  4361. const llama_model & model;
  4362. const llama_context & lctx;
  4363. const llama_hparams & hparams;
  4364. const llama_cparams & cparams;
  4365. const llama_batch & batch;
  4366. const llama_kv_cache & kv_self;
  4367. const int64_t n_embd;
  4368. const int64_t n_layer;
  4369. const int64_t n_rot;
  4370. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  4371. const int64_t n_head;
  4372. const int64_t n_head_kv;
  4373. const int64_t n_embd_head_k;
  4374. const int64_t n_embd_k_gqa;
  4375. const int64_t n_embd_head_v;
  4376. const int64_t n_embd_v_gqa;
  4377. const int64_t n_expert;
  4378. const int64_t n_expert_used;
  4379. const float freq_base;
  4380. const float freq_scale;
  4381. const float ext_factor;
  4382. const float attn_factor;
  4383. const float beta_fast;
  4384. const float beta_slow;
  4385. const float norm_eps;
  4386. const float norm_rms_eps;
  4387. const int32_t n_tokens;
  4388. const int32_t n_kv; // size of KV cache to consider (n_kv <= n_ctx)
  4389. const int32_t kv_head; // index of where we store new KV data in the cache
  4390. const int32_t n_orig_ctx;
  4391. const enum llama_pooling_type pooling_type;
  4392. const enum llama_rope_type rope_type;
  4393. const llm_build_cb & cb;
  4394. std::vector<uint8_t> & buf_compute_meta;
  4395. struct ggml_context * ctx0 = nullptr;
  4396. // TODO: consider making the entire interface noexcept
  4397. llm_build_context(
  4398. llama_context & lctx,
  4399. const llama_batch & batch,
  4400. const llm_build_cb & cb,
  4401. bool worst_case) :
  4402. model (lctx.model),
  4403. lctx (lctx),
  4404. hparams (model.hparams),
  4405. cparams (lctx.cparams),
  4406. batch (batch),
  4407. kv_self (lctx.kv_self),
  4408. n_embd (hparams.n_embd),
  4409. n_layer (hparams.n_layer),
  4410. n_rot (hparams.n_rot),
  4411. n_ctx (cparams.n_ctx),
  4412. n_head (hparams.n_head),
  4413. n_head_kv (hparams.n_head_kv),
  4414. n_embd_head_k (hparams.n_embd_head_k),
  4415. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  4416. n_embd_head_v (hparams.n_embd_head_v),
  4417. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  4418. n_expert (hparams.n_expert),
  4419. n_expert_used (hparams.n_expert_used),
  4420. freq_base (cparams.rope_freq_base),
  4421. freq_scale (cparams.rope_freq_scale),
  4422. ext_factor (cparams.yarn_ext_factor),
  4423. attn_factor (cparams.yarn_attn_factor),
  4424. beta_fast (cparams.yarn_beta_fast),
  4425. beta_slow (cparams.yarn_beta_slow),
  4426. norm_eps (hparams.f_norm_eps),
  4427. norm_rms_eps (hparams.f_norm_rms_eps),
  4428. n_tokens (batch.n_tokens),
  4429. n_kv (worst_case ? n_ctx : kv_self.n),
  4430. kv_head (worst_case ? n_ctx - n_tokens : kv_self.head),
  4431. n_orig_ctx (cparams.n_yarn_orig_ctx),
  4432. pooling_type (cparams.pooling_type),
  4433. rope_type (hparams.rope_type),
  4434. cb (cb),
  4435. buf_compute_meta (lctx.buf_compute_meta) {
  4436. // all initializations should be done in init()
  4437. }
  4438. void init() {
  4439. struct ggml_init_params params = {
  4440. /*.mem_size =*/ buf_compute_meta.size(),
  4441. /*.mem_buffer =*/ buf_compute_meta.data(),
  4442. /*.no_alloc =*/ true,
  4443. };
  4444. ctx0 = ggml_init(params);
  4445. }
  4446. void free() {
  4447. if (ctx0) {
  4448. ggml_free(ctx0);
  4449. ctx0 = nullptr;
  4450. }
  4451. }
  4452. struct ggml_cgraph * build_k_shift() {
  4453. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4454. for (int il = 0; il < n_layer; ++il) {
  4455. struct ggml_tensor * tmp =
  4456. // we rotate only the first n_rot dimensions
  4457. ggml_rope_custom_inplace(ctx0,
  4458. ggml_view_3d(ctx0, kv_self.k_l[il],
  4459. n_embd_head_k, n_head_kv, n_ctx,
  4460. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  4461. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  4462. 0),
  4463. lctx.inp_K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4464. ext_factor, attn_factor, beta_fast, beta_slow);
  4465. cb(tmp, "K_shifted", il);
  4466. ggml_build_forward_expand(gf, tmp);
  4467. }
  4468. return gf;
  4469. }
  4470. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  4471. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4472. for (uint32_t i = 0; i < ids.size(); ++i) {
  4473. const uint32_t id = ids[i];
  4474. if (i == id || id == ids.size()) {
  4475. continue;
  4476. }
  4477. uint32_t nm = 1;
  4478. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  4479. nm++;
  4480. }
  4481. for (int il = 0; il < n_layer; ++il) {
  4482. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  4483. n_embd_k_gqa, nm,
  4484. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  4485. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  4486. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  4487. n_embd_k_gqa, nm,
  4488. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  4489. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  4490. ggml_tensor * view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  4491. nm, n_embd_v_gqa,
  4492. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  4493. ggml_row_size(kv_self.v_l[il]->type, i));
  4494. ggml_tensor * view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  4495. nm, n_embd_v_gqa,
  4496. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  4497. ggml_row_size(kv_self.v_l[il]->type, id));
  4498. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  4499. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  4500. }
  4501. i += nm - 1;
  4502. }
  4503. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  4504. return gf;
  4505. }
  4506. struct ggml_cgraph * build_llama() {
  4507. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4508. const int64_t n_embd_head = hparams.n_embd_head_v;
  4509. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4510. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4511. struct ggml_tensor * cur;
  4512. struct ggml_tensor * inpL;
  4513. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4514. cb(inpL, "inp_embd", -1);
  4515. // inp_pos - contains the positions
  4516. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4517. cb(inp_pos, "inp_pos", -1);
  4518. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4519. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4520. cb(KQ_mask, "KQ_mask", -1);
  4521. for (int il = 0; il < n_layer; ++il) {
  4522. struct ggml_tensor * inpSA = inpL;
  4523. // norm
  4524. cur = llm_build_norm(ctx0, inpL, hparams,
  4525. model.layers[il].attn_norm, NULL,
  4526. LLM_NORM_RMS, cb, il);
  4527. cb(cur, "attn_norm", il);
  4528. // self-attention
  4529. {
  4530. // compute Q and K and RoPE them
  4531. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4532. cb(Qcur, "Qcur", il);
  4533. if (model.layers[il].bq) {
  4534. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  4535. cb(Qcur, "Qcur", il);
  4536. }
  4537. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4538. cb(Kcur, "Kcur", il);
  4539. if (model.layers[il].bk) {
  4540. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4541. cb(Kcur, "Kcur", il);
  4542. }
  4543. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4544. cb(Vcur, "Vcur", il);
  4545. if (model.layers[il].bv) {
  4546. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4547. cb(Vcur, "Vcur", il);
  4548. }
  4549. Qcur = ggml_rope_custom(
  4550. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4551. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4552. ext_factor, attn_factor, beta_fast, beta_slow
  4553. );
  4554. cb(Qcur, "Qcur", il);
  4555. Kcur = ggml_rope_custom(
  4556. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4557. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4558. ext_factor, attn_factor, beta_fast, beta_slow
  4559. );
  4560. cb(Kcur, "Kcur", il);
  4561. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4562. model.layers[il].wo, model.layers[il].bo,
  4563. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4564. cb(cur, "kqv_out", il);
  4565. }
  4566. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4567. cb(ffn_inp, "ffn_inp", il);
  4568. // feed-forward network
  4569. if (model.layers[il].ffn_gate_inp == nullptr) {
  4570. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4571. model.layers[il].ffn_norm, NULL,
  4572. LLM_NORM_RMS, cb, il);
  4573. cb(cur, "ffn_norm", il);
  4574. cur = llm_build_ffn(ctx0, cur,
  4575. model.layers[il].ffn_up, NULL,
  4576. model.layers[il].ffn_gate, NULL,
  4577. model.layers[il].ffn_down, NULL,
  4578. NULL,
  4579. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4580. cb(cur, "ffn_out", il);
  4581. } else {
  4582. // MoE branch
  4583. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4584. model.layers[il].ffn_norm, NULL,
  4585. LLM_NORM_RMS, cb, il);
  4586. cb(cur, "ffn_norm", il);
  4587. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  4588. cb(logits, "ffn_moe_logits", il);
  4589. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  4590. cb(probs, "ffn_moe_probs", il);
  4591. // select experts
  4592. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  4593. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  4594. ggml_tensor * weights = ggml_get_rows(ctx0,
  4595. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  4596. cb(weights, "ffn_moe_weights", il);
  4597. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  4598. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  4599. cb(weights_sum, "ffn_moe_weights_sum", il);
  4600. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  4601. cb(weights, "ffn_moe_weights_norm", il);
  4602. // compute expert outputs
  4603. ggml_tensor * moe_out = nullptr;
  4604. for (int i = 0; i < n_expert_used; ++i) {
  4605. ggml_tensor * cur_expert;
  4606. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  4607. cb(cur_up, "ffn_moe_up", il);
  4608. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  4609. cb(cur_gate, "ffn_moe_gate", il);
  4610. cur_gate = ggml_silu(ctx0, cur_gate);
  4611. cb(cur_gate, "ffn_moe_silu", il);
  4612. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  4613. cb(cur_expert, "ffn_moe_gate_par", il);
  4614. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  4615. cb(cur_expert, "ffn_moe_down", il);
  4616. cur_expert = ggml_mul(ctx0, cur_expert,
  4617. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  4618. cb(cur_expert, "ffn_moe_weighted", il);
  4619. if (i == 0) {
  4620. moe_out = cur_expert;
  4621. } else {
  4622. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  4623. cb(moe_out, "ffn_moe_out", il);
  4624. }
  4625. }
  4626. cur = moe_out;
  4627. }
  4628. cur = ggml_add(ctx0, cur, ffn_inp);
  4629. cb(cur, "l_out", il);
  4630. // input for next layer
  4631. inpL = cur;
  4632. }
  4633. cur = inpL;
  4634. cur = llm_build_norm(ctx0, cur, hparams,
  4635. model.output_norm, NULL,
  4636. LLM_NORM_RMS, cb, -1);
  4637. cb(cur, "result_norm", -1);
  4638. // lm_head
  4639. cur = ggml_mul_mat(ctx0, model.output, cur);
  4640. cb(cur, "result_output", -1);
  4641. ggml_build_forward_expand(gf, cur);
  4642. return gf;
  4643. }
  4644. struct ggml_cgraph * build_baichuan() {
  4645. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4646. const int64_t n_embd_head = hparams.n_embd_head_v;
  4647. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4648. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4649. struct ggml_tensor * cur;
  4650. struct ggml_tensor * inpL;
  4651. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4652. cb(inpL, "inp_embd", -1);
  4653. // inp_pos - contains the positions
  4654. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4655. cb(inp_pos, "inp_pos", -1);
  4656. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4657. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4658. cb(KQ_mask, "KQ_mask", -1);
  4659. // positions of the tokens in the KV cache
  4660. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  4661. cb(KQ_pos, "KQ_pos", -1);
  4662. for (int il = 0; il < n_layer; ++il) {
  4663. struct ggml_tensor * inpSA = inpL;
  4664. cur = llm_build_norm(ctx0, inpL, hparams,
  4665. model.layers[il].attn_norm, NULL,
  4666. LLM_NORM_RMS, cb, il);
  4667. cb(cur, "attn_norm", il);
  4668. // self-attention
  4669. {
  4670. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4671. cb(Qcur, "Qcur", il);
  4672. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4673. cb(Kcur, "Kcur", il);
  4674. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4675. cb(Vcur, "Vcur", il);
  4676. switch (model.type) {
  4677. case MODEL_7B:
  4678. Qcur = ggml_rope_custom(
  4679. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4680. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4681. ext_factor, attn_factor, beta_fast, beta_slow
  4682. );
  4683. Kcur = ggml_rope_custom(
  4684. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4685. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4686. ext_factor, attn_factor, beta_fast, beta_slow
  4687. );
  4688. break;
  4689. case MODEL_13B:
  4690. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  4691. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  4692. break;
  4693. default:
  4694. GGML_ASSERT(false);
  4695. }
  4696. cb(Qcur, "Qcur", il);
  4697. cb(Kcur, "Kcur", il);
  4698. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4699. model.layers[il].wo, NULL,
  4700. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4701. cb(cur, "kqv_out", il);
  4702. }
  4703. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4704. cb(ffn_inp, "ffn_inp", il);
  4705. // feed-forward network
  4706. {
  4707. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4708. model.layers[il].ffn_norm, NULL,
  4709. LLM_NORM_RMS, cb, il);
  4710. cb(cur, "ffn_norm", il);
  4711. cur = llm_build_ffn(ctx0, cur,
  4712. model.layers[il].ffn_up, NULL,
  4713. model.layers[il].ffn_gate, NULL,
  4714. model.layers[il].ffn_down, NULL,
  4715. NULL,
  4716. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4717. cb(cur, "ffn_out", il);
  4718. }
  4719. cur = ggml_add(ctx0, cur, ffn_inp);
  4720. cb(cur, "l_out", il);
  4721. // input for next layer
  4722. inpL = cur;
  4723. }
  4724. cur = inpL;
  4725. cur = llm_build_norm(ctx0, cur, hparams,
  4726. model.output_norm, NULL,
  4727. LLM_NORM_RMS, cb, -1);
  4728. cb(cur, "result_norm", -1);
  4729. // lm_head
  4730. cur = ggml_mul_mat(ctx0, model.output, cur);
  4731. cb(cur, "result_output", -1);
  4732. ggml_build_forward_expand(gf, cur);
  4733. return gf;
  4734. }
  4735. struct ggml_cgraph * build_falcon() {
  4736. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4737. const int64_t n_embd_head = hparams.n_embd_head_v;
  4738. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4739. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4740. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4741. struct ggml_tensor * cur;
  4742. struct ggml_tensor * inpL;
  4743. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4744. cb(inpL, "inp_embd", -1);
  4745. // inp_pos - contains the positions
  4746. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4747. cb(inp_pos, "inp_pos", -1);
  4748. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4749. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4750. cb(KQ_mask, "KQ_mask", -1);
  4751. for (int il = 0; il < n_layer; ++il) {
  4752. struct ggml_tensor * attn_norm;
  4753. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  4754. model.layers[il].attn_norm,
  4755. model.layers[il].attn_norm_b,
  4756. LLM_NORM, cb, il);
  4757. cb(attn_norm, "attn_norm", il);
  4758. // self-attention
  4759. {
  4760. if (model.layers[il].attn_norm_2) {
  4761. // Falcon-40B
  4762. cur = llm_build_norm(ctx0, inpL, hparams,
  4763. model.layers[il].attn_norm_2,
  4764. model.layers[il].attn_norm_2_b,
  4765. LLM_NORM, cb, il);
  4766. cb(cur, "attn_norm_2", il);
  4767. } else {
  4768. cur = attn_norm;
  4769. }
  4770. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4771. cb(cur, "wqkv", il);
  4772. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4773. 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)));
  4774. 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)));
  4775. cb(Qcur, "Qcur", il);
  4776. cb(Kcur, "Kcur", il);
  4777. cb(Vcur, "Vcur", il);
  4778. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4779. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4780. // using mode = 2 for neox mode
  4781. Qcur = ggml_rope_custom(
  4782. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  4783. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4784. );
  4785. cb(Qcur, "Qcur", il);
  4786. Kcur = ggml_rope_custom(
  4787. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  4788. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4789. );
  4790. cb(Kcur, "Kcur", il);
  4791. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4792. model.layers[il].wo, NULL,
  4793. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4794. cb(cur, "kqv_out", il);
  4795. }
  4796. struct ggml_tensor * ffn_inp = cur;
  4797. // feed forward
  4798. {
  4799. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  4800. model.layers[il].ffn_up, NULL,
  4801. NULL, NULL,
  4802. model.layers[il].ffn_down, NULL,
  4803. NULL,
  4804. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4805. cb(cur, "ffn_out", il);
  4806. }
  4807. cur = ggml_add(ctx0, cur, ffn_inp);
  4808. cb(cur, "l_out", il);
  4809. cur = ggml_add(ctx0, cur, inpL);
  4810. cb(cur, "l_out", il);
  4811. // input for next layer
  4812. inpL = cur;
  4813. }
  4814. cur = inpL;
  4815. // norm
  4816. cur = llm_build_norm(ctx0, cur, hparams,
  4817. model.output_norm,
  4818. model.output_norm_b,
  4819. LLM_NORM, cb, -1);
  4820. cb(cur, "result_norm", -1);
  4821. cur = ggml_mul_mat(ctx0, model.output, cur);
  4822. cb(cur, "result_output", -1);
  4823. ggml_build_forward_expand(gf, cur);
  4824. return gf;
  4825. }
  4826. struct ggml_cgraph * build_starcoder() {
  4827. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4828. const int64_t n_embd_head = hparams.n_embd_head_v;
  4829. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4830. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4831. struct ggml_tensor * cur;
  4832. struct ggml_tensor * pos;
  4833. struct ggml_tensor * inpL;
  4834. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4835. cb(inpL, "inp_embd", -1);
  4836. // inp_pos - contains the positions
  4837. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4838. cb(inp_pos, "inp_pos", -1);
  4839. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4840. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4841. cb(KQ_mask, "KQ_mask", -1);
  4842. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  4843. cb(pos, "pos_embd", -1);
  4844. inpL = ggml_add(ctx0, inpL, pos);
  4845. cb(inpL, "inpL", -1);
  4846. for (int il = 0; il < n_layer; ++il) {
  4847. cur = llm_build_norm(ctx0, inpL, hparams,
  4848. model.layers[il].attn_norm,
  4849. model.layers[il].attn_norm_b,
  4850. LLM_NORM, cb, il);
  4851. cb(cur, "attn_norm", il);
  4852. // self-attention
  4853. {
  4854. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4855. cb(cur, "wqkv", il);
  4856. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4857. cb(cur, "bqkv", il);
  4858. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4859. 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)));
  4860. 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)));
  4861. cb(Qcur, "Qcur", il);
  4862. cb(Kcur, "Kcur", il);
  4863. cb(Vcur, "Vcur", il);
  4864. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4865. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4866. model.layers[il].wo, model.layers[il].bo,
  4867. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4868. cb(cur, "kqv_out", il);
  4869. }
  4870. // add the input
  4871. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4872. cb(ffn_inp, "ffn_inp", il);
  4873. // FF
  4874. {
  4875. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4876. model.layers[il].ffn_norm,
  4877. model.layers[il].ffn_norm_b,
  4878. LLM_NORM, cb, il);
  4879. cb(cur, "ffn_norm", il);
  4880. cur = llm_build_ffn(ctx0, cur,
  4881. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4882. NULL, NULL,
  4883. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4884. NULL,
  4885. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4886. cb(cur, "ffn_out", il);
  4887. }
  4888. inpL = ggml_add(ctx0, cur, ffn_inp);
  4889. cb(inpL, "l_out", il);
  4890. }
  4891. cur = llm_build_norm(ctx0, inpL, hparams,
  4892. model.output_norm,
  4893. model.output_norm_b,
  4894. LLM_NORM, cb, -1);
  4895. cb(cur, "result_norm", -1);
  4896. cur = ggml_mul_mat(ctx0, model.output, cur);
  4897. cb(cur, "result_output", -1);
  4898. ggml_build_forward_expand(gf, cur);
  4899. return gf;
  4900. }
  4901. struct ggml_cgraph * build_persimmon() {
  4902. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4903. const int64_t n_embd_head = hparams.n_embd_head_v;
  4904. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4905. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  4906. struct ggml_tensor * cur;
  4907. struct ggml_tensor * inpL;
  4908. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4909. cb(inpL, "inp_embd", -1);
  4910. // inp_pos - contains the positions
  4911. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4912. cb(inp_pos, "inp_pos", -1);
  4913. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4914. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4915. cb(KQ_mask, "KQ_mask", -1);
  4916. for (int il = 0; il < n_layer; ++il) {
  4917. struct ggml_tensor * residual = inpL;
  4918. cur = llm_build_norm(ctx0, inpL, hparams,
  4919. model.layers[il].attn_norm,
  4920. model.layers[il].attn_norm_b,
  4921. LLM_NORM, cb, il);
  4922. cb(cur, "attn_norm", il);
  4923. // self attention
  4924. {
  4925. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4926. cb(cur, "wqkv", il);
  4927. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4928. cb(cur, "bqkv", il);
  4929. // split qkv
  4930. GGML_ASSERT(n_head_kv == n_head);
  4931. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  4932. cb(tmpqkv, "tmpqkv", il);
  4933. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  4934. cb(tmpqkv_perm, "tmpqkv", il);
  4935. struct ggml_tensor * tmpq = ggml_view_3d(
  4936. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4937. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4938. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4939. 0
  4940. );
  4941. cb(tmpq, "tmpq", il);
  4942. struct ggml_tensor * tmpk = ggml_view_3d(
  4943. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4944. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4945. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4946. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  4947. );
  4948. cb(tmpk, "tmpk", il);
  4949. // Q/K Layernorm
  4950. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  4951. model.layers[il].attn_q_norm,
  4952. model.layers[il].attn_q_norm_b,
  4953. LLM_NORM, cb, il);
  4954. cb(tmpq, "tmpq", il);
  4955. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  4956. model.layers[il].attn_k_norm,
  4957. model.layers[il].attn_k_norm_b,
  4958. LLM_NORM, cb, il);
  4959. cb(tmpk, "tmpk", il);
  4960. // RoPE the first n_rot of q/k, pass the other half, and concat.
  4961. struct ggml_tensor * qrot = ggml_view_3d(
  4962. ctx0, tmpq, n_rot, n_head, n_tokens,
  4963. ggml_element_size(tmpq) * n_embd_head,
  4964. ggml_element_size(tmpq) * n_embd_head * n_head,
  4965. 0
  4966. );
  4967. cb(qrot, "qrot", il);
  4968. struct ggml_tensor * krot = ggml_view_3d(
  4969. ctx0, tmpk, n_rot, n_head, n_tokens,
  4970. ggml_element_size(tmpk) * n_embd_head,
  4971. ggml_element_size(tmpk) * n_embd_head * n_head,
  4972. 0
  4973. );
  4974. cb(krot, "krot", il);
  4975. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  4976. struct ggml_tensor * qpass = ggml_view_3d(
  4977. ctx0, tmpq, n_rot, n_head, n_tokens,
  4978. ggml_element_size(tmpq) * n_embd_head,
  4979. ggml_element_size(tmpq) * n_embd_head * n_head,
  4980. ggml_element_size(tmpq) * n_rot
  4981. );
  4982. cb(qpass, "qpass", il);
  4983. struct ggml_tensor * kpass = ggml_view_3d(
  4984. ctx0, tmpk, n_rot, n_head, n_tokens,
  4985. ggml_element_size(tmpk) * n_embd_head,
  4986. ggml_element_size(tmpk) * n_embd_head * n_head,
  4987. ggml_element_size(tmpk) * n_rot
  4988. );
  4989. cb(kpass, "kpass", il);
  4990. struct ggml_tensor * qrotated = ggml_rope_custom(
  4991. ctx0, qrot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  4992. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4993. );
  4994. cb(qrotated, "qrotated", il);
  4995. struct ggml_tensor * krotated = ggml_rope_custom(
  4996. ctx0, krot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  4997. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4998. );
  4999. cb(krotated, "krotated", il);
  5000. // ggml currently only supports concatenation on dim=2
  5001. // so we need to permute qrot, qpass, concat, then permute back.
  5002. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  5003. cb(qrotated, "qrotated", il);
  5004. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  5005. cb(krotated, "krotated", il);
  5006. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  5007. cb(qpass, "qpass", il);
  5008. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  5009. cb(kpass, "kpass", il);
  5010. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  5011. cb(Qcur, "Qcur", il);
  5012. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  5013. cb(Kcur, "Kcur", il);
  5014. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  5015. cb(Q, "Q", il);
  5016. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  5017. cb(Kcur, "Kcur", il);
  5018. struct ggml_tensor * Vcur = ggml_view_3d(
  5019. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  5020. ggml_element_size(tmpqkv_perm) * n_embd_head,
  5021. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  5022. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  5023. );
  5024. cb(Vcur, "Vcur", il);
  5025. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5026. model.layers[il].wo, model.layers[il].bo,
  5027. Kcur, Vcur, Q, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5028. cb(cur, "kqv_out", il);
  5029. }
  5030. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  5031. cb(ffn_inp, "ffn_inp", il);
  5032. // feed-forward network
  5033. {
  5034. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5035. model.layers[il].ffn_norm,
  5036. model.layers[il].ffn_norm_b,
  5037. LLM_NORM, cb, il);
  5038. cb(cur, "ffn_norm", il);
  5039. cur = llm_build_ffn(ctx0, cur,
  5040. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5041. NULL, NULL,
  5042. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5043. NULL,
  5044. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  5045. cb(cur, "ffn_out", il);
  5046. }
  5047. cur = ggml_add(ctx0, cur, ffn_inp);
  5048. cb(cur, "l_out", il);
  5049. inpL = cur;
  5050. }
  5051. cur = inpL;
  5052. cur = llm_build_norm(ctx0, cur, hparams,
  5053. model.output_norm,
  5054. model.output_norm_b,
  5055. LLM_NORM, cb, -1);
  5056. cb(cur, "result_norm", -1);
  5057. cur = ggml_mul_mat(ctx0, model.output, cur);
  5058. cb(cur, "result_output", -1);
  5059. ggml_build_forward_expand(gf, cur);
  5060. return gf;
  5061. }
  5062. struct ggml_cgraph * build_refact() {
  5063. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5064. const int64_t n_embd_head = hparams.n_embd_head_v;
  5065. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5066. struct ggml_tensor * cur;
  5067. struct ggml_tensor * inpL;
  5068. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5069. cb(inpL, "inp_embd", -1);
  5070. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5071. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5072. cb(KQ_mask, "KQ_mask", -1);
  5073. // positions of the tokens in the KV cache
  5074. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  5075. cb(KQ_pos, "KQ_pos", -1);
  5076. for (int il = 0; il < n_layer; ++il) {
  5077. struct ggml_tensor * inpSA = inpL;
  5078. cur = llm_build_norm(ctx0, inpL, hparams,
  5079. model.layers[il].attn_norm, NULL,
  5080. LLM_NORM_RMS, cb, il);
  5081. cb(cur, "attn_norm", il);
  5082. // self-attention
  5083. {
  5084. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5085. cb(Qcur, "Qcur", il);
  5086. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5087. cb(Kcur, "Kcur", il);
  5088. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5089. cb(Vcur, "Vcur", il);
  5090. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5091. cb(Kcur, "Kcur", il);
  5092. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5093. cb(Qcur, "Qcur", il);
  5094. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5095. model.layers[il].wo, NULL,
  5096. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5097. cb(cur, "kqv_out", il);
  5098. }
  5099. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5100. cb(ffn_inp, "ffn_inp", il);
  5101. // feed-forward network
  5102. {
  5103. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5104. model.layers[il].ffn_norm, NULL,
  5105. LLM_NORM_RMS, cb, il);
  5106. cb(cur, "ffn_norm", il);
  5107. cur = llm_build_ffn(ctx0, cur,
  5108. model.layers[il].ffn_up, NULL,
  5109. model.layers[il].ffn_gate, NULL,
  5110. model.layers[il].ffn_down, NULL,
  5111. NULL,
  5112. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5113. cb(cur, "ffn_out", il);
  5114. }
  5115. cur = ggml_add(ctx0, cur, ffn_inp);
  5116. cb(cur, "l_out", il);
  5117. // input for next layer
  5118. inpL = cur;
  5119. }
  5120. cur = inpL;
  5121. cur = llm_build_norm(ctx0, cur, hparams,
  5122. model.output_norm, NULL,
  5123. LLM_NORM_RMS, cb, -1);
  5124. cb(cur, "result_norm", -1);
  5125. // lm_head
  5126. cur = ggml_mul_mat(ctx0, model.output, cur);
  5127. cb(cur, "result_output", -1);
  5128. ggml_build_forward_expand(gf, cur);
  5129. return gf;
  5130. }
  5131. struct ggml_cgraph * build_bert() {
  5132. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5133. const int64_t n_embd_head = hparams.n_embd_head_v;
  5134. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5135. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5136. struct ggml_tensor * cur;
  5137. struct ggml_tensor * inpL;
  5138. // get input vectors with right size
  5139. const size_t stride1 = n_tokens * ggml_type_size(lctx.inp_tokens->type);
  5140. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5141. struct ggml_tensor * inp_mean = ggml_view_2d(ctx0, lctx.inp_mean, n_tokens, n_tokens, stride1, 0);
  5142. struct ggml_tensor * inp_cls = ggml_view_1d(ctx0, lctx.inp_cls, n_tokens, 0);
  5143. // construct input embeddings (token, type, position)
  5144. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5145. // token types are hardcoded to zero ("Sentence A")
  5146. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  5147. inpL = ggml_add(ctx0, inpL, type_row0);
  5148. if (model.arch == LLM_ARCH_BERT) {
  5149. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  5150. }
  5151. cb(inpL, "inp_embd", -1);
  5152. // embed layer norm
  5153. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  5154. cb(inpL, "inp_norm", -1);
  5155. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5156. struct ggml_tensor * KQ_mask = ggml_cont(ctx0, ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_tokens, n_tokens, n_tokens*ggml_type_size(lctx.inp_KQ_mask->type), 0));
  5157. cb(KQ_mask, "KQ_mask", -1); // [n_tokens, n_tokens]
  5158. // iterate layers
  5159. for (int il = 0; il < n_layer; ++il) {
  5160. struct ggml_tensor * cur = inpL;
  5161. struct ggml_tensor * Qcur;
  5162. struct ggml_tensor * Kcur;
  5163. struct ggml_tensor * Vcur;
  5164. // self-attention
  5165. if (model.arch == LLM_ARCH_BERT) {
  5166. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  5167. cb(Qcur, "Qcur", il);
  5168. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  5169. cb(Kcur, "Kcur", il);
  5170. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  5171. cb(Vcur, "Vcur", il);
  5172. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5173. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5174. } else {
  5175. // compute Q and K and RoPE them
  5176. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5177. cb(cur, "wqkv", il);
  5178. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5179. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5180. 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)));
  5181. cb(Qcur, "Qcur", il);
  5182. cb(Kcur, "Kcur", il);
  5183. cb(Vcur, "Vcur", il);
  5184. Qcur = ggml_rope_custom(
  5185. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5186. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5187. ext_factor, attn_factor, beta_fast, beta_slow
  5188. );
  5189. cb(Qcur, "Qcur", il);
  5190. Kcur = ggml_rope_custom(
  5191. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5192. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5193. ext_factor, attn_factor, beta_fast, beta_slow
  5194. );
  5195. cb(Kcur, "Kcur", il);
  5196. }
  5197. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  5198. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  5199. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  5200. cb(kq, "kq", il);
  5201. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask, nullptr, 1.0f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  5202. cb(kq, "kq_soft_max_ext", il);
  5203. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  5204. cb(v, "v", il);
  5205. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  5206. cb(kqv, "kqv", il);
  5207. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  5208. cb(kqv_merged, "kqv_merged", il);
  5209. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  5210. cb(cur, "kqv_merged_cont", il);
  5211. ggml_build_forward_expand(gf, cur);
  5212. cur = ggml_mul_mat(ctx0, model.layers[il].wo, cur);
  5213. if (model.layers[il].bo) {
  5214. cb(cur, "kqv_wo", il);
  5215. }
  5216. if (model.layers[il].bo) {
  5217. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  5218. }
  5219. cb(cur, "kqv_out", il);
  5220. // re-add the layer input
  5221. cur = ggml_add(ctx0, cur, inpL);
  5222. // attention layer norm
  5223. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  5224. struct ggml_tensor * ffn_inp = cur;
  5225. cb(ffn_inp, "ffn_inp", il);
  5226. // feed-forward network
  5227. if (model.arch == LLM_ARCH_BERT) {
  5228. cur = llm_build_ffn(ctx0, cur,
  5229. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5230. NULL, NULL,
  5231. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5232. NULL,
  5233. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5234. } else {
  5235. cur = llm_build_ffn(ctx0, cur,
  5236. model.layers[il].ffn_up, NULL,
  5237. model.layers[il].ffn_gate, NULL,
  5238. model.layers[il].ffn_down, NULL,
  5239. NULL,
  5240. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5241. }
  5242. cb(cur, "ffn_out", il);
  5243. // attentions bypass the intermediate layer
  5244. cur = ggml_add(ctx0, cur, ffn_inp);
  5245. // output layer norm
  5246. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  5247. // input for next layer
  5248. inpL = cur;
  5249. }
  5250. // final output
  5251. cur = inpL;
  5252. cb(cur, "result_embd", -1);
  5253. // pooling layer
  5254. switch (pooling_type) {
  5255. case LLAMA_POOLING_TYPE_NONE:
  5256. {
  5257. // nop
  5258. } break;
  5259. case LLAMA_POOLING_TYPE_MEAN:
  5260. {
  5261. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, cur)), inp_mean);
  5262. cb(cur, "result_embd_pooled", -1);
  5263. } break;
  5264. case LLAMA_POOLING_TYPE_CLS:
  5265. {
  5266. cur = ggml_get_rows(ctx0, cur, inp_cls);
  5267. cb(cur, "result_embd_pooled", -1);
  5268. } break;
  5269. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  5270. {
  5271. GGML_ASSERT(false && "Invalid pooling type");
  5272. } break;
  5273. }
  5274. ggml_build_forward_expand(gf, cur);
  5275. return gf;
  5276. }
  5277. struct ggml_cgraph * build_bloom() {
  5278. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5279. const int64_t n_embd_head = hparams.n_embd_head_v;
  5280. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5281. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5282. struct ggml_tensor * cur;
  5283. struct ggml_tensor * inpL;
  5284. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5285. cb(inpL, "inp_embd", -1);
  5286. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5287. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5288. cb(KQ_mask, "KQ_mask", -1);
  5289. // positions of the tokens in the KV cache
  5290. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  5291. cb(KQ_pos, "KQ_pos", -1);
  5292. inpL = llm_build_norm(ctx0, inpL, hparams,
  5293. model.tok_norm,
  5294. model.tok_norm_b,
  5295. LLM_NORM, cb, -1);
  5296. cb(inpL, "inp_norm", -1);
  5297. for (int il = 0; il < n_layer; ++il) {
  5298. cur = llm_build_norm(ctx0, inpL, hparams,
  5299. model.layers[il].attn_norm,
  5300. model.layers[il].attn_norm_b,
  5301. LLM_NORM, cb, il);
  5302. cb(cur, "attn_norm", il);
  5303. // self-attention
  5304. {
  5305. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5306. cb(cur, "wqkv", il);
  5307. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5308. cb(cur, "bqkv", il);
  5309. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5310. 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)));
  5311. 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)));
  5312. cb(Qcur, "Qcur", il);
  5313. cb(Kcur, "Kcur", il);
  5314. cb(Vcur, "Vcur", il);
  5315. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5316. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5317. model.layers[il].wo, model.layers[il].bo,
  5318. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5319. cb(cur, "kqv_out", il);
  5320. }
  5321. // Add the input
  5322. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5323. cb(ffn_inp, "ffn_inp", il);
  5324. // FF
  5325. {
  5326. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5327. model.layers[il].ffn_norm,
  5328. model.layers[il].ffn_norm_b,
  5329. LLM_NORM, cb, il);
  5330. cb(cur, "ffn_norm", il);
  5331. cur = llm_build_ffn(ctx0, cur,
  5332. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5333. NULL, NULL,
  5334. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5335. NULL,
  5336. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5337. cb(cur, "ffn_out", il);
  5338. }
  5339. inpL = ggml_add(ctx0, cur, ffn_inp);
  5340. cb(inpL, "l_out", il);
  5341. }
  5342. cur = llm_build_norm(ctx0, inpL, hparams,
  5343. model.output_norm,
  5344. model.output_norm_b,
  5345. LLM_NORM, cb, -1);
  5346. cb(cur, "result_norm", -1);
  5347. cur = ggml_mul_mat(ctx0, model.output, cur);
  5348. cb(cur, "result_output", -1);
  5349. ggml_build_forward_expand(gf, cur);
  5350. return gf;
  5351. }
  5352. struct ggml_cgraph * build_mpt() {
  5353. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5354. const int64_t n_embd_head = hparams.n_embd_head_v;
  5355. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5356. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5357. struct ggml_tensor * cur;
  5358. struct ggml_tensor * inpL;
  5359. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5360. cb(inpL, "inp_embd", -1);
  5361. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5362. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5363. cb(KQ_mask, "KQ_mask", -1);
  5364. // positions of the tokens in the KV cache
  5365. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  5366. cb(KQ_pos, "KQ_pos", -1);
  5367. for (int il = 0; il < n_layer; ++il) {
  5368. struct ggml_tensor * attn_norm;
  5369. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  5370. model.layers[il].attn_norm,
  5371. model.layers[il].attn_norm_b,
  5372. LLM_NORM, cb, il);
  5373. cb(attn_norm, "attn_norm", il);
  5374. // self-attention
  5375. {
  5376. cur = attn_norm;
  5377. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5378. cb(cur, "wqkv", il);
  5379. if (model.layers[il].bqkv){
  5380. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5381. cb(cur, "bqkv", il);
  5382. }
  5383. if (hparams.f_clamp_kqv > 0.0f) {
  5384. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  5385. cb(cur, "wqkv_clamped", il);
  5386. }
  5387. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5388. 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)));
  5389. 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)));
  5390. cb(Qcur, "Qcur", il);
  5391. cb(Kcur, "Kcur", il);
  5392. cb(Vcur, "Vcur", il);
  5393. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5394. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5395. model.layers[il].wo, model.layers[il].bo,
  5396. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5397. cb(cur, "kqv_out", il);
  5398. }
  5399. // Add the input
  5400. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5401. cb(ffn_inp, "ffn_inp", il);
  5402. // feed forward
  5403. {
  5404. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5405. model.layers[il].ffn_norm,
  5406. model.layers[il].ffn_norm_b,
  5407. LLM_NORM, cb, il);
  5408. cb(cur, "ffn_norm", il);
  5409. cur = llm_build_ffn(ctx0, cur,
  5410. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5411. NULL, NULL,
  5412. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5413. model.layers[il].ffn_act,
  5414. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5415. cb(cur, "ffn_out", il);
  5416. }
  5417. cur = ggml_add(ctx0, cur, ffn_inp);
  5418. cb(cur, "l_out", il);
  5419. // input for next layer
  5420. inpL = cur;
  5421. }
  5422. cur = inpL;
  5423. cur = llm_build_norm(ctx0, cur, hparams,
  5424. model.output_norm,
  5425. model.output_norm_b,
  5426. LLM_NORM, cb, -1);
  5427. cb(cur, "result_norm", -1);
  5428. cur = ggml_mul_mat(ctx0, model.output, cur);
  5429. cb(cur, "result_output", -1);
  5430. ggml_build_forward_expand(gf, cur);
  5431. return gf;
  5432. }
  5433. struct ggml_cgraph * build_stablelm() {
  5434. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  5435. const int64_t n_embd_head = hparams.n_embd_head_v;
  5436. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5437. struct ggml_tensor * cur;
  5438. struct ggml_tensor * inpL;
  5439. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5440. cb(inpL, "inp_embd", -1);
  5441. // inp_pos - contains the positions
  5442. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5443. cb(inp_pos, "inp_pos", -1);
  5444. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5445. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5446. cb(KQ_mask, "KQ_mask", -1);
  5447. for (int il = 0; il < n_layer; ++il) {
  5448. struct ggml_tensor * inpSA = inpL;
  5449. // norm
  5450. cur = llm_build_norm(ctx0, inpL, hparams,
  5451. model.layers[il].attn_norm,
  5452. model.layers[il].attn_norm_b,
  5453. LLM_NORM, cb, il);
  5454. cb(cur, "attn_norm", il);
  5455. // self-attention
  5456. {
  5457. // compute Q and K and RoPE them
  5458. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5459. cb(Qcur, "Qcur", il);
  5460. if (model.layers[il].bq) {
  5461. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5462. cb(Qcur, "Qcur", il);
  5463. }
  5464. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5465. cb(Kcur, "Kcur", il);
  5466. if (model.layers[il].bk) {
  5467. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5468. cb(Kcur, "Kcur", il);
  5469. }
  5470. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5471. cb(Vcur, "Vcur", il);
  5472. if (model.layers[il].bv) {
  5473. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5474. cb(Vcur, "Vcur", il);
  5475. }
  5476. Qcur = ggml_rope_custom(
  5477. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5478. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5479. ext_factor, attn_factor, beta_fast, beta_slow
  5480. );
  5481. cb(Qcur, "Qcur", il);
  5482. Kcur = ggml_rope_custom(
  5483. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5484. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5485. ext_factor, attn_factor, beta_fast, beta_slow
  5486. );
  5487. cb(Kcur, "Kcur", il);
  5488. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5489. model.layers[il].wo, NULL,
  5490. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5491. cb(cur, "kqv_out", il);
  5492. }
  5493. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5494. cb(ffn_inp, "ffn_inp", il);
  5495. // feed-forward network
  5496. {
  5497. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5498. model.layers[il].ffn_norm,
  5499. model.layers[il].ffn_norm_b,
  5500. LLM_NORM, cb, il);
  5501. cb(cur, "ffn_norm", il);
  5502. cur = llm_build_ffn(ctx0, cur,
  5503. model.layers[il].ffn_up, NULL,
  5504. model.layers[il].ffn_gate, NULL,
  5505. model.layers[il].ffn_down, NULL,
  5506. NULL,
  5507. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5508. cb(cur, "ffn_out", il);
  5509. }
  5510. cur = ggml_add(ctx0, cur, ffn_inp);
  5511. cb(cur, "l_out", il);
  5512. // input for next layer
  5513. inpL = cur;
  5514. }
  5515. cur = inpL;
  5516. cur = llm_build_norm(ctx0, cur, hparams,
  5517. model.output_norm,
  5518. model.output_norm_b,
  5519. LLM_NORM, cb, -1);
  5520. cb(cur, "result_norm", -1);
  5521. // lm_head
  5522. cur = ggml_mul_mat(ctx0, model.output, cur);
  5523. cb(cur, "result_output", -1);
  5524. ggml_build_forward_expand(gf, cur);
  5525. return gf;
  5526. }
  5527. struct ggml_cgraph * build_qwen() {
  5528. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5529. const int64_t n_embd_head = hparams.n_embd_head_v;
  5530. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5531. struct ggml_tensor * cur;
  5532. struct ggml_tensor * inpL;
  5533. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5534. cb(inpL, "inp_embd", -1);
  5535. // inp_pos - contains the positions
  5536. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5537. cb(inp_pos, "inp_pos", -1);
  5538. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5539. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5540. cb(KQ_mask, "KQ_mask", -1);
  5541. for (int il = 0; il < n_layer; ++il) {
  5542. struct ggml_tensor * inpSA = inpL;
  5543. cur = llm_build_norm(ctx0, inpL, hparams,
  5544. model.layers[il].attn_norm, NULL,
  5545. LLM_NORM_RMS, cb, il);
  5546. cb(cur, "attn_norm", il);
  5547. // self-attention
  5548. {
  5549. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5550. cb(cur, "wqkv", il);
  5551. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5552. cb(cur, "bqkv", il);
  5553. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5554. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5555. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  5556. cb(Qcur, "Qcur", il);
  5557. cb(Kcur, "Kcur", il);
  5558. cb(Vcur, "Vcur", il);
  5559. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5560. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5561. // using mode = 2 for neox mode
  5562. Qcur = ggml_rope_custom(
  5563. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5564. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5565. );
  5566. cb(Qcur, "Qcur", il);
  5567. Kcur = ggml_rope_custom(
  5568. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5569. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5570. );
  5571. cb(Kcur, "Kcur", il);
  5572. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5573. model.layers[il].wo, NULL,
  5574. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5575. cb(cur, "kqv_out", il);
  5576. }
  5577. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5578. cb(ffn_inp, "ffn_inp", il);
  5579. // feed-forward forward
  5580. {
  5581. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5582. model.layers[il].ffn_norm, NULL,
  5583. LLM_NORM_RMS, cb, il);
  5584. cb(cur, "ffn_norm", il);
  5585. cur = llm_build_ffn(ctx0, cur,
  5586. model.layers[il].ffn_up, NULL,
  5587. model.layers[il].ffn_gate, NULL,
  5588. model.layers[il].ffn_down, NULL,
  5589. NULL,
  5590. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5591. cb(cur, "ffn_out", il);
  5592. }
  5593. cur = ggml_add(ctx0, cur, ffn_inp);
  5594. cb(cur, "l_out", il);
  5595. // input for next layer
  5596. inpL = cur;
  5597. }
  5598. cur = inpL;
  5599. cur = llm_build_norm(ctx0, cur, hparams,
  5600. model.output_norm, NULL,
  5601. LLM_NORM_RMS, cb, -1);
  5602. cb(cur, "result_norm", -1);
  5603. // lm_head
  5604. cur = ggml_mul_mat(ctx0, model.output, cur);
  5605. cb(cur, "result_output", -1);
  5606. ggml_build_forward_expand(gf, cur);
  5607. return gf;
  5608. }
  5609. struct ggml_cgraph * build_qwen2() {
  5610. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5611. const int64_t n_embd_head = hparams.n_embd_head_v;
  5612. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5613. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5614. struct ggml_tensor * cur;
  5615. struct ggml_tensor * inpL;
  5616. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5617. cb(inpL, "inp_embd", -1);
  5618. // inp_pos - contains the positions
  5619. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5620. cb(inp_pos, "inp_pos", -1);
  5621. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5622. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5623. cb(KQ_mask, "KQ_mask", -1);
  5624. for (int il = 0; il < n_layer; ++il) {
  5625. struct ggml_tensor * inpSA = inpL;
  5626. // norm
  5627. cur = llm_build_norm(ctx0, inpL, hparams,
  5628. model.layers[il].attn_norm, NULL,
  5629. LLM_NORM_RMS, cb, il);
  5630. cb(cur, "attn_norm", il);
  5631. // self-attention
  5632. {
  5633. // compute Q and K and RoPE them
  5634. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5635. cb(Qcur, "Qcur", il);
  5636. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5637. cb(Qcur, "Qcur", il);
  5638. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5639. cb(Kcur, "Kcur", il);
  5640. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5641. cb(Kcur, "Kcur", il);
  5642. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5643. cb(Vcur, "Vcur", il);
  5644. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5645. cb(Vcur, "Vcur", il);
  5646. // these nodes are added to the graph together so that they are not reordered
  5647. // by doing so, the number of splits in the graph is reduced
  5648. ggml_build_forward_expand(gf, Qcur);
  5649. ggml_build_forward_expand(gf, Kcur);
  5650. ggml_build_forward_expand(gf, Vcur);
  5651. Qcur = ggml_rope_custom(
  5652. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5653. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5654. ext_factor, attn_factor, beta_fast, beta_slow
  5655. );
  5656. cb(Qcur, "Qcur", il);
  5657. Kcur = ggml_rope_custom(
  5658. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5659. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5660. ext_factor, attn_factor, beta_fast, beta_slow
  5661. );
  5662. cb(Kcur, "Kcur", il);
  5663. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5664. model.layers[il].wo, model.layers[il].bo,
  5665. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5666. cb(cur, "kqv_out", il);
  5667. }
  5668. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5669. cb(ffn_inp, "ffn_inp", il);
  5670. // feed-forward network
  5671. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5672. model.layers[il].ffn_norm, NULL,
  5673. LLM_NORM_RMS, cb, il);
  5674. cb(cur, "ffn_norm", il);
  5675. cur = llm_build_ffn(ctx0, cur,
  5676. model.layers[il].ffn_up, NULL,
  5677. model.layers[il].ffn_gate, NULL,
  5678. model.layers[il].ffn_down, NULL,
  5679. NULL,
  5680. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5681. cb(cur, "ffn_out", il);
  5682. cur = ggml_add(ctx0, cur, ffn_inp);
  5683. cb(cur, "l_out", il);
  5684. // input for next layer
  5685. inpL = cur;
  5686. }
  5687. cur = inpL;
  5688. cur = llm_build_norm(ctx0, cur, hparams,
  5689. model.output_norm, NULL,
  5690. LLM_NORM_RMS, cb, -1);
  5691. cb(cur, "result_norm", -1);
  5692. // lm_head
  5693. cur = ggml_mul_mat(ctx0, model.output, cur);
  5694. cb(cur, "result_output", -1);
  5695. ggml_build_forward_expand(gf, cur);
  5696. return gf;
  5697. }
  5698. struct ggml_cgraph * build_phi2() {
  5699. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5700. const int64_t n_embd_head = hparams.n_embd_head_v;
  5701. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5702. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5703. struct ggml_tensor * cur;
  5704. struct ggml_tensor * attn_norm_output;
  5705. struct ggml_tensor * ffn_output;
  5706. struct ggml_tensor * inpL;
  5707. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5708. cb(inpL, "inp_embd", -1);
  5709. // inp_pos - contains the positions
  5710. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5711. cb(inp_pos, "inp_pos", -1);
  5712. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5713. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5714. cb(KQ_mask, "KQ_mask", -1);
  5715. for (int il = 0; il < n_layer; ++il) {
  5716. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  5717. model.layers[il].attn_norm,
  5718. model.layers[il].attn_norm_b,
  5719. LLM_NORM, cb, il);
  5720. cb(attn_norm_output, "attn_norm", il);
  5721. // self-attention
  5722. {
  5723. struct ggml_tensor * Qcur = nullptr;
  5724. struct ggml_tensor * Kcur = nullptr;
  5725. struct ggml_tensor * Vcur = nullptr;
  5726. if (model.layers[il].wqkv) {
  5727. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  5728. cb(cur, "wqkv", il);
  5729. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5730. cb(cur, "bqkv", il);
  5731. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5732. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5733. 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)));
  5734. } else {
  5735. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  5736. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  5737. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  5738. }
  5739. cb(Qcur, "Qcur", il);
  5740. cb(Kcur, "Kcur", il);
  5741. cb(Vcur, "Vcur", il);
  5742. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5743. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5744. Qcur = ggml_rope_custom(
  5745. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5746. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5747. );
  5748. cb(Qcur, "Qcur", il);
  5749. // with phi2, we scale the Q to avoid precision issues
  5750. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  5751. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  5752. cb(Qcur, "Qcur", il);
  5753. Kcur = ggml_rope_custom(
  5754. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5755. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5756. );
  5757. cb(Kcur, "Kcur", il);
  5758. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5759. model.layers[il].wo, model.layers[il].bo,
  5760. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  5761. cb(cur, "kqv_out", il);
  5762. }
  5763. // FF
  5764. {
  5765. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  5766. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5767. NULL, NULL,
  5768. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5769. NULL,
  5770. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5771. cb(ffn_output, "ffn_out", il);
  5772. }
  5773. cur = ggml_add(ctx0, cur, ffn_output);
  5774. cb(cur, "l_out", il);
  5775. cur = ggml_add(ctx0, cur, inpL);
  5776. cb(cur, "l_out", il);
  5777. inpL = cur;
  5778. }
  5779. cur = llm_build_norm(ctx0, inpL, hparams,
  5780. model.output_norm,
  5781. model.output_norm_b,
  5782. LLM_NORM, cb, -1);
  5783. cb(cur, "result_norm", -1);
  5784. cur = ggml_mul_mat(ctx0, model.output, cur);
  5785. cb(cur, "result_output_no_bias", -1);
  5786. cur = ggml_add(ctx0, cur, model.output_b);
  5787. cb(cur, "result_output", -1);
  5788. ggml_build_forward_expand(gf, cur);
  5789. return gf;
  5790. }
  5791. struct ggml_cgraph * build_plamo() {
  5792. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  5793. const int64_t n_embd_head = hparams.n_embd_head_v;
  5794. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5795. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5796. struct ggml_tensor * cur;
  5797. struct ggml_tensor * inpL;
  5798. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5799. cb(inpL, "inp_embd", -1);
  5800. // inp_pos - contains the positions
  5801. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5802. cb(inp_pos, "inp_pos", -1);
  5803. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5804. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5805. cb(KQ_mask, "KQ_mask", -1);
  5806. for (int il = 0; il < n_layer; ++il) {
  5807. // norm
  5808. cur = llm_build_norm(ctx0, inpL, hparams,
  5809. model.layers[il].attn_norm, NULL,
  5810. LLM_NORM_RMS, cb, il);
  5811. cb(cur, "attn_norm", il);
  5812. struct ggml_tensor * attention_norm = cur;
  5813. // self-attention
  5814. {
  5815. // compute Q and K and RoPE them
  5816. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5817. cb(Qcur, "Qcur", il);
  5818. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5819. cb(Kcur, "Kcur", il);
  5820. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5821. cb(Vcur, "Vcur", il);
  5822. Qcur = ggml_rope_custom(
  5823. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos,
  5824. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5825. ext_factor, attn_factor, beta_fast, beta_slow);
  5826. cb(Qcur, "Qcur", il);
  5827. Kcur = ggml_rope_custom(
  5828. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos,
  5829. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5830. ext_factor, attn_factor, beta_fast, beta_slow);
  5831. cb(Kcur, "Kcur", il);
  5832. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5833. model.layers[il].wo, NULL,
  5834. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5835. cb(cur, "kqv_out", il);
  5836. }
  5837. struct ggml_tensor * sa_out = cur;
  5838. cur = attention_norm;
  5839. // feed-forward network
  5840. {
  5841. cur = llm_build_ffn(ctx0, cur,
  5842. model.layers[il].ffn_up, NULL,
  5843. model.layers[il].ffn_gate, NULL,
  5844. model.layers[il].ffn_down, NULL,
  5845. NULL,
  5846. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5847. cb(cur, "ffn_out", il);
  5848. }
  5849. cur = ggml_add(ctx0, cur, sa_out);
  5850. cb(cur, "l_out", il);
  5851. cur = ggml_add(ctx0, cur, inpL);
  5852. cb(cur, "l_out", il);
  5853. // input for next layer
  5854. inpL = cur;
  5855. }
  5856. cur = inpL;
  5857. cur = llm_build_norm(ctx0, cur, hparams,
  5858. model.output_norm, NULL,
  5859. LLM_NORM_RMS, cb, -1);
  5860. cb(cur, "result_norm", -1);
  5861. // lm_head
  5862. cur = ggml_mul_mat(ctx0, model.output, cur);
  5863. cb(cur, "result_output", -1);
  5864. ggml_build_forward_expand(gf, cur);
  5865. return gf;
  5866. }
  5867. struct ggml_cgraph * build_gpt2() {
  5868. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5869. const int64_t n_embd_head = hparams.n_embd_head_v;
  5870. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5871. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5872. struct ggml_tensor * cur;
  5873. struct ggml_tensor * pos;
  5874. struct ggml_tensor * inpL;
  5875. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5876. cb(inpL, "inp_embd", -1);
  5877. // inp_pos - contains the positions
  5878. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5879. cb(inp_pos, "inp_pos", -1);
  5880. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5881. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5882. cb(KQ_mask, "KQ_mask", -1);
  5883. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  5884. cb(pos, "pos_embd", -1);
  5885. inpL = ggml_add(ctx0, inpL, pos);
  5886. cb(inpL, "inpL", -1);
  5887. for (int il = 0; il < n_layer; ++il) {
  5888. cur = llm_build_norm(ctx0, inpL, hparams,
  5889. model.layers[il].attn_norm,
  5890. model.layers[il].attn_norm_b,
  5891. LLM_NORM, cb, il);
  5892. cb(cur, "attn_norm", il);
  5893. // self-attention
  5894. {
  5895. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5896. cb(cur, "wqkv", il);
  5897. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5898. cb(cur, "bqkv", il);
  5899. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5900. 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)));
  5901. 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)));
  5902. cb(Qcur, "Qcur", il);
  5903. cb(Kcur, "Kcur", il);
  5904. cb(Vcur, "Vcur", il);
  5905. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5906. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5907. model.layers[il].wo, model.layers[il].bo,
  5908. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5909. cb(cur, "kqv_out", il);
  5910. }
  5911. // add the input
  5912. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5913. cb(ffn_inp, "ffn_inp", il);
  5914. // FF
  5915. {
  5916. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5917. model.layers[il].ffn_norm,
  5918. model.layers[il].ffn_norm_b,
  5919. LLM_NORM, cb, il);
  5920. cb(cur, "ffn_norm", il);
  5921. cur = llm_build_ffn(ctx0, cur,
  5922. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5923. NULL, NULL,
  5924. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5925. NULL,
  5926. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5927. cb(cur, "ffn_out", il);
  5928. }
  5929. inpL = ggml_add(ctx0, cur, ffn_inp);
  5930. cb(inpL, "l_out", il);
  5931. }
  5932. cur = llm_build_norm(ctx0, inpL, hparams,
  5933. model.output_norm,
  5934. model.output_norm_b,
  5935. LLM_NORM, cb, -1);
  5936. cb(cur, "result_norm", -1);
  5937. cur = ggml_mul_mat(ctx0, model.output, cur);
  5938. cb(cur, "result_output", -1);
  5939. ggml_build_forward_expand(gf, cur);
  5940. return gf;
  5941. }
  5942. struct ggml_cgraph * build_codeshell() {
  5943. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5944. const int64_t n_embd_head = hparams.n_embd_head_v;
  5945. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5946. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5947. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5948. struct ggml_tensor * cur;
  5949. struct ggml_tensor * inpL;
  5950. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5951. cb(inpL, "inp_embd", -1);
  5952. // inp_pos - contains the positions
  5953. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5954. cb(inp_pos, "inp_pos", -1);
  5955. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5956. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5957. cb(KQ_mask, "KQ_mask", -1);
  5958. for (int il = 0; il < n_layer; ++il) {
  5959. cur = llm_build_norm(ctx0, inpL, hparams,
  5960. model.layers[il].attn_norm,
  5961. model.layers[il].attn_norm_b,
  5962. LLM_NORM, cb, il);
  5963. cb(cur, "attn_norm", il);
  5964. // self-attention
  5965. {
  5966. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5967. cb(cur, "wqkv", il);
  5968. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5969. cb(cur, "bqkv", il);
  5970. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5971. 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)));
  5972. 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)));
  5973. cb(tmpq, "tmpq", il);
  5974. cb(tmpk, "tmpk", il);
  5975. cb(Vcur, "Vcur", il);
  5976. struct ggml_tensor * Qcur = ggml_rope_custom(
  5977. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  5978. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5979. ext_factor, attn_factor, beta_fast, beta_slow
  5980. );
  5981. cb(Qcur, "Qcur", il);
  5982. struct ggml_tensor * Kcur = ggml_rope_custom(
  5983. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5984. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5985. ext_factor, attn_factor, beta_fast, beta_slow
  5986. );
  5987. cb(Kcur, "Kcur", il);
  5988. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5989. model.layers[il].wo, model.layers[il].bo,
  5990. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5991. cb(cur, "kqv_out", il);
  5992. }
  5993. // add the input
  5994. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5995. cb(ffn_inp, "ffn_inp", il);
  5996. // FF
  5997. {
  5998. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5999. model.layers[il].ffn_norm,
  6000. model.layers[il].ffn_norm_b,
  6001. LLM_NORM, cb, il);
  6002. cb(cur, "ffn_norm", il);
  6003. cur = llm_build_ffn(ctx0, cur,
  6004. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6005. NULL, NULL,
  6006. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6007. NULL,
  6008. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6009. cb(cur, "ffn_out", il);
  6010. }
  6011. inpL = ggml_add(ctx0, cur, ffn_inp);
  6012. cb(inpL, "l_out", il);
  6013. }
  6014. cur = llm_build_norm(ctx0, inpL, hparams,
  6015. model.output_norm,
  6016. model.output_norm_b,
  6017. LLM_NORM, cb, -1);
  6018. cb(cur, "result_norm", -1);
  6019. cur = ggml_mul_mat(ctx0, model.output, cur);
  6020. cb(cur, "result_output", -1);
  6021. ggml_build_forward_expand(gf, cur);
  6022. return gf;
  6023. }
  6024. struct ggml_cgraph * build_orion() {
  6025. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6026. const int64_t n_embd_head = hparams.n_embd_head_v;
  6027. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6028. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6029. struct ggml_tensor * cur;
  6030. struct ggml_tensor * inpL;
  6031. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  6032. cb(inpL, "inp_embd", -1);
  6033. // inp_pos - contains the positions
  6034. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  6035. cb(inp_pos, "inp_pos", -1);
  6036. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6037. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  6038. cb(KQ_mask, "KQ_mask", -1);
  6039. for (int il = 0; il < n_layer; ++il) {
  6040. struct ggml_tensor * inpSA = inpL;
  6041. // norm
  6042. cur = llm_build_norm(ctx0, inpL, hparams,
  6043. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  6044. LLM_NORM, cb, il);
  6045. cb(cur, "attn_norm", il);
  6046. // self-attention
  6047. {
  6048. // compute Q and K and RoPE them
  6049. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6050. cb(Qcur, "Qcur", il);
  6051. // if (model.layers[il].bq) {
  6052. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6053. // cb(Qcur, "Qcur", il);
  6054. // }
  6055. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6056. cb(Kcur, "Kcur", il);
  6057. // if (model.layers[il].bk) {
  6058. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6059. // cb(Kcur, "Kcur", il);
  6060. // }
  6061. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6062. cb(Vcur, "Vcur", il);
  6063. // if (model.layers[il].bv) {
  6064. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6065. // cb(Vcur, "Vcur", il);
  6066. // }
  6067. Qcur = ggml_rope_custom(
  6068. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6069. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6070. ext_factor, attn_factor, beta_fast, beta_slow
  6071. );
  6072. cb(Qcur, "Qcur", il);
  6073. Kcur = ggml_rope_custom(
  6074. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6075. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6076. ext_factor, attn_factor, beta_fast, beta_slow
  6077. );
  6078. cb(Kcur, "Kcur", il);
  6079. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6080. model.layers[il].wo, NULL,
  6081. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6082. cb(cur, "kqv_out", il);
  6083. }
  6084. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6085. cb(ffn_inp, "ffn_inp", il);
  6086. // feed-forward network
  6087. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6088. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  6089. LLM_NORM, cb, il);
  6090. cb(cur, "ffn_norm", il);
  6091. cur = llm_build_ffn(ctx0, cur,
  6092. model.layers[il].ffn_up, NULL,
  6093. model.layers[il].ffn_gate, NULL,
  6094. model.layers[il].ffn_down, NULL,
  6095. NULL,
  6096. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6097. cb(cur, "ffn_out", il);
  6098. cur = ggml_add(ctx0, cur, ffn_inp);
  6099. cb(cur, "l_out", il);
  6100. // input for next layer
  6101. inpL = cur;
  6102. }
  6103. cur = inpL;
  6104. cur = llm_build_norm(ctx0, cur, hparams,
  6105. model.output_norm, model.output_norm_b,
  6106. LLM_NORM, cb, -1);
  6107. cb(cur, "result_norm", -1);
  6108. // lm_head
  6109. cur = ggml_mul_mat(ctx0, model.output, cur);
  6110. cb(cur, "result_output", -1);
  6111. ggml_build_forward_expand(gf, cur);
  6112. return gf;
  6113. }
  6114. struct ggml_cgraph * build_internlm2() {
  6115. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6116. const int64_t n_embd_head = hparams.n_embd_head_v;
  6117. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6118. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6119. struct ggml_tensor * cur;
  6120. struct ggml_tensor * inpL;
  6121. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  6122. cb(inpL, "inp_embd", -1);
  6123. // inp_pos - contains the positions
  6124. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  6125. cb(inp_pos, "inp_pos", -1);
  6126. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6127. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  6128. cb(KQ_mask, "KQ_mask", -1);
  6129. for (int il = 0; il < n_layer; ++il) {
  6130. struct ggml_tensor * inpSA = inpL;
  6131. // norm
  6132. cur = llm_build_norm(ctx0, inpL, hparams,
  6133. model.layers[il].attn_norm, NULL,
  6134. LLM_NORM_RMS, cb, il);
  6135. cb(cur, "attn_norm", il);
  6136. // self-attention
  6137. {
  6138. // compute Q and K and RoPE them
  6139. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6140. cb(Qcur, "Qcur", il);
  6141. if (model.layers[il].bq) {
  6142. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6143. cb(Qcur, "Qcur", il);
  6144. }
  6145. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6146. cb(Kcur, "Kcur", il);
  6147. if (model.layers[il].bk) {
  6148. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6149. cb(Kcur, "Kcur", il);
  6150. }
  6151. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6152. cb(Vcur, "Vcur", il);
  6153. if (model.layers[il].bv) {
  6154. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6155. cb(Vcur, "Vcur", il);
  6156. }
  6157. Qcur = ggml_rope_custom(
  6158. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6159. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6160. ext_factor, attn_factor, beta_fast, beta_slow
  6161. );
  6162. cb(Qcur, "Qcur", il);
  6163. Kcur = ggml_rope_custom(
  6164. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6165. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6166. ext_factor, attn_factor, beta_fast, beta_slow
  6167. );
  6168. cb(Kcur, "Kcur", il);
  6169. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6170. model.layers[il].wo, model.layers[il].bo,
  6171. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6172. cb(cur, "kqv_out", il);
  6173. }
  6174. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6175. cb(ffn_inp, "ffn_inp", il);
  6176. // feed-forward network
  6177. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6178. model.layers[il].ffn_norm, NULL,
  6179. LLM_NORM_RMS, cb, il);
  6180. cb(cur, "ffn_norm", il);
  6181. cur = llm_build_ffn(ctx0, cur,
  6182. model.layers[il].ffn_up, NULL,
  6183. model.layers[il].ffn_gate, NULL,
  6184. model.layers[il].ffn_down, NULL,
  6185. NULL,
  6186. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6187. cb(cur, "ffn_out", il);
  6188. cur = ggml_add(ctx0, cur, ffn_inp);
  6189. cb(cur, "l_out", il);
  6190. // input for next layer
  6191. inpL = cur;
  6192. }
  6193. cur = inpL;
  6194. cur = llm_build_norm(ctx0, cur, hparams,
  6195. model.output_norm, NULL,
  6196. LLM_NORM_RMS, cb, -1);
  6197. cb(cur, "result_norm", -1);
  6198. // lm_head
  6199. cur = ggml_mul_mat(ctx0, model.output, cur);
  6200. cb(cur, "result_output", -1);
  6201. ggml_build_forward_expand(gf, cur);
  6202. return gf;
  6203. }
  6204. // ref: https://arxiv.org/abs/2203.03466
  6205. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  6206. // based on the original build_llama() function
  6207. struct ggml_cgraph * build_minicpm() {
  6208. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6209. const int64_t n_embd_head = hparams.n_embd_head_v;
  6210. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6211. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6212. const int64_t n_embd = hparams.n_embd;
  6213. //TODO: if the model varies, these parameters need to be read from the model
  6214. const int64_t n_embd_base = 256;
  6215. const float scale_embd = 12.0f;
  6216. const float scale_depth = 1.4f;
  6217. struct ggml_tensor * cur;
  6218. struct ggml_tensor * inpL;
  6219. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  6220. cb(inpL, "inp_embd", -1);
  6221. // scale the input embeddings
  6222. inpL = ggml_scale(ctx0, inpL, scale_embd);
  6223. cb(inpL, "inp_scaled", -1);
  6224. // inp_pos - contains the positions
  6225. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  6226. cb(inp_pos, "inp_pos", -1);
  6227. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6228. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  6229. cb(KQ_mask, "KQ_mask", -1);
  6230. for (int il = 0; il < n_layer; ++il) {
  6231. struct ggml_tensor * inpSA = inpL;
  6232. // norm
  6233. cur = llm_build_norm(ctx0, inpL, hparams,
  6234. model.layers[il].attn_norm, NULL,
  6235. LLM_NORM_RMS, cb, il);
  6236. cb(cur, "attn_norm", il);
  6237. // self-attention
  6238. {
  6239. // compute Q and K and RoPE them
  6240. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6241. cb(Qcur, "Qcur", il);
  6242. if (model.layers[il].bq) {
  6243. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6244. cb(Qcur, "Qcur", il);
  6245. }
  6246. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6247. cb(Kcur, "Kcur", il);
  6248. if (model.layers[il].bk) {
  6249. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6250. cb(Kcur, "Kcur", il);
  6251. }
  6252. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6253. cb(Vcur, "Vcur", il);
  6254. if (model.layers[il].bv) {
  6255. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6256. cb(Vcur, "Vcur", il);
  6257. }
  6258. Qcur = ggml_rope_custom(
  6259. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6260. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6261. ext_factor, attn_factor, beta_fast, beta_slow
  6262. );
  6263. cb(Qcur, "Qcur", il);
  6264. Kcur = ggml_rope_custom(
  6265. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6266. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6267. ext_factor, attn_factor, beta_fast, beta_slow
  6268. );
  6269. cb(Kcur, "Kcur", il);
  6270. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6271. model.layers[il].wo, model.layers[il].bo,
  6272. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6273. cb(cur, "kqv_out", il);
  6274. }
  6275. // scale_res - scale the hidden states for residual connection
  6276. const float scale_res = scale_depth/sqrtf(float(n_layer));
  6277. cur = ggml_scale(ctx0, cur, scale_res);
  6278. cb(cur, "hidden_scaled", -1);
  6279. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6280. cb(ffn_inp, "ffn_inp", il);
  6281. // feed-forward network
  6282. {
  6283. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6284. model.layers[il].ffn_norm, NULL,
  6285. LLM_NORM_RMS, cb, il);
  6286. cb(cur, "ffn_norm", il);
  6287. cur = llm_build_ffn(ctx0, cur,
  6288. model.layers[il].ffn_up, NULL,
  6289. model.layers[il].ffn_gate, NULL,
  6290. model.layers[il].ffn_down, NULL,
  6291. NULL,
  6292. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6293. cb(cur, "ffn_out", il);
  6294. }
  6295. // scale the hidden states for residual connection
  6296. cur = ggml_scale(ctx0, cur, scale_res);
  6297. cb(cur, "hidden_scaled_ffn", -1);
  6298. cur = ggml_add(ctx0, cur, ffn_inp);
  6299. cb(cur, "l_out", il);
  6300. // input for next layer
  6301. inpL = cur;
  6302. }
  6303. cur = inpL;
  6304. cur = llm_build_norm(ctx0, cur, hparams,
  6305. model.output_norm, NULL,
  6306. LLM_NORM_RMS, cb, -1);
  6307. cb(cur, "result_norm", -1);
  6308. // lm_head scaling
  6309. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  6310. cur = ggml_scale(ctx0, cur, scale_lmhead);
  6311. cb(cur, "lmhead_scaling", -1);
  6312. // lm_head
  6313. cur = ggml_mul_mat(ctx0, model.tok_embd, cur);
  6314. cb(cur, "result_output", -1);
  6315. ggml_build_forward_expand(gf, cur);
  6316. return gf;
  6317. }
  6318. struct ggml_cgraph * build_gemma() {
  6319. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6320. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  6321. struct ggml_tensor * cur;
  6322. struct ggml_tensor * inpL;
  6323. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  6324. cb(inpL, "inp_embd", -1);
  6325. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  6326. cb(inpL, "inp_scaled", -1);
  6327. // inp_pos - contains the positions
  6328. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  6329. cb(inp_pos, "inp_pos", -1);
  6330. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6331. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  6332. cb(KQ_mask, "KQ_mask", -1);
  6333. for (int il = 0; il < n_layer; ++il) {
  6334. // norm
  6335. cur = llm_build_norm(ctx0, inpL, hparams,
  6336. model.layers[il].attn_norm, NULL,
  6337. LLM_NORM_RMS, cb, il);
  6338. cb(cur, "attn_norm", il);
  6339. // self-attention
  6340. {
  6341. // compute Q and K and RoPE them
  6342. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6343. cb(Qcur, "Qcur", il);
  6344. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6345. cb(Kcur, "Kcur", il);
  6346. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6347. cb(Vcur, "Vcur", il);
  6348. Qcur = ggml_rope_custom(
  6349. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos,
  6350. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6351. ext_factor, attn_factor, beta_fast, beta_slow);
  6352. cb(Qcur, "Qcur", il);
  6353. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  6354. cb(Qcur, "Qcur_scaled", il);
  6355. Kcur = ggml_rope_custom(
  6356. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos,
  6357. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6358. ext_factor, attn_factor, beta_fast, beta_slow);
  6359. cb(Kcur, "Kcur", il);
  6360. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6361. model.layers[il].wo, NULL,
  6362. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  6363. cb(cur, "kqv_out", il);
  6364. }
  6365. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  6366. cb(sa_out, "sa_out", il);
  6367. cur = llm_build_norm(ctx0, sa_out, hparams,
  6368. model.layers[il].ffn_norm, NULL,
  6369. LLM_NORM_RMS, cb, il);
  6370. cb(cur, "ffn_norm", il);
  6371. // feed-forward network
  6372. {
  6373. cur = llm_build_ffn(ctx0, cur,
  6374. model.layers[il].ffn_up, NULL,
  6375. model.layers[il].ffn_gate, NULL,
  6376. model.layers[il].ffn_down, NULL,
  6377. NULL,
  6378. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  6379. cb(cur, "ffn_out", il);
  6380. }
  6381. cur = ggml_add(ctx0, cur, sa_out);
  6382. cb(cur, "l_out", il);
  6383. // input for next layer
  6384. inpL = cur;
  6385. }
  6386. cur = inpL;
  6387. cur = llm_build_norm(ctx0, cur, hparams,
  6388. model.output_norm, NULL,
  6389. LLM_NORM_RMS, cb, -1);
  6390. cb(cur, "result_norm", -1);
  6391. // lm_head
  6392. cur = ggml_mul_mat(ctx0, model.output, cur);
  6393. cb(cur, "result_output", -1);
  6394. ggml_build_forward_expand(gf, cur);
  6395. return gf;
  6396. }
  6397. struct ggml_cgraph * build_starcoder2() {
  6398. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6399. const int64_t n_embd_head = hparams.n_embd_head_v;
  6400. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6401. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6402. struct ggml_tensor * cur;
  6403. struct ggml_tensor * inpL;
  6404. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  6405. cb(inpL, "inp_embd", -1);
  6406. // inp_pos - contains the positions
  6407. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  6408. cb(inp_pos, "inp_pos", -1);
  6409. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6410. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  6411. cb(KQ_mask, "KQ_mask", -1);
  6412. for (int il = 0; il < n_layer; ++il) {
  6413. struct ggml_tensor * inpSA = inpL;
  6414. // norm
  6415. cur = llm_build_norm(ctx0, inpL, hparams,
  6416. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  6417. LLM_NORM, cb, il);
  6418. cb(cur, "attn_norm", il);
  6419. // self-attention
  6420. {
  6421. // compute Q and K and RoPE them
  6422. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6423. cb(Qcur, "Qcur", il);
  6424. if (model.layers[il].bq) {
  6425. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6426. cb(Qcur, "Qcur", il);
  6427. }
  6428. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6429. cb(Kcur, "Kcur", il);
  6430. if (model.layers[il].bk) {
  6431. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6432. cb(Kcur, "Kcur", il);
  6433. }
  6434. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6435. cb(Vcur, "Vcur", il);
  6436. if (model.layers[il].bv) {
  6437. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6438. cb(Vcur, "Vcur", il);
  6439. }
  6440. Qcur = ggml_rope_custom(
  6441. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6442. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6443. ext_factor, attn_factor, beta_fast, beta_slow
  6444. );
  6445. cb(Qcur, "Qcur", il);
  6446. Kcur = ggml_rope_custom(
  6447. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6448. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6449. ext_factor, attn_factor, beta_fast, beta_slow
  6450. );
  6451. cb(Kcur, "Kcur", il);
  6452. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6453. model.layers[il].wo, model.layers[il].bo,
  6454. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6455. cb(cur, "kqv_out", il);
  6456. }
  6457. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6458. cb(ffn_inp, "ffn_inp", il);
  6459. // feed-forward network
  6460. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6461. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  6462. LLM_NORM, cb, il);
  6463. cb(cur, "ffn_norm", il);
  6464. cur = llm_build_ffn(ctx0, cur,
  6465. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6466. NULL, NULL,
  6467. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6468. NULL,
  6469. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6470. cb(cur, "ffn_out", il);
  6471. cur = ggml_add(ctx0, cur, ffn_inp);
  6472. cb(cur, "l_out", il);
  6473. // input for next layer
  6474. inpL = cur;
  6475. }
  6476. cur = inpL;
  6477. cur = llm_build_norm(ctx0, cur, hparams,
  6478. model.output_norm, model.output_norm_b,
  6479. LLM_NORM, cb, -1);
  6480. cb(cur, "result_norm", -1);
  6481. // lm_head
  6482. cur = ggml_mul_mat(ctx0, model.output, cur);
  6483. cb(cur, "result_output", -1);
  6484. ggml_build_forward_expand(gf, cur);
  6485. return gf;
  6486. }
  6487. };
  6488. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  6489. llama_batch dummy;
  6490. dummy.n_tokens = 0;
  6491. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  6492. struct llm_build_context llm(lctx, dummy, cb, false);
  6493. llm.init();
  6494. struct ggml_cgraph * result = llm.build_defrag(ids);
  6495. llm.free();
  6496. return result;
  6497. }
  6498. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  6499. llama_batch dummy;
  6500. dummy.n_tokens = 0;
  6501. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  6502. struct llm_build_context llm(lctx, dummy, cb, false);
  6503. llm.init();
  6504. struct ggml_cgraph * result = llm.build_k_shift();
  6505. llm.free();
  6506. return result;
  6507. }
  6508. static struct ggml_cgraph * llama_build_graph(
  6509. llama_context & lctx,
  6510. const llama_batch & batch,
  6511. bool worst_case) {
  6512. const auto & model = lctx.model;
  6513. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  6514. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  6515. if (il >= 0) {
  6516. ggml_format_name(cur, "%s-%d", name, il);
  6517. } else {
  6518. ggml_set_name(cur, name);
  6519. }
  6520. if (!lctx.cparams.offload_kqv) {
  6521. if (strcmp(name, "kqv_merged_cont") == 0) {
  6522. // all nodes between the KV store and the attention output are run on the CPU
  6523. ggml_backend_sched_set_node_backend(lctx.sched, cur, lctx.backend_cpu);
  6524. }
  6525. }
  6526. };
  6527. struct ggml_cgraph * result = NULL;
  6528. struct llm_build_context llm(lctx, batch, cb, worst_case);
  6529. llm.init();
  6530. switch (model.arch) {
  6531. case LLM_ARCH_LLAMA:
  6532. {
  6533. result = llm.build_llama();
  6534. } break;
  6535. case LLM_ARCH_BAICHUAN:
  6536. {
  6537. result = llm.build_baichuan();
  6538. } break;
  6539. case LLM_ARCH_FALCON:
  6540. {
  6541. result = llm.build_falcon();
  6542. } break;
  6543. case LLM_ARCH_STARCODER:
  6544. {
  6545. result = llm.build_starcoder();
  6546. } break;
  6547. case LLM_ARCH_PERSIMMON:
  6548. {
  6549. result = llm.build_persimmon();
  6550. } break;
  6551. case LLM_ARCH_REFACT:
  6552. {
  6553. result = llm.build_refact();
  6554. } break;
  6555. case LLM_ARCH_BERT:
  6556. case LLM_ARCH_NOMIC_BERT:
  6557. {
  6558. result = llm.build_bert();
  6559. } break;
  6560. case LLM_ARCH_BLOOM:
  6561. {
  6562. result = llm.build_bloom();
  6563. } break;
  6564. case LLM_ARCH_MPT:
  6565. {
  6566. result = llm.build_mpt();
  6567. } break;
  6568. case LLM_ARCH_STABLELM:
  6569. {
  6570. result = llm.build_stablelm();
  6571. } break;
  6572. case LLM_ARCH_QWEN:
  6573. {
  6574. result = llm.build_qwen();
  6575. } break;
  6576. case LLM_ARCH_QWEN2:
  6577. {
  6578. result = llm.build_qwen2();
  6579. } break;
  6580. case LLM_ARCH_PHI2:
  6581. {
  6582. result = llm.build_phi2();
  6583. } break;
  6584. case LLM_ARCH_PLAMO:
  6585. {
  6586. result = llm.build_plamo();
  6587. } break;
  6588. case LLM_ARCH_GPT2:
  6589. {
  6590. result = llm.build_gpt2();
  6591. } break;
  6592. case LLM_ARCH_CODESHELL:
  6593. {
  6594. result = llm.build_codeshell();
  6595. } break;
  6596. case LLM_ARCH_ORION:
  6597. {
  6598. result = llm.build_orion();
  6599. } break;
  6600. case LLM_ARCH_INTERNLM2:
  6601. {
  6602. result = llm.build_internlm2();
  6603. } break;
  6604. case LLM_ARCH_MINICPM:
  6605. {
  6606. result = llm.build_minicpm();
  6607. } break;
  6608. case LLM_ARCH_GEMMA:
  6609. {
  6610. result = llm.build_gemma();
  6611. } break;
  6612. case LLM_ARCH_STARCODER2:
  6613. {
  6614. result = llm.build_starcoder2();
  6615. } break;
  6616. default:
  6617. GGML_ASSERT(false);
  6618. }
  6619. llm.free();
  6620. return result;
  6621. }
  6622. static void llama_set_k_shift(llama_context & lctx) {
  6623. const auto & cparams = lctx.cparams;
  6624. const int64_t n_ctx = cparams.n_ctx;
  6625. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  6626. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  6627. for (int i = 0; i < n_ctx; ++i) {
  6628. data[i] = lctx.kv_self.cells[i].delta;
  6629. }
  6630. }
  6631. static void llama_set_inputs(llama_context & lctx, const llama_batch & batch) {
  6632. //
  6633. // set input data
  6634. //
  6635. const auto & hparams = lctx.model.hparams;
  6636. const auto & cparams = lctx.cparams;
  6637. const auto & kv_self = lctx.kv_self;
  6638. if (batch.token) {
  6639. const int64_t n_tokens = batch.n_tokens;
  6640. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  6641. }
  6642. if (batch.embd) {
  6643. const int64_t n_embd = hparams.n_embd;
  6644. const int64_t n_tokens = batch.n_tokens;
  6645. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  6646. }
  6647. if (batch.pos) {
  6648. const int64_t n_tokens = batch.n_tokens;
  6649. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  6650. }
  6651. if (hparams.causal_attn) {
  6652. const int64_t n_kv = kv_self.n;
  6653. const int64_t n_tokens = batch.n_tokens;
  6654. assert(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  6655. float * data = (float *) lctx.inp_KQ_mask->data;
  6656. for (int h = 0; h < 1; ++h) {
  6657. for (int j = 0; j < n_tokens; ++j) {
  6658. const llama_pos pos = batch.pos[j];
  6659. const llama_seq_id seq_id = batch.seq_id[j][0];
  6660. for (int i = 0; i < n_kv; ++i) {
  6661. float f;
  6662. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  6663. f = -INFINITY;
  6664. } else {
  6665. f = 0.0f;
  6666. }
  6667. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  6668. }
  6669. }
  6670. }
  6671. } else {
  6672. // non-causal attention attends only the tokens within the batch (i.e. the KV cache is not used)
  6673. const int64_t n_tokens = batch.n_tokens;
  6674. assert(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  6675. float * data = (float *) lctx.inp_KQ_mask->data;
  6676. for (int h = 0; h < 1; ++h) {
  6677. for (int j = 0; j < n_tokens; ++j) {
  6678. const llama_seq_id seq_id = batch.seq_id[j][0];
  6679. for (int i = 0; i < n_tokens; ++i) {
  6680. float f = -INFINITY;
  6681. for (int s = 0; s < batch.n_seq_id[i]; ++s) {
  6682. if (batch.seq_id[i][s] == seq_id) {
  6683. f = 0.0f;
  6684. break;
  6685. }
  6686. }
  6687. data[h*(n_tokens*n_tokens) + j*n_tokens + i] = f;
  6688. }
  6689. }
  6690. }
  6691. }
  6692. if (hparams.need_kq_pos) {
  6693. const int64_t n_kv = kv_self.n;
  6694. assert(ggml_backend_buffer_is_host(lctx.inp_KQ_pos->buffer));
  6695. float * data = (float *) lctx.inp_KQ_pos->data;
  6696. for (int i = 0; i < n_kv; ++i) {
  6697. data[i] = float(lctx.kv_self.cells[i].pos);
  6698. }
  6699. }
  6700. if (cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  6701. const int64_t n_tokens = batch.n_tokens;
  6702. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  6703. float * data = (float *) lctx.inp_mean->data;
  6704. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  6705. std::vector<uint64_t> sum(n_tokens, 0);
  6706. for (int i = 0; i < n_tokens; ++i) {
  6707. const llama_seq_id seq_id = batch.seq_id[i][0];
  6708. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
  6709. sum[seq_id] += 1;
  6710. }
  6711. std::vector<float> div(n_tokens, 0.0f);
  6712. for (int i = 0; i < n_tokens; ++i) {
  6713. const uint64_t s = sum[i];
  6714. if (s > 0) {
  6715. div[i] = 1.0f/float(s);
  6716. }
  6717. }
  6718. for (int i = 0; i < n_tokens; ++i) {
  6719. const llama_seq_id seq_id = batch.seq_id[i][0];
  6720. data[seq_id*n_tokens + i] = div[seq_id];
  6721. }
  6722. }
  6723. if (cparams.pooling_type == LLAMA_POOLING_TYPE_CLS) {
  6724. const int64_t n_tokens = batch.n_tokens;
  6725. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  6726. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  6727. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  6728. for (int i = 0; i < n_tokens; ++i) {
  6729. const llama_seq_id seq_id = batch.seq_id[i][0];
  6730. const llama_pos pos = batch.pos[i];
  6731. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS");
  6732. if (pos == 0) {
  6733. data[seq_id] = i;
  6734. }
  6735. }
  6736. }
  6737. }
  6738. static void llama_graph_compute(
  6739. llama_context & lctx,
  6740. ggml_cgraph * gf,
  6741. int n_threads) {
  6742. #ifdef GGML_USE_MPI
  6743. const int64_t n_layer = lctx.model.hparams.n_layer;
  6744. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  6745. #endif
  6746. #ifdef GGML_USE_METAL
  6747. if (ggml_backend_is_metal(lctx.backend_metal)) {
  6748. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  6749. }
  6750. #endif
  6751. if (lctx.backend_cpu != nullptr) {
  6752. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  6753. ggml_backend_cpu_set_abort_callback(lctx.backend_cpu, lctx.abort_callback, lctx.abort_callback_data);
  6754. }
  6755. ggml_backend_sched_graph_compute(lctx.sched, gf);
  6756. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  6757. #ifdef GGML_USE_MPI
  6758. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  6759. #endif
  6760. }
  6761. // decode a batch of tokens by evaluating the transformer
  6762. //
  6763. // - lctx: llama context
  6764. // - batch: batch to evaluate
  6765. //
  6766. // return 0 on success
  6767. // return positive int on warning
  6768. // return negative int on error
  6769. //
  6770. static int llama_decode_internal(
  6771. llama_context & lctx,
  6772. llama_batch batch) {
  6773. const uint32_t n_tokens = batch.n_tokens;
  6774. if (n_tokens == 0) {
  6775. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  6776. return -1;
  6777. }
  6778. const auto & model = lctx.model;
  6779. const auto & hparams = model.hparams;
  6780. const auto & cparams = lctx.cparams;
  6781. const auto n_batch = cparams.n_batch;
  6782. GGML_ASSERT(n_tokens <= n_batch);
  6783. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  6784. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  6785. const int64_t t_start_us = ggml_time_us();
  6786. #ifdef GGML_USE_MPI
  6787. // TODO: needs fix after #3228
  6788. GGML_ASSERT(false && "not implemented");
  6789. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  6790. #endif
  6791. GGML_ASSERT(n_threads > 0);
  6792. auto & kv_self = lctx.kv_self;
  6793. const int64_t n_embd = hparams.n_embd;
  6794. const int64_t n_vocab = hparams.n_vocab;
  6795. // helpers for smoother batch API transition
  6796. // after deprecating the llama_eval calls, these will be removed
  6797. std::vector<llama_pos> pos;
  6798. std::vector<int32_t> n_seq_id;
  6799. std::vector<llama_seq_id *> seq_id_arr;
  6800. std::vector<std::vector<llama_seq_id>> seq_id;
  6801. if (batch.pos == nullptr) {
  6802. pos.resize(n_tokens);
  6803. for (uint32_t i = 0; i < n_tokens; i++) {
  6804. pos[i] = batch.all_pos_0 + i*batch.all_pos_1;
  6805. }
  6806. batch.pos = pos.data();
  6807. }
  6808. if (batch.seq_id == nullptr) {
  6809. n_seq_id.resize(n_tokens);
  6810. seq_id.resize(n_tokens);
  6811. seq_id_arr.resize(n_tokens);
  6812. for (uint32_t i = 0; i < n_tokens; i++) {
  6813. n_seq_id[i] = 1;
  6814. seq_id[i].resize(1);
  6815. seq_id[i][0] = batch.all_seq_id;
  6816. seq_id_arr[i] = seq_id[i].data();
  6817. }
  6818. batch.n_seq_id = n_seq_id.data();
  6819. batch.seq_id = seq_id_arr.data();
  6820. }
  6821. // non-causal masks do not use the KV cache
  6822. if (hparams.causal_attn) {
  6823. llama_kv_cache_update(&lctx);
  6824. // if we have enough unused cells before the current head ->
  6825. // better to start searching from the beginning of the cache, hoping to fill it
  6826. if (kv_self.head > kv_self.used + 2*n_tokens) {
  6827. kv_self.head = 0;
  6828. }
  6829. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  6830. return 1;
  6831. }
  6832. // a heuristic, to avoid attending the full cache if it is not yet utilized
  6833. // after enough generations, the benefit from this heuristic disappears
  6834. // if we start defragmenting the cache, the benefit from this will be more important
  6835. kv_self.n = std::min(cparams.n_ctx, std::max(32u, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  6836. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  6837. }
  6838. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  6839. ggml_backend_sched_reset(lctx.sched);
  6840. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  6841. ggml_cgraph * gf = llama_build_graph(lctx, batch, false);
  6842. // the output is always the last tensor in the graph
  6843. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  6844. struct ggml_tensor * embd = gf->nodes[gf->n_nodes - 2];
  6845. if (!hparams.causal_attn) {
  6846. res = nullptr; // do not extract logits for embedding models such as BERT
  6847. // token or sequence embeddings
  6848. embd = gf->nodes[gf->n_nodes - 1];
  6849. GGML_ASSERT(strcmp(embd->name, "result_embd") == 0 || strcmp(embd->name, "result_embd_pooled") == 0);
  6850. } else {
  6851. if (strcmp(res->name, "result_output") == 0) {
  6852. // the token embeddings could be the second to last tensor, or the third to last tensor
  6853. if (strcmp(embd->name, "result_norm") != 0) {
  6854. embd = gf->nodes[gf->n_nodes - 3];
  6855. GGML_ASSERT(strcmp(embd->name, "result_norm") == 0);
  6856. }
  6857. } else {
  6858. GGML_ASSERT(false && "missing result_output tensor");
  6859. }
  6860. }
  6861. // 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);
  6862. // for big prompts, if BLAS is enabled, it is better to use only one thread
  6863. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  6864. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  6865. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  6866. // with the BLAS calls. need a better solution
  6867. // MoE Special Case: This logic applies when hparams.n_expert == 0, i.e. the model is NOT an MoE model. When an MoE is
  6868. // being processed then Accelerate/BLAS will not be involved, so capping would limit performance.
  6869. if (n_tokens >= 32 && hparams.n_expert == 0 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  6870. n_threads = std::min(4, n_threads);
  6871. }
  6872. llama_set_inputs(lctx, batch);
  6873. llama_graph_compute(lctx, gf, n_threads);
  6874. // update the kv ring buffer
  6875. {
  6876. kv_self.head += n_tokens;
  6877. // Ensure kv cache head points to a valid index.
  6878. if (kv_self.head >= kv_self.size) {
  6879. kv_self.head = 0;
  6880. }
  6881. }
  6882. // decide if we need to defrag the kv cache
  6883. if (cparams.defrag_thold >= 0.0f) {
  6884. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used + n_tokens)/float(kv_self.n) : 0.0f;
  6885. // queue defragmentation for next llama_kv_cache_update
  6886. if (fragmentation > cparams.defrag_thold) {
  6887. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  6888. llama_kv_cache_defrag(kv_self);
  6889. }
  6890. }
  6891. #ifdef GGML_PERF
  6892. // print timing information per ggml operation (for debugging purposes)
  6893. // requires GGML_PERF to be defined
  6894. ggml_graph_print(gf);
  6895. #endif
  6896. // plot the computation graph in dot format (for debugging purposes)
  6897. //if (n_past%100 == 0) {
  6898. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  6899. //}
  6900. // extract logits
  6901. // TODO: do not compute and extract logits if only embeddings are needed
  6902. // need to update the graphs to skip "result_output"
  6903. if (res) {
  6904. auto & logits_out = lctx.logits;
  6905. #ifndef NDEBUG
  6906. auto & logits_valid = lctx.logits_valid;
  6907. logits_valid.clear();
  6908. logits_valid.resize(n_tokens);
  6909. logits_out.clear();
  6910. #endif
  6911. ggml_backend_t backend_res = ggml_backend_sched_get_node_backend(lctx.sched, res);
  6912. GGML_ASSERT(backend_res != nullptr);
  6913. if (batch.logits) {
  6914. logits_out.resize(n_vocab * n_tokens);
  6915. for (uint32_t i = 0; i < n_tokens; i++) {
  6916. if (batch.logits[i] == 0) {
  6917. continue;
  6918. }
  6919. ggml_backend_tensor_get_async(backend_res, res, logits_out.data() + (n_vocab*i), (n_vocab*i)*sizeof(float), n_vocab*sizeof(float));
  6920. #ifndef NDEBUG
  6921. logits_valid[i] = true;
  6922. #endif
  6923. }
  6924. } else if (lctx.logits_all) {
  6925. logits_out.resize(n_vocab * n_tokens);
  6926. ggml_backend_tensor_get_async(backend_res, res, logits_out.data(), 0, n_vocab*n_tokens*sizeof(float));
  6927. #ifndef NDEBUG
  6928. std::fill(logits_valid.begin(), logits_valid.end(), true);
  6929. #endif
  6930. } else {
  6931. logits_out.resize(n_vocab);
  6932. ggml_backend_tensor_get_async(backend_res, res, logits_out.data(), (n_vocab*(n_tokens - 1))*sizeof(float), n_vocab*sizeof(float));
  6933. #ifndef NDEBUG
  6934. logits_valid[0] = true;
  6935. #endif
  6936. }
  6937. ggml_backend_synchronize(backend_res);
  6938. }
  6939. // extract embeddings
  6940. if (cparams.embeddings && embd) {
  6941. ggml_backend_t backend_embd = ggml_backend_sched_get_node_backend(lctx.sched, embd);
  6942. GGML_ASSERT(backend_embd != nullptr);
  6943. switch (cparams.pooling_type) {
  6944. case LLAMA_POOLING_TYPE_NONE:
  6945. {
  6946. // extract token embeddings
  6947. auto & embd_out = lctx.embd;
  6948. if (batch.logits) {
  6949. embd_out.resize(n_embd * n_tokens);
  6950. for (uint32_t i = 0; i < n_tokens; i++) {
  6951. if (batch.logits[i] == 0) {
  6952. continue;
  6953. }
  6954. ggml_backend_tensor_get_async(backend_embd, embd, embd_out.data() + (n_embd*i), (n_embd*i)*sizeof(float), n_embd*sizeof(float));
  6955. }
  6956. }
  6957. } break;
  6958. case LLAMA_POOLING_TYPE_CLS:
  6959. case LLAMA_POOLING_TYPE_MEAN:
  6960. {
  6961. GGML_ASSERT(strcmp(embd->name, "result_embd_pooled") == 0);
  6962. // extract sequence embeddings
  6963. auto & embd_seq_out = lctx.embd_seq;
  6964. embd_seq_out.clear();
  6965. for (uint32_t i = 0; i < n_tokens; i++) {
  6966. const llama_seq_id seq_id = batch.seq_id[i][0];
  6967. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  6968. continue;
  6969. }
  6970. embd_seq_out[seq_id].resize(n_embd);
  6971. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  6972. }
  6973. } break;
  6974. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  6975. {
  6976. GGML_ASSERT(false && "unknown pooling type");
  6977. } break;
  6978. }
  6979. ggml_backend_synchronize(backend_embd);
  6980. }
  6981. // measure the performance only for the single-token evals
  6982. if (n_tokens == 1) {
  6983. lctx.t_eval_us += ggml_time_us() - t_start_us;
  6984. lctx.n_eval++;
  6985. }
  6986. else if (n_tokens > 1) {
  6987. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  6988. lctx.n_p_eval += n_tokens;
  6989. }
  6990. // get a more accurate load time, upon first eval
  6991. // TODO: fix this
  6992. if (!lctx.has_evaluated_once) {
  6993. lctx.t_load_us = ggml_time_us() - lctx.t_start_us;
  6994. lctx.has_evaluated_once = true;
  6995. }
  6996. return 0;
  6997. }
  6998. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  6999. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  7000. auto & kv_self = lctx.kv_self;
  7001. const auto & hparams = lctx.model.hparams;
  7002. const uint32_t n_layer = hparams.n_layer;
  7003. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  7004. const uint32_t n_used = kv_self.used;
  7005. assert(n_used <= n_kv);
  7006. //const int64_t t_start = ggml_time_us();
  7007. // number of cells moved
  7008. uint32_t n_moves = 0;
  7009. // determine which KV cells to move where
  7010. //
  7011. // cell i moves to ids[i]
  7012. //
  7013. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  7014. //
  7015. std::vector<uint32_t> ids(n_kv, n_kv);
  7016. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  7017. const auto & cell0 = kv_self.cells[i0];
  7018. if (!cell0.is_empty()) {
  7019. ids[i0] = i0;
  7020. continue;
  7021. }
  7022. // found a hole - fill it with data from the end of the cache
  7023. uint32_t nh = 1;
  7024. // determine the size of the hole
  7025. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  7026. nh++;
  7027. }
  7028. // each move requires 6*n_layer tensors (see build_defrag)
  7029. // - source view, destination view, copy operation
  7030. // - x2 for keys and values
  7031. //
  7032. if (6*(n_moves + nh)*n_layer >= LLAMA_MAX_NODES) {
  7033. // the graph is too big, we cannot move more cells
  7034. break;
  7035. }
  7036. uint32_t nf = 0;
  7037. uint32_t is = n_kv - 1;
  7038. // starting from the end, find nh non-empty cells
  7039. for (; is > i0; --is) {
  7040. const auto & cell1 = kv_self.cells[is];
  7041. if (cell1.is_empty() || ids[is] != n_kv) {
  7042. continue;
  7043. }
  7044. // non-empty cell which is not yet moved
  7045. nf++;
  7046. if (nf == nh) {
  7047. break;
  7048. }
  7049. }
  7050. // this can only happen if `n_used` is not accurate, which would be a bug
  7051. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  7052. nf = 0;
  7053. uint32_t i1 = is;
  7054. // are we moving a continuous block of memory?
  7055. bool cont = false;
  7056. // go back and move the nf cells to the hole
  7057. for (; i1 < n_kv; ++i1) {
  7058. auto & cell1 = kv_self.cells[i1];
  7059. if (cell1.is_empty() || ids[i1] != n_kv) {
  7060. cont = false;
  7061. continue;
  7062. }
  7063. // this cell goes to (i0 + nf)
  7064. ids[i1] = i0 + nf;
  7065. // move the cell meta data
  7066. kv_self.cells[i0 + nf] = cell1;
  7067. // clear the old cell and move the head there
  7068. cell1 = llama_kv_cell();
  7069. kv_self.head = n_used;
  7070. if (!cont) {
  7071. n_moves++;
  7072. cont = true;
  7073. }
  7074. nf++;
  7075. if (nf == nh) {
  7076. break;
  7077. }
  7078. }
  7079. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  7080. i0 += nh - 1;
  7081. }
  7082. if (n_moves == 0) {
  7083. return;
  7084. }
  7085. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  7086. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  7087. #if 0
  7088. // CPU defrag
  7089. //
  7090. // TODO: optimizations are possible:
  7091. // - multiple threads
  7092. // - avoid copying to the host memory when already there
  7093. //
  7094. // likely not worth the effort, as we have ggml_graph based defrag
  7095. //
  7096. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  7097. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  7098. const uint32_t kv_size = kv_self.size;
  7099. std::vector<uint8_t> buf_k;
  7100. std::vector<uint8_t> buf_v;
  7101. for (uint32_t il = 0; il < n_layer; ++il) {
  7102. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  7103. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  7104. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  7105. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  7106. buf_k.resize(k_size);
  7107. buf_v.resize(v_size);
  7108. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  7109. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  7110. // batch move [i, i+nm) to [id, id+nm)
  7111. // note: cells can move only to a lower index
  7112. for (uint32_t i = 0; i < n_kv; ++i) {
  7113. const uint32_t id = ids[i];
  7114. if (i == id || id == n_kv) {
  7115. continue;
  7116. }
  7117. uint32_t nm = 1;
  7118. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  7119. nm++;
  7120. }
  7121. // move keys
  7122. {
  7123. const int64_t os = i*k_size_row;
  7124. const int64_t od = id*k_size_row;
  7125. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  7126. }
  7127. // move values (note: they are transposed)
  7128. {
  7129. const int64_t os = i;
  7130. const int64_t od = id;
  7131. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  7132. 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);
  7133. }
  7134. }
  7135. i += nm - 1;
  7136. }
  7137. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  7138. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  7139. }
  7140. #else
  7141. // ggml_graph defrag
  7142. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  7143. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  7144. #endif
  7145. //const int64_t t_end = ggml_time_us();
  7146. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  7147. }
  7148. static void llama_kv_cache_update_internal(struct llama_context & lctx) {
  7149. // apply K-shift if needed
  7150. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE && lctx.kv_self.has_shift) {
  7151. llama_set_k_shift(lctx);
  7152. {
  7153. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  7154. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  7155. }
  7156. {
  7157. auto & kv_self = lctx.kv_self;
  7158. kv_self.has_shift = false;
  7159. for (uint32_t i = 0; i < kv_self.size; ++i) {
  7160. kv_self.cells[i].delta = 0;
  7161. }
  7162. }
  7163. }
  7164. // defragment the KV cache if needed
  7165. if (lctx.kv_self.do_defrag) {
  7166. llama_kv_cache_defrag_internal(lctx);
  7167. lctx.kv_self.do_defrag = false;
  7168. }
  7169. }
  7170. //
  7171. // tokenizer
  7172. //
  7173. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  7174. return vocab.type;
  7175. }
  7176. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  7177. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  7178. }
  7179. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  7180. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  7181. }
  7182. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  7183. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  7184. }
  7185. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  7186. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  7187. }
  7188. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  7189. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  7190. }
  7191. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  7192. GGML_ASSERT(llama_is_byte_token(vocab, id));
  7193. const auto& token_data = vocab.id_to_token.at(id);
  7194. switch (llama_vocab_get_type(vocab)) {
  7195. case LLAMA_VOCAB_TYPE_SPM: {
  7196. auto buf = token_data.text.substr(3, 2);
  7197. return strtol(buf.c_str(), NULL, 16);
  7198. }
  7199. case LLAMA_VOCAB_TYPE_BPE: {
  7200. GGML_ASSERT(false);
  7201. return unicode_to_bytes_bpe(token_data.text);
  7202. }
  7203. case LLAMA_VOCAB_TYPE_WPM: {
  7204. GGML_ASSERT(false);
  7205. }
  7206. default:
  7207. GGML_ASSERT(false);
  7208. }
  7209. }
  7210. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  7211. static const char * hex = "0123456789ABCDEF";
  7212. switch (llama_vocab_get_type(vocab)) {
  7213. case LLAMA_VOCAB_TYPE_SPM: {
  7214. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  7215. auto token = vocab.token_to_id.find(buf);
  7216. if (token != vocab.token_to_id.end()) {
  7217. return (*token).second;
  7218. }
  7219. // Try to fall back to just the byte as a string
  7220. const char buf2[2] = { (char)ch, 0 };
  7221. return vocab.token_to_id.at(buf2);
  7222. }
  7223. case LLAMA_VOCAB_TYPE_WPM:
  7224. case LLAMA_VOCAB_TYPE_BPE: {
  7225. return vocab.token_to_id.at(bytes_to_unicode_bpe(ch));
  7226. }
  7227. default:
  7228. GGML_ASSERT(false);
  7229. }
  7230. }
  7231. static void llama_escape_whitespace(std::string & text) {
  7232. replace_all(text, " ", "\xe2\x96\x81");
  7233. }
  7234. static void llama_unescape_whitespace(std::string & word) {
  7235. replace_all(word, "\xe2\x96\x81", " ");
  7236. }
  7237. struct llm_symbol {
  7238. using index = int;
  7239. index prev;
  7240. index next;
  7241. const char * text;
  7242. size_t n;
  7243. };
  7244. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  7245. // SPM tokenizer
  7246. // original implementation:
  7247. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  7248. struct llm_bigram_spm {
  7249. struct comparator {
  7250. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  7251. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  7252. }
  7253. };
  7254. using queue_storage = std::vector<llm_bigram_spm>;
  7255. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  7256. llm_symbol::index left;
  7257. llm_symbol::index right;
  7258. float score;
  7259. size_t size;
  7260. };
  7261. struct llm_tokenizer_spm {
  7262. llm_tokenizer_spm(const llama_vocab & vocab) : vocab(vocab) {}
  7263. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  7264. // split string into utf8 chars
  7265. int index = 0;
  7266. size_t offs = 0;
  7267. while (offs < text.size()) {
  7268. llm_symbol sym;
  7269. size_t len = utf8_len(text[offs]);
  7270. sym.text = text.c_str() + offs;
  7271. sym.n = std::min(len, text.size() - offs);
  7272. offs += sym.n;
  7273. sym.prev = index - 1;
  7274. sym.next = offs == text.size() ? -1 : index + 1;
  7275. index++;
  7276. symbols.emplace_back(sym);
  7277. }
  7278. // seed the work queue with all possible 2-character tokens.
  7279. for (size_t i = 1; i < symbols.size(); ++i) {
  7280. try_add_bigram(i - 1, i);
  7281. }
  7282. // keep substituting the highest frequency pairs for as long as we can.
  7283. while (!work_queue.empty()) {
  7284. auto bigram = work_queue.top();
  7285. work_queue.pop();
  7286. auto & left_sym = symbols[bigram.left];
  7287. auto & right_sym = symbols[bigram.right];
  7288. // if one of the symbols already got merged, skip it.
  7289. if (left_sym.n == 0 || right_sym.n == 0 ||
  7290. left_sym.n + right_sym.n != bigram.size) {
  7291. continue;
  7292. }
  7293. // merge the right sym into the left one
  7294. left_sym.n += right_sym.n;
  7295. right_sym.n = 0;
  7296. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  7297. // remove the right sym from the chain
  7298. left_sym.next = right_sym.next;
  7299. if (right_sym.next >= 0) {
  7300. symbols[right_sym.next].prev = bigram.left;
  7301. }
  7302. // find more substitutions
  7303. try_add_bigram(left_sym.prev, bigram.left);
  7304. try_add_bigram(bigram.left, left_sym.next);
  7305. }
  7306. for (int i = 0; i != -1; i = symbols[i].next) {
  7307. auto & symbol = symbols[i];
  7308. resegment(symbol, output);
  7309. }
  7310. }
  7311. private:
  7312. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  7313. auto text = std::string(symbol.text, symbol.n);
  7314. auto token = vocab.token_to_id.find(text);
  7315. // Do we need to support is_unused?
  7316. if (token != vocab.token_to_id.end()) {
  7317. output.push_back((*token).second);
  7318. return;
  7319. }
  7320. const auto p = rev_merge.find(text);
  7321. if (p == rev_merge.end()) {
  7322. // output any symbols that did not form tokens as bytes.
  7323. output.reserve(output.size() + symbol.n);
  7324. for (int j = 0; j < (int)symbol.n; ++j) {
  7325. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  7326. output.push_back(token_id);
  7327. }
  7328. return;
  7329. }
  7330. resegment(symbols[p->second.first], output);
  7331. resegment(symbols[p->second.second], output);
  7332. }
  7333. void try_add_bigram(int left, int right) {
  7334. if (left == -1 || right == -1) {
  7335. return;
  7336. }
  7337. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  7338. auto token = vocab.token_to_id.find(text);
  7339. if (token == vocab.token_to_id.end()) {
  7340. return;
  7341. }
  7342. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  7343. return;
  7344. }
  7345. const auto & tok_data = vocab.id_to_token[(*token).second];
  7346. llm_bigram_spm bigram;
  7347. bigram.left = left;
  7348. bigram.right = right;
  7349. bigram.score = tok_data.score;
  7350. bigram.size = text.size();
  7351. work_queue.push(bigram);
  7352. // Do we need to support is_unused?
  7353. rev_merge[text] = std::make_pair(left, right);
  7354. }
  7355. const llama_vocab & vocab;
  7356. std::vector<llm_symbol> symbols;
  7357. llm_bigram_spm::queue work_queue;
  7358. std::map<std::string, std::pair<int, int>> rev_merge;
  7359. };
  7360. // BPE tokenizer
  7361. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  7362. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  7363. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  7364. struct llm_bigram_bpe {
  7365. struct comparator {
  7366. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  7367. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  7368. }
  7369. };
  7370. using queue_storage = std::vector<llm_bigram_bpe>;
  7371. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  7372. llm_symbol::index left;
  7373. llm_symbol::index right;
  7374. std::string text;
  7375. int rank;
  7376. size_t size;
  7377. };
  7378. struct llm_tokenizer_bpe {
  7379. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  7380. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  7381. int final_prev_index = -1;
  7382. auto word_collection = bpe_gpt2_preprocess(text);
  7383. symbols_final.clear();
  7384. for (auto & word : word_collection) {
  7385. work_queue = llm_bigram_bpe::queue();
  7386. symbols.clear();
  7387. int index = 0;
  7388. size_t offset = 0;
  7389. while (offset < word.size()) {
  7390. llm_symbol sym;
  7391. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  7392. sym.text = word.c_str() + offset;
  7393. sym.n = char_len;
  7394. offset += sym.n;
  7395. sym.prev = index - 1;
  7396. sym.next = offset == word.size() ? -1 : index + 1;
  7397. index++;
  7398. symbols.emplace_back(sym);
  7399. }
  7400. for (size_t i = 1; i < symbols.size(); ++i) {
  7401. add_new_bigram(i - 1, i);
  7402. }
  7403. // build token(s)
  7404. while (!work_queue.empty()) {
  7405. auto bigram = work_queue.top();
  7406. work_queue.pop();
  7407. auto & left_symbol = symbols[bigram.left];
  7408. auto & right_symbol = symbols[bigram.right];
  7409. if (left_symbol.n == 0 || right_symbol.n == 0) {
  7410. continue;
  7411. }
  7412. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  7413. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  7414. if (left_token + right_token != bigram.text) {
  7415. continue; // Skip this bigram if it's outdated
  7416. }
  7417. // merge the right sym into the left one
  7418. left_symbol.n += right_symbol.n;
  7419. right_symbol.n = 0;
  7420. // remove the right sym from the chain
  7421. left_symbol.next = right_symbol.next;
  7422. if (right_symbol.next >= 0) {
  7423. symbols[right_symbol.next].prev = bigram.left;
  7424. }
  7425. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  7426. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  7427. }
  7428. // add the fnished tokens to the final list keeping correct order for next and prev
  7429. for (auto & sym : symbols) {
  7430. if (sym.n > 0) {
  7431. sym.prev = final_prev_index;
  7432. sym.next = -1;
  7433. if (final_prev_index != -1) {
  7434. symbols_final[final_prev_index].next = symbols_final.size();
  7435. }
  7436. symbols_final.emplace_back(sym);
  7437. final_prev_index = symbols_final.size() - 1;
  7438. }
  7439. }
  7440. }
  7441. symbols = symbols_final;
  7442. if (!symbols.empty()) {
  7443. for (int i = 0; i != -1; i = symbols[i].next) {
  7444. auto & symbol = symbols[i];
  7445. if (symbol.n == 0) {
  7446. continue;
  7447. }
  7448. const std::string str = std::string(symbol.text, symbol.n);
  7449. const auto token = vocab.token_to_id.find(str);
  7450. if (token == vocab.token_to_id.end()) {
  7451. for (auto j = str.begin(); j != str.end(); ++j) {
  7452. std::string byte_str(1, *j);
  7453. auto token_multibyte = vocab.token_to_id.find(byte_str);
  7454. if (token_multibyte == vocab.token_to_id.end()) {
  7455. throw std::runtime_error("ERROR: byte not found in vocab");
  7456. }
  7457. output.push_back((*token_multibyte).second);
  7458. }
  7459. } else {
  7460. output.push_back((*token).second);
  7461. }
  7462. }
  7463. }
  7464. }
  7465. private:
  7466. void add_new_bigram(int left, int right) {
  7467. if (left == -1 || right == -1) {
  7468. return;
  7469. }
  7470. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  7471. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  7472. int rank_found = -1;
  7473. rank_found = vocab.find_bpe_rank(left_token, right_token);
  7474. if (rank_found < 0) {
  7475. return;
  7476. }
  7477. llm_bigram_bpe bigram;
  7478. bigram.left = left;
  7479. bigram.right = right;
  7480. bigram.text = left_token + right_token;
  7481. bigram.size = left_token.size() + right_token.size();
  7482. bigram.rank = rank_found;
  7483. work_queue.push(bigram);
  7484. }
  7485. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  7486. std::vector<std::string> bpe_words;
  7487. std::vector<std::string> bpe_encoded_words;
  7488. std::string token = "";
  7489. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  7490. bool collecting_numeric = false;
  7491. bool collecting_letter = false;
  7492. bool collecting_special = false;
  7493. bool collecting_whitespace_lookahead = false;
  7494. bool collecting = false;
  7495. std::vector<std::string> text_utf;
  7496. text_utf.reserve(text.size());
  7497. bpe_words.reserve(text.size());
  7498. bpe_encoded_words.reserve(text.size());
  7499. auto cps = codepoints_from_utf8(text);
  7500. for (size_t i = 0; i < cps.size(); ++i)
  7501. text_utf.emplace_back(codepoint_to_utf8(cps[i]));
  7502. for (int i = 0; i < (int)text_utf.size(); i++) {
  7503. const std::string & utf_char = text_utf[i];
  7504. bool split_condition = false;
  7505. int bytes_remain = text_utf.size() - i;
  7506. // forward backward lookups
  7507. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  7508. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  7509. // handling contractions
  7510. if (!split_condition && bytes_remain >= 2) {
  7511. // 's|'t|'m|'d
  7512. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  7513. split_condition = true;
  7514. }
  7515. if (split_condition) {
  7516. if (token.size()) {
  7517. bpe_words.emplace_back(token); // push previous content as token
  7518. }
  7519. token = utf_char + utf_char_next;
  7520. bpe_words.emplace_back(token);
  7521. token = "";
  7522. i++;
  7523. continue;
  7524. }
  7525. }
  7526. if (!split_condition && bytes_remain >= 3) {
  7527. // 're|'ve|'ll
  7528. if (utf_char == "\'" && (
  7529. (utf_char_next == "r" && utf_char_next_next == "e") ||
  7530. (utf_char_next == "v" && utf_char_next_next == "e") ||
  7531. (utf_char_next == "l" && utf_char_next_next == "l"))
  7532. ) {
  7533. split_condition = true;
  7534. }
  7535. if (split_condition) {
  7536. // current token + next token can be defined
  7537. if (token.size()) {
  7538. bpe_words.emplace_back(token); // push previous content as token
  7539. }
  7540. token = utf_char + utf_char_next + utf_char_next_next;
  7541. bpe_words.emplace_back(token); // the contraction
  7542. token = "";
  7543. i += 2;
  7544. continue;
  7545. }
  7546. }
  7547. if (!split_condition && !collecting) {
  7548. if (codepoint_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  7549. collecting_letter = true;
  7550. collecting = true;
  7551. }
  7552. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  7553. collecting_numeric = true;
  7554. collecting = true;
  7555. }
  7556. else if (
  7557. ((codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (codepoint_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  7558. (!token.size() && utf_char == " " && codepoint_type(utf_char_next) != CODEPOINT_TYPE_LETTER && codepoint_type(utf_char_next) != CODEPOINT_TYPE_DIGIT && codepoint_type(utf_char_next) != CODEPOINT_TYPE_WHITESPACE)
  7559. ) {
  7560. collecting_special = true;
  7561. collecting = true;
  7562. }
  7563. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && codepoint_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  7564. collecting_whitespace_lookahead = true;
  7565. collecting = true;
  7566. }
  7567. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  7568. split_condition = true;
  7569. }
  7570. }
  7571. else if (!split_condition && collecting) {
  7572. if (collecting_letter && codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  7573. split_condition = true;
  7574. }
  7575. else if (collecting_numeric && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  7576. split_condition = true;
  7577. }
  7578. else if (collecting_special && (codepoint_type(utf_char) == CODEPOINT_TYPE_LETTER || codepoint_type(utf_char) == CODEPOINT_TYPE_DIGIT || codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE)) {
  7579. split_condition = true;
  7580. }
  7581. else if (collecting_whitespace_lookahead && (codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER || codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  7582. split_condition = true;
  7583. }
  7584. }
  7585. if (utf_char_next == "") {
  7586. split_condition = true; // final
  7587. token += utf_char;
  7588. }
  7589. if (split_condition) {
  7590. if (token.size()) {
  7591. bpe_words.emplace_back(token);
  7592. }
  7593. token = utf_char;
  7594. collecting = false;
  7595. collecting_letter = false;
  7596. collecting_numeric = false;
  7597. collecting_special = false;
  7598. collecting_whitespace_lookahead = false;
  7599. }
  7600. else {
  7601. token += utf_char;
  7602. }
  7603. }
  7604. for (std::string & word : bpe_words) {
  7605. std::string encoded_token = "";
  7606. for (char & c : word) {
  7607. encoded_token += bytes_to_unicode_bpe(c);
  7608. }
  7609. bpe_encoded_words.emplace_back(encoded_token);
  7610. }
  7611. return bpe_encoded_words;
  7612. }
  7613. const llama_vocab & vocab;
  7614. std::vector<llm_symbol> symbols;
  7615. std::vector<llm_symbol> symbols_final;
  7616. llm_bigram_bpe::queue work_queue;
  7617. };
  7618. struct llm_tokenizer_wpm {
  7619. llm_tokenizer_wpm(const llama_vocab & vocab): vocab(vocab) {}
  7620. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  7621. auto * token_map = &vocab.token_to_id;
  7622. // normalize and split by whitespace
  7623. std::vector<std::string> words = preprocess(text);
  7624. // bos token prepended already
  7625. // find the longest tokens that form the words
  7626. for (const std::string &word : words) {
  7627. // skip empty words
  7628. if (word.size() == 0) {
  7629. continue;
  7630. }
  7631. // prepend phantom space
  7632. std::string word1 = "\xe2\x96\x81" + word;
  7633. int n = word1.size();
  7634. // we're at the start of a new word
  7635. int i = 0;
  7636. bool match_any = false;
  7637. // move through character position in word
  7638. while (i < n) {
  7639. // loop through possible match length
  7640. bool match = false;
  7641. for (int j = n; j > i; j--) {
  7642. auto it = token_map->find(word1.substr(i, j - i));
  7643. if (it != token_map->end()) {
  7644. output.push_back(it->second);
  7645. match = true;
  7646. match_any = true;
  7647. i = j;
  7648. break;
  7649. }
  7650. }
  7651. // must be an unknown character
  7652. if (!match) {
  7653. i++;
  7654. }
  7655. }
  7656. // we didn't find any matches for this word
  7657. if (!match_any) {
  7658. output.push_back(vocab.special_unk_id);
  7659. }
  7660. }
  7661. // append eos token
  7662. output.push_back(vocab.special_eos_id);
  7663. }
  7664. std::vector<std::string> preprocess(const std::string & text) {
  7665. // normalalization form D
  7666. std::vector<uint32_t> codepoints = codepoints_from_utf8(text);
  7667. std::vector<uint32_t> nfd_codepoints;
  7668. for (uint32_t code : codepoints) {
  7669. auto it = nfd_map.equal_range(code);
  7670. if (it.first != it.second) {
  7671. for (auto jt = it.first; jt != it.second; jt++) {
  7672. nfd_codepoints.push_back(jt->second);
  7673. }
  7674. } else {
  7675. nfd_codepoints.push_back(code);
  7676. }
  7677. }
  7678. // strip accents, strip control, uniformize whitespace,
  7679. // to lowercase, pad chinese characters, pad punctuation
  7680. std::string new_str = "";
  7681. for (uint32_t code : nfd_codepoints) {
  7682. int type = codepoint_type(code);
  7683. if (type == CODEPOINT_TYPE_ACCENT_MARK || type == CODEPOINT_TYPE_CONTROL) {
  7684. continue;
  7685. }
  7686. code = to_lower(code);
  7687. if (type == CODEPOINT_TYPE_WHITESPACE) {
  7688. code = ' ';
  7689. }
  7690. std::string s = codepoint_to_utf8(code);
  7691. if (type == CODEPOINT_TYPE_PUNCTUATION || is_ascii_punct(code) || is_chinese_char(code)) {
  7692. new_str += " ";
  7693. new_str += s;
  7694. new_str += " ";
  7695. } else {
  7696. new_str += s;
  7697. }
  7698. }
  7699. // split by whitespace
  7700. uint64_t l = 0;
  7701. uint64_t r = 0;
  7702. std::vector<std::string> words;
  7703. while (r < new_str.size()) {
  7704. // if is whitespace
  7705. if (isspace(new_str[r])) {
  7706. if (r > l) words.push_back(new_str.substr(l, (r - l)));
  7707. l = r + 1;
  7708. r = l;
  7709. }
  7710. else {
  7711. r += 1;
  7712. }
  7713. }
  7714. if (r > l) {
  7715. words.push_back(new_str.substr(l, (r - l)));
  7716. }
  7717. return words;
  7718. }
  7719. uint32_t to_lower(uint32_t code) {
  7720. static const std::locale locale("en_US.UTF-8");
  7721. #if defined(_WIN32)
  7722. if (code > 0xFFFF) {
  7723. return code;
  7724. }
  7725. #endif
  7726. return std::tolower(wchar_t(code), locale);
  7727. }
  7728. bool is_ascii_punct(uint32_t code) {
  7729. return code < 256 && ispunct(code);
  7730. }
  7731. bool is_chinese_char(uint32_t codepoint) {
  7732. if ((codepoint >= 0x4E00 && codepoint <= 0x9FFF) ||
  7733. (codepoint >= 0x3400 && codepoint <= 0x4DBF) ||
  7734. (codepoint >= 0x20000 && codepoint <= 0x2A6DF) ||
  7735. (codepoint >= 0x2A700 && codepoint <= 0x2B73F) ||
  7736. (codepoint >= 0x2B740 && codepoint <= 0x2B81F) ||
  7737. (codepoint >= 0x2B920 && codepoint <= 0x2CEAF) || // this should be 0x2B820 but in hf rust code it is 0x2B920
  7738. (codepoint >= 0xF900 && codepoint <= 0xFAFF) ||
  7739. (codepoint >= 0x2F800 && codepoint <= 0x2FA1F) ||
  7740. (codepoint >= 0x3000 && codepoint <= 0x303F) ||
  7741. (codepoint >= 0xFF00 && codepoint <= 0xFFEF)) {
  7742. return true; // NOLINT
  7743. }
  7744. return false;
  7745. }
  7746. const llama_vocab & vocab;
  7747. };
  7748. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE {
  7749. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  7750. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  7751. } FRAGMENT_BUFFER_VARIANT_TYPE;
  7752. struct fragment_buffer_variant {
  7753. fragment_buffer_variant(llama_vocab::id _token)
  7754. :
  7755. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  7756. token(_token),
  7757. raw_text(_dummy),
  7758. offset(0),
  7759. length(0) {}
  7760. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  7761. :
  7762. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  7763. token((llama_vocab::id) - 1),
  7764. raw_text(_raw_text),
  7765. offset(_offset),
  7766. length(_length){
  7767. GGML_ASSERT(_offset >= 0);
  7768. GGML_ASSERT(_length >= 1);
  7769. GGML_ASSERT(offset + length <= raw_text.length());
  7770. }
  7771. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  7772. const llama_vocab::id token;
  7773. const std::string _dummy;
  7774. const std::string & raw_text;
  7775. const uint64_t offset;
  7776. const uint64_t length;
  7777. };
  7778. // #define PRETOKENIZERDEBUG
  7779. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer) {
  7780. // for each special token
  7781. for (const auto & st: vocab.special_tokens_cache) {
  7782. const auto & special_token = st.first;
  7783. const auto & special_id = st.second;
  7784. // for each text fragment
  7785. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  7786. while (it != buffer.end()) {
  7787. auto & fragment = (*it);
  7788. // if a fragment is text ( not yet processed )
  7789. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7790. auto * raw_text = &(fragment.raw_text);
  7791. auto raw_text_base_offset = fragment.offset;
  7792. auto raw_text_base_length = fragment.length;
  7793. // loop over the text
  7794. while (true) {
  7795. // find the first occurrence of a given special token in this fragment
  7796. // passing offset argument only limit the "search area" but match coordinates
  7797. // are still relative to the source full raw_text
  7798. auto match = raw_text->find(special_token, raw_text_base_offset);
  7799. // no occurrences found, stop processing this fragment for a given special token
  7800. if (match == std::string::npos) break;
  7801. // check if match is within bounds of offset <-> length
  7802. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  7803. #ifdef PRETOKENIZERDEBUG
  7804. 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());
  7805. #endif
  7806. auto source = std::distance(buffer.begin(), it);
  7807. // if match is further than base offset
  7808. // then we have some text to the left of it
  7809. if (match > raw_text_base_offset) {
  7810. // left
  7811. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  7812. const int64_t left_reminder_length = match - raw_text_base_offset;
  7813. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  7814. #ifdef PRETOKENIZERDEBUG
  7815. 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());
  7816. #endif
  7817. it++;
  7818. }
  7819. // special token
  7820. buffer.emplace_after(it, special_id);
  7821. it++;
  7822. // right
  7823. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  7824. const int64_t right_reminder_offset = match + special_token.length();
  7825. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  7826. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  7827. #ifdef PRETOKENIZERDEBUG
  7828. 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());
  7829. #endif
  7830. it++;
  7831. if (source == 0) {
  7832. buffer.erase_after(buffer.before_begin());
  7833. } else {
  7834. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  7835. }
  7836. // repeat for the right side
  7837. raw_text_base_offset = right_reminder_offset;
  7838. raw_text_base_length = right_reminder_length;
  7839. #ifdef PRETOKENIZERDEBUG
  7840. 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());
  7841. #endif
  7842. } else {
  7843. if (source == 0) {
  7844. buffer.erase_after(buffer.before_begin());
  7845. } else {
  7846. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  7847. }
  7848. break;
  7849. }
  7850. }
  7851. }
  7852. it++;
  7853. }
  7854. }
  7855. }
  7856. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  7857. std::vector<llama_vocab::id> output;
  7858. // OG tokenizer behavior:
  7859. //
  7860. // tokenizer.encode('', add_bos=True) returns [1]
  7861. // tokenizer.encode('', add_bos=False) returns []
  7862. if (bos && vocab.special_bos_id != -1) {
  7863. output.push_back(vocab.special_bos_id);
  7864. }
  7865. if (raw_text.empty()) {
  7866. return output;
  7867. }
  7868. std::forward_list<fragment_buffer_variant> fragment_buffer;
  7869. fragment_buffer.emplace_front(raw_text, 0, raw_text.length());
  7870. if (special) tokenizer_st_partition(vocab, fragment_buffer);
  7871. switch (vocab.type) {
  7872. case LLAMA_VOCAB_TYPE_SPM:
  7873. {
  7874. for (const auto & fragment : fragment_buffer) {
  7875. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7876. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  7877. // TODO: It's likely possible to get rid of this string copy entirely
  7878. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  7879. // and passing 'add space prefix' as bool argument
  7880. //
  7881. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7882. if (&fragment == &fragment_buffer.front()) {
  7883. if (vocab.add_space_prefix) {
  7884. raw_text = " " + raw_text; // prefix with space if the first token is not special
  7885. }
  7886. }
  7887. #ifdef PRETOKENIZERDEBUG
  7888. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7889. #endif
  7890. llm_tokenizer_spm tokenizer(vocab);
  7891. llama_escape_whitespace(raw_text);
  7892. tokenizer.tokenize(raw_text, output);
  7893. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7894. output.push_back(fragment.token);
  7895. }
  7896. }
  7897. } break;
  7898. case LLAMA_VOCAB_TYPE_BPE:
  7899. {
  7900. for (const auto & fragment : fragment_buffer) {
  7901. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7902. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7903. #ifdef PRETOKENIZERDEBUG
  7904. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7905. #endif
  7906. llm_tokenizer_bpe tokenizer(vocab);
  7907. tokenizer.tokenize(raw_text, output);
  7908. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7909. output.push_back(fragment.token);
  7910. }
  7911. }
  7912. } break;
  7913. case LLAMA_VOCAB_TYPE_WPM:
  7914. {
  7915. for (const auto & fragment : fragment_buffer) {
  7916. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7917. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7918. #ifdef PRETOKENIZERDEBUG
  7919. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7920. #endif
  7921. llm_tokenizer_wpm tokenizer(vocab);
  7922. tokenizer.tokenize(raw_text, output);
  7923. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7924. output.push_back(fragment.token);
  7925. }
  7926. }
  7927. } break;
  7928. }
  7929. return output;
  7930. }
  7931. //
  7932. // grammar - internal
  7933. //
  7934. struct llama_partial_utf8 {
  7935. uint32_t value; // bit value so far (unshifted)
  7936. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  7937. };
  7938. struct llama_grammar {
  7939. const std::vector<std::vector<llama_grammar_element>> rules;
  7940. std::vector<std::vector<const llama_grammar_element *>> stacks;
  7941. // buffer for partially generated UTF-8 sequence from accepted tokens
  7942. llama_partial_utf8 partial_utf8;
  7943. };
  7944. struct llama_grammar_candidate {
  7945. size_t index;
  7946. const uint32_t * code_points;
  7947. llama_partial_utf8 partial_utf8;
  7948. };
  7949. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  7950. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  7951. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  7952. const std::string & src,
  7953. llama_partial_utf8 partial_start) {
  7954. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  7955. const char * pos = src.c_str();
  7956. std::vector<uint32_t> code_points;
  7957. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  7958. code_points.reserve(src.size() + 1);
  7959. uint32_t value = partial_start.value;
  7960. int n_remain = partial_start.n_remain;
  7961. // continue previous decode, if applicable
  7962. while (*pos != 0 && n_remain > 0) {
  7963. uint8_t next_byte = static_cast<uint8_t>(*pos);
  7964. if ((next_byte >> 6) != 2) {
  7965. // invalid sequence, abort
  7966. code_points.push_back(0);
  7967. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  7968. }
  7969. value = (value << 6) + (next_byte & 0x3F);
  7970. ++pos;
  7971. --n_remain;
  7972. }
  7973. if (partial_start.n_remain > 0 && n_remain == 0) {
  7974. code_points.push_back(value);
  7975. }
  7976. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  7977. while (*pos != 0) {
  7978. uint8_t first_byte = static_cast<uint8_t>(*pos);
  7979. uint8_t highbits = first_byte >> 4;
  7980. n_remain = lookup[highbits] - 1;
  7981. if (n_remain < 0) {
  7982. // invalid sequence, abort
  7983. code_points.clear();
  7984. code_points.push_back(0);
  7985. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  7986. }
  7987. uint8_t mask = (1 << (7 - n_remain)) - 1;
  7988. value = first_byte & mask;
  7989. ++pos;
  7990. while (*pos != 0 && n_remain > 0) {
  7991. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  7992. ++pos;
  7993. --n_remain;
  7994. }
  7995. if (n_remain == 0) {
  7996. code_points.push_back(value);
  7997. }
  7998. }
  7999. code_points.push_back(0);
  8000. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  8001. }
  8002. // returns true iff pos points to the end of one of the definitions of a rule
  8003. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  8004. switch (pos->type) {
  8005. case LLAMA_GRETYPE_END: return true; // NOLINT
  8006. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  8007. default: return false;
  8008. }
  8009. }
  8010. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  8011. // asserts that pos is pointing to a char range element
  8012. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  8013. const llama_grammar_element * pos,
  8014. const uint32_t chr) {
  8015. bool found = false;
  8016. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  8017. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  8018. do {
  8019. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  8020. // inclusive range, e.g. [a-z]
  8021. found = found || (pos->value <= chr && chr <= pos[1].value);
  8022. pos += 2;
  8023. } else {
  8024. // exact char match, e.g. [a] or "a"
  8025. found = found || pos->value == chr;
  8026. pos += 1;
  8027. }
  8028. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  8029. return std::make_pair(found == is_positive_char, pos);
  8030. }
  8031. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  8032. // range at pos (regular or inverse range)
  8033. // asserts that pos is pointing to a char range element
  8034. static bool llama_grammar_match_partial_char(
  8035. const llama_grammar_element * pos,
  8036. const llama_partial_utf8 partial_utf8) {
  8037. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  8038. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  8039. uint32_t partial_value = partial_utf8.value;
  8040. int n_remain = partial_utf8.n_remain;
  8041. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  8042. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  8043. return false;
  8044. }
  8045. // range of possible code points this partial UTF-8 sequence could complete to
  8046. uint32_t low = partial_value << (n_remain * 6);
  8047. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  8048. if (low == 0) {
  8049. if (n_remain == 2) {
  8050. low = 1 << 11;
  8051. } else if (n_remain == 3) {
  8052. low = 1 << 16;
  8053. }
  8054. }
  8055. do {
  8056. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  8057. // inclusive range, e.g. [a-z]
  8058. if (pos->value <= high && low <= pos[1].value) {
  8059. return is_positive_char;
  8060. }
  8061. pos += 2;
  8062. } else {
  8063. // exact char match, e.g. [a] or "a"
  8064. if (low <= pos->value && pos->value <= high) {
  8065. return is_positive_char;
  8066. }
  8067. pos += 1;
  8068. }
  8069. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  8070. return !is_positive_char;
  8071. }
  8072. // transforms a grammar pushdown stack into N possible stacks, all ending
  8073. // at a character range (terminal element)
  8074. static void llama_grammar_advance_stack(
  8075. const std::vector<std::vector<llama_grammar_element>> & rules,
  8076. const std::vector<const llama_grammar_element *> & stack,
  8077. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  8078. if (stack.empty()) {
  8079. new_stacks.emplace_back(stack);
  8080. return;
  8081. }
  8082. const llama_grammar_element * pos = stack.back();
  8083. switch (pos->type) {
  8084. case LLAMA_GRETYPE_RULE_REF: {
  8085. const size_t rule_id = static_cast<size_t>(pos->value);
  8086. const llama_grammar_element * subpos = rules[rule_id].data();
  8087. do {
  8088. // init new stack without the top (pos)
  8089. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  8090. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  8091. // if this rule ref is followed by another element, add that to stack
  8092. new_stack.push_back(pos + 1);
  8093. }
  8094. if (!llama_grammar_is_end_of_sequence(subpos)) {
  8095. // if alternate is nonempty, add to stack
  8096. new_stack.push_back(subpos);
  8097. }
  8098. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  8099. while (!llama_grammar_is_end_of_sequence(subpos)) {
  8100. // scan to end of alternate def
  8101. subpos++;
  8102. }
  8103. if (subpos->type == LLAMA_GRETYPE_ALT) {
  8104. // there's another alternate def of this rule to process
  8105. subpos++;
  8106. } else {
  8107. break;
  8108. }
  8109. } while (true);
  8110. break;
  8111. }
  8112. case LLAMA_GRETYPE_CHAR:
  8113. case LLAMA_GRETYPE_CHAR_NOT:
  8114. new_stacks.emplace_back(stack);
  8115. break;
  8116. default:
  8117. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  8118. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  8119. // those
  8120. GGML_ASSERT(false);
  8121. }
  8122. }
  8123. // takes a set of possible pushdown stacks on a grammar, which are required to
  8124. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  8125. // produces the N possible stacks if the given char is accepted at those
  8126. // positions
  8127. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  8128. const std::vector<std::vector<llama_grammar_element>> & rules,
  8129. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  8130. const uint32_t chr) {
  8131. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  8132. for (const auto & stack : stacks) {
  8133. if (stack.empty()) {
  8134. continue;
  8135. }
  8136. auto match = llama_grammar_match_char(stack.back(), chr);
  8137. if (match.first) {
  8138. const llama_grammar_element * pos = match.second;
  8139. // update top of stack to next element, if any
  8140. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  8141. if (!llama_grammar_is_end_of_sequence(pos)) {
  8142. new_stack.push_back(pos);
  8143. }
  8144. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  8145. }
  8146. }
  8147. return new_stacks;
  8148. }
  8149. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  8150. const std::vector<std::vector<llama_grammar_element>> & rules,
  8151. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  8152. const std::vector<llama_grammar_candidate> & candidates);
  8153. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  8154. const std::vector<std::vector<llama_grammar_element>> & rules,
  8155. const std::vector<const llama_grammar_element *> & stack,
  8156. const std::vector<llama_grammar_candidate> & candidates) {
  8157. std::vector<llama_grammar_candidate> rejects;
  8158. if (stack.empty()) {
  8159. for (const auto & tok : candidates) {
  8160. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  8161. rejects.push_back(tok);
  8162. }
  8163. }
  8164. return rejects;
  8165. }
  8166. const llama_grammar_element * stack_pos = stack.back();
  8167. std::vector<llama_grammar_candidate> next_candidates;
  8168. for (const auto & tok : candidates) {
  8169. if (*tok.code_points == 0) {
  8170. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  8171. // that cannot satisfy this position in grammar
  8172. if (tok.partial_utf8.n_remain != 0 &&
  8173. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  8174. rejects.push_back(tok);
  8175. }
  8176. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  8177. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  8178. } else {
  8179. rejects.push_back(tok);
  8180. }
  8181. }
  8182. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  8183. // update top of stack to next element, if any
  8184. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  8185. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  8186. stack_after.push_back(stack_pos_after);
  8187. }
  8188. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  8189. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  8190. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  8191. for (const auto & tok : next_rejects) {
  8192. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  8193. }
  8194. return rejects;
  8195. }
  8196. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  8197. const std::vector<std::vector<llama_grammar_element>> & rules,
  8198. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  8199. const std::vector<llama_grammar_candidate> & candidates) {
  8200. GGML_ASSERT(!stacks.empty()); // REVIEW
  8201. if (candidates.empty()) {
  8202. return std::vector<llama_grammar_candidate>();
  8203. }
  8204. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  8205. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  8206. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  8207. }
  8208. return rejects;
  8209. }
  8210. //
  8211. // grammar - external
  8212. //
  8213. struct llama_grammar * llama_grammar_init(
  8214. const llama_grammar_element ** rules,
  8215. size_t n_rules,
  8216. size_t start_rule_index) {
  8217. const llama_grammar_element * pos;
  8218. // copy rule definitions into vectors
  8219. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  8220. for (size_t i = 0; i < n_rules; i++) {
  8221. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  8222. vec_rules[i].push_back(*pos);
  8223. }
  8224. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  8225. }
  8226. // loop over alternates of start rule to build initial stacks
  8227. std::vector<std::vector<const llama_grammar_element *>> stacks;
  8228. pos = rules[start_rule_index];
  8229. do {
  8230. std::vector<const llama_grammar_element *> stack;
  8231. if (!llama_grammar_is_end_of_sequence(pos)) {
  8232. // if alternate is nonempty, add to stack
  8233. stack.push_back(pos);
  8234. }
  8235. llama_grammar_advance_stack(vec_rules, stack, stacks);
  8236. while (!llama_grammar_is_end_of_sequence(pos)) {
  8237. // scan to end of alternate def
  8238. pos++;
  8239. }
  8240. if (pos->type == LLAMA_GRETYPE_ALT) {
  8241. // there's another alternate def of this rule to process
  8242. pos++;
  8243. } else {
  8244. break;
  8245. }
  8246. } while (true);
  8247. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  8248. }
  8249. void llama_grammar_free(struct llama_grammar * grammar) {
  8250. delete grammar;
  8251. }
  8252. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  8253. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  8254. // redirect elements in stacks to point to new rules
  8255. for (size_t is = 0; is < result->stacks.size(); is++) {
  8256. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  8257. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  8258. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  8259. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  8260. result->stacks[is][ie] = &result->rules[ir0][ir1];
  8261. }
  8262. }
  8263. }
  8264. }
  8265. }
  8266. return result;
  8267. }
  8268. //
  8269. // sampling
  8270. //
  8271. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  8272. if (seed == LLAMA_DEFAULT_SEED) {
  8273. seed = time(NULL);
  8274. }
  8275. ctx->rng.seed(seed);
  8276. }
  8277. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  8278. GGML_ASSERT(candidates->size > 0);
  8279. const int64_t t_start_sample_us = ggml_time_us();
  8280. // Sort the logits in descending order
  8281. if (!candidates->sorted) {
  8282. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  8283. return a.logit > b.logit;
  8284. });
  8285. candidates->sorted = true;
  8286. }
  8287. float max_l = candidates->data[0].logit;
  8288. float cum_sum = 0.0f;
  8289. for (size_t i = 0; i < candidates->size; ++i) {
  8290. float p = expf(candidates->data[i].logit - max_l);
  8291. candidates->data[i].p = p;
  8292. cum_sum += p;
  8293. }
  8294. for (size_t i = 0; i < candidates->size; ++i) {
  8295. candidates->data[i].p /= cum_sum;
  8296. }
  8297. if (ctx) {
  8298. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8299. }
  8300. }
  8301. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  8302. // TODO: move bucket sort to separate function so that top_p/tail_free/typical/softmax first is equally fast
  8303. // if (k >= (int32_t)candidates->size) {
  8304. // return;
  8305. // }
  8306. const int64_t t_start_sample_us = ggml_time_us();
  8307. if (k <= 0) {
  8308. k = candidates->size;
  8309. }
  8310. k = std::max(k, (int) min_keep);
  8311. k = std::min(k, (int) candidates->size);
  8312. // Sort scores in descending order
  8313. if (!candidates->sorted) {
  8314. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  8315. return a.logit > b.logit;
  8316. };
  8317. if (k <= 128) {
  8318. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  8319. } else {
  8320. constexpr int nbuckets = 128;
  8321. constexpr float bucket_low = -10.0f;
  8322. constexpr float bucket_high = 10.0f;
  8323. constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
  8324. constexpr float bucker_inter = -bucket_low * bucket_scale;
  8325. std::vector<int> bucket_idx(candidates->size);
  8326. std::vector<int> histo(nbuckets, 0);
  8327. for (int i = 0; i < (int)candidates->size; ++i) {
  8328. const float val = candidates->data[i].logit;
  8329. int ib = int(bucket_scale * val + bucker_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
  8330. ib = std::max(0, std::min(nbuckets-1, ib));
  8331. bucket_idx[i] = ib;
  8332. ++histo[ib];
  8333. }
  8334. int nhave = 0;
  8335. int ib = nbuckets - 1;
  8336. for ( ; ib >= 0; --ib) {
  8337. nhave += histo[ib];
  8338. if (nhave >= k) break;
  8339. }
  8340. std::vector<llama_token_data> tmp_tokens(nhave);
  8341. auto ptr = tmp_tokens.data();
  8342. std::vector<llama_token_data*> bucket_ptrs;
  8343. bucket_ptrs.reserve(nbuckets - ib);
  8344. for (int j = nbuckets - 1; j >= ib; --j) {
  8345. bucket_ptrs.push_back(ptr);
  8346. ptr += histo[j];
  8347. }
  8348. for (int i = 0; i < (int)candidates->size; ++i) {
  8349. int j = bucket_idx[i];
  8350. if (j >= ib) {
  8351. *bucket_ptrs[nbuckets-1-j]++ = candidates->data[i];
  8352. }
  8353. }
  8354. ptr = tmp_tokens.data();
  8355. int ndone = 0;
  8356. for (int j = nbuckets-1; j > ib; --j) {
  8357. std::sort(ptr, ptr + histo[j], comp);
  8358. ptr += histo[j];
  8359. ndone += histo[j];
  8360. }
  8361. std::partial_sort(ptr, ptr + k - ndone, ptr + histo[ib], comp);
  8362. std::memcpy(candidates->data, tmp_tokens.data(), k*sizeof(llama_token_data));
  8363. }
  8364. candidates->sorted = true;
  8365. }
  8366. candidates->size = k;
  8367. if (ctx) {
  8368. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8369. }
  8370. }
  8371. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  8372. if (p >= 1.0f) {
  8373. return;
  8374. }
  8375. llama_sample_softmax(ctx, candidates);
  8376. const int64_t t_start_sample_us = ggml_time_us();
  8377. // Compute the cumulative probabilities
  8378. float cum_sum = 0.0f;
  8379. size_t last_idx = candidates->size;
  8380. for (size_t i = 0; i < candidates->size; ++i) {
  8381. cum_sum += candidates->data[i].p;
  8382. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  8383. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  8384. if (cum_sum >= p && i + 1 >= min_keep) {
  8385. last_idx = i + 1;
  8386. break;
  8387. }
  8388. }
  8389. // Resize the output vector to keep only the top-p tokens
  8390. candidates->size = last_idx;
  8391. if (ctx) {
  8392. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8393. }
  8394. }
  8395. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  8396. if (p <= 0.0f || !candidates->size) {
  8397. return;
  8398. }
  8399. const int64_t t_start_sample_us = ggml_time_us();
  8400. bool min_p_applied = false;
  8401. // if the candidates aren't sorted, try the unsorted implementation first
  8402. if (!candidates->sorted) {
  8403. std::vector<llama_token_data> filtered_tokens;
  8404. float max_logit = -FLT_MAX;
  8405. for (size_t i = 0; i < candidates->size; ++i) {
  8406. max_logit = std::max(max_logit, candidates->data[i].logit);
  8407. }
  8408. const float min_logit = max_logit + logf(p); // min logit for p_i >= p * p_max
  8409. for (size_t i = 0; i < candidates->size; ++i) {
  8410. if (candidates->data[i].logit >= min_logit) {
  8411. filtered_tokens.push_back(candidates->data[i]);
  8412. }
  8413. }
  8414. // if we have enough values the operation was a success
  8415. if (filtered_tokens.size() >= min_keep) {
  8416. memcpy(candidates->data, filtered_tokens.data(), filtered_tokens.size()*sizeof(llama_token_data));
  8417. candidates->size = filtered_tokens.size();
  8418. min_p_applied = true;
  8419. }
  8420. }
  8421. // if the candidates are sorted or the unsorted implementation failed, use this implementation
  8422. if (!min_p_applied) {
  8423. // Sort the logits in descending order
  8424. if (!candidates->sorted) {
  8425. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  8426. return a.logit > b.logit;
  8427. });
  8428. candidates->sorted = true;
  8429. }
  8430. const float min_logit = candidates->data[0].logit + logf(p); // min logit for p_i >= p * p_max
  8431. size_t i = 1; // first token always matches
  8432. for (; i < candidates->size; ++i) {
  8433. if (candidates->data[i].logit < min_logit && i >= min_keep) {
  8434. break; // prob too small
  8435. }
  8436. }
  8437. // Resize the output vector to keep only the matching tokens
  8438. candidates->size = i;
  8439. }
  8440. if (ctx) {
  8441. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8442. }
  8443. }
  8444. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  8445. if (z >= 1.0f || candidates->size <= 2) {
  8446. return;
  8447. }
  8448. llama_sample_softmax(nullptr, candidates);
  8449. const int64_t t_start_sample_us = ggml_time_us();
  8450. // Compute the first and second derivatives
  8451. std::vector<float> first_derivatives(candidates->size - 1);
  8452. std::vector<float> second_derivatives(candidates->size - 2);
  8453. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  8454. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  8455. }
  8456. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  8457. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  8458. }
  8459. // Calculate absolute value of second derivatives
  8460. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  8461. second_derivatives[i] = std::abs(second_derivatives[i]);
  8462. }
  8463. // Normalize the second derivatives
  8464. {
  8465. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  8466. if (second_derivatives_sum > 1e-6f) {
  8467. for (float & value : second_derivatives) {
  8468. value /= second_derivatives_sum;
  8469. }
  8470. } else {
  8471. for (float & value : second_derivatives) {
  8472. value = 1.0f / second_derivatives.size();
  8473. }
  8474. }
  8475. }
  8476. float cum_sum = 0.0f;
  8477. size_t last_idx = candidates->size;
  8478. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  8479. cum_sum += second_derivatives[i];
  8480. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  8481. if (cum_sum > z && i >= min_keep) {
  8482. last_idx = i;
  8483. break;
  8484. }
  8485. }
  8486. // Resize the output vector to keep only the tokens above the tail location
  8487. candidates->size = last_idx;
  8488. if (ctx) {
  8489. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8490. }
  8491. }
  8492. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  8493. // Reference implementation:
  8494. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  8495. if (p >= 1.0f) {
  8496. return;
  8497. }
  8498. // Compute the softmax of logits and calculate entropy
  8499. llama_sample_softmax(nullptr, candidates);
  8500. const int64_t t_start_sample_us = ggml_time_us();
  8501. float entropy = 0.0f;
  8502. for (size_t i = 0; i < candidates->size; ++i) {
  8503. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  8504. }
  8505. // Compute the absolute difference between negative log probability and entropy for each candidate
  8506. std::vector<float> shifted_scores;
  8507. for (size_t i = 0; i < candidates->size; ++i) {
  8508. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  8509. shifted_scores.push_back(shifted_score);
  8510. }
  8511. // Sort tokens based on the shifted_scores and their corresponding indices
  8512. std::vector<size_t> indices(candidates->size);
  8513. std::iota(indices.begin(), indices.end(), 0);
  8514. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  8515. return shifted_scores[a] < shifted_scores[b];
  8516. });
  8517. // Compute the cumulative probabilities
  8518. float cum_sum = 0.0f;
  8519. size_t last_idx = indices.size();
  8520. for (size_t i = 0; i < indices.size(); ++i) {
  8521. size_t idx = indices[i];
  8522. cum_sum += candidates->data[idx].p;
  8523. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  8524. if (cum_sum > p && i >= min_keep - 1) {
  8525. last_idx = i + 1;
  8526. break;
  8527. }
  8528. }
  8529. // Resize the output vector to keep only the locally typical tokens
  8530. std::vector<llama_token_data> new_candidates;
  8531. for (size_t i = 0; i < last_idx; ++i) {
  8532. size_t idx = indices[i];
  8533. new_candidates.push_back(candidates->data[idx]);
  8534. }
  8535. // Replace the data in candidates with the new_candidates data
  8536. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  8537. candidates->size = new_candidates.size();
  8538. candidates->sorted = false;
  8539. if (ctx) {
  8540. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8541. }
  8542. }
  8543. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  8544. const int64_t t_start_sample_us = ggml_time_us();
  8545. // no need to do anything if there is only one (or zero) candidates
  8546. if(candidates_p->size <= 1) {
  8547. return;
  8548. }
  8549. // Calculate maximum possible entropy
  8550. float max_entropy = -logf(1.0f / candidates_p->size);
  8551. llama_sample_softmax(nullptr, candidates_p);
  8552. // Calculate entropy of the softmax probabilities
  8553. float entropy = 0.0f;
  8554. for (size_t i = 0; i < candidates_p->size; ++i) {
  8555. float prob = candidates_p->data[i].p;
  8556. if (prob > 0.0f) { // Ensure no log(0)
  8557. entropy -= prob * logf(prob);
  8558. }
  8559. }
  8560. // Normalize the entropy (max_entropy cannot be 0 here because we checked candidates_p->size != 1 above)
  8561. float normalized_entropy = entropy / max_entropy;
  8562. // Map the normalized entropy to the desired temperature range using the power function
  8563. float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);
  8564. #ifdef DEBUG
  8565. LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
  8566. LLAMA_LOG_INFO("Entropy: %f\n", entropy);
  8567. LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
  8568. LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
  8569. LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
  8570. LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
  8571. #endif
  8572. // Apply the dynamically calculated temperature scaling
  8573. for (size_t i = 0; i < candidates_p->size; ++i) {
  8574. candidates_p->data[i].logit /= dyn_temp;
  8575. }
  8576. // Re-compute softmax probabilities after scaling logits with dynamic temperature
  8577. double max_l_double = candidates_p->data[0].logit;
  8578. double cum_sum_double = 0.0;
  8579. for (size_t i = 0; i < candidates_p->size; ++i) {
  8580. double p = exp(candidates_p->data[i].logit - max_l_double);
  8581. candidates_p->data[i].p = p; // Store the scaled probability
  8582. cum_sum_double += p;
  8583. }
  8584. for (size_t i = 0; i < candidates_p->size; ++i) {
  8585. candidates_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
  8586. }
  8587. #ifdef DEBUG
  8588. // Print the updated top 25 probabilities after temperature scaling
  8589. LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
  8590. for (size_t i = 0; i < 25 && i < candidates_p->size; ++i) {
  8591. LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, candidates_p->data[i].p * 100.0f);
  8592. }
  8593. #endif
  8594. if (ctx) {
  8595. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8596. }
  8597. }
  8598. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  8599. const int64_t t_start_sample_us = ggml_time_us();
  8600. for (size_t i = 0; i < candidates_p->size; ++i) {
  8601. candidates_p->data[i].logit /= temp;
  8602. }
  8603. if (ctx) {
  8604. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8605. }
  8606. }
  8607. void llama_sample_repetition_penalties(
  8608. struct llama_context * ctx,
  8609. llama_token_data_array * candidates,
  8610. const llama_token * last_tokens,
  8611. size_t penalty_last_n,
  8612. float penalty_repeat,
  8613. float penalty_freq,
  8614. float penalty_present) {
  8615. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  8616. return;
  8617. }
  8618. const int64_t t_start_sample_us = ggml_time_us();
  8619. // Create a frequency map to count occurrences of each token in last_tokens
  8620. std::unordered_map<llama_token, int> token_count;
  8621. for (size_t i = 0; i < penalty_last_n; ++i) {
  8622. token_count[last_tokens[i]]++;
  8623. }
  8624. // Apply frequency and presence penalties to the candidates
  8625. for (size_t i = 0; i < candidates->size; ++i) {
  8626. const auto token_iter = token_count.find(candidates->data[i].id);
  8627. if (token_iter == token_count.end()) {
  8628. continue;
  8629. }
  8630. const int count = token_iter->second;
  8631. // 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.
  8632. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  8633. if (candidates->data[i].logit <= 0) {
  8634. candidates->data[i].logit *= penalty_repeat;
  8635. } else {
  8636. candidates->data[i].logit /= penalty_repeat;
  8637. }
  8638. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  8639. }
  8640. candidates->sorted = false;
  8641. if (ctx) {
  8642. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8643. }
  8644. }
  8645. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  8646. GGML_ASSERT(ctx);
  8647. const int64_t t_start_sample_us = ggml_time_us();
  8648. bool allow_eos = false;
  8649. for (const auto & stack : grammar->stacks) {
  8650. if (stack.empty()) {
  8651. allow_eos = true;
  8652. break;
  8653. }
  8654. }
  8655. const llama_token eos = llama_token_eos(&ctx->model);
  8656. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  8657. candidates_decoded.reserve(candidates->size);
  8658. std::vector<llama_grammar_candidate> candidates_grammar;
  8659. candidates_grammar.reserve(candidates->size);
  8660. for (size_t i = 0; i < candidates->size; ++i) {
  8661. const llama_token id = candidates->data[i].id;
  8662. const std::string piece = llama_token_to_piece(ctx, id);
  8663. if (id == eos) {
  8664. if (!allow_eos) {
  8665. candidates->data[i].logit = -INFINITY;
  8666. }
  8667. } else if (piece.empty() || piece[0] == 0) {
  8668. candidates->data[i].logit = -INFINITY;
  8669. } else {
  8670. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  8671. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  8672. }
  8673. }
  8674. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  8675. for (const auto & reject : rejects) {
  8676. candidates->data[reject.index].logit = -INFINITY;
  8677. }
  8678. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8679. }
  8680. static void llama_log_softmax(float * array, size_t size) {
  8681. float max_l = *std::max_element(array, array + size);
  8682. float sum = 0.f;
  8683. for (size_t i = 0; i < size; ++i) {
  8684. float p = expf(array[i] - max_l);
  8685. sum += p;
  8686. array[i] = p;
  8687. }
  8688. for (size_t i = 0; i < size; ++i) {
  8689. array[i] = logf(array[i] / sum);
  8690. }
  8691. }
  8692. void llama_sample_apply_guidance(
  8693. struct llama_context * ctx,
  8694. float * logits,
  8695. float * logits_guidance,
  8696. float scale) {
  8697. GGML_ASSERT(ctx);
  8698. const auto t_start_sample_us = ggml_time_us();
  8699. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  8700. llama_log_softmax(logits, n_vocab);
  8701. llama_log_softmax(logits_guidance, n_vocab);
  8702. for (int i = 0; i < n_vocab; ++i) {
  8703. auto & l = logits[i];
  8704. const auto & g = logits_guidance[i];
  8705. l = scale * (l - g) + g;
  8706. }
  8707. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8708. }
  8709. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  8710. GGML_ASSERT(ctx);
  8711. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  8712. int64_t t_start_sample_us;
  8713. t_start_sample_us = ggml_time_us();
  8714. llama_sample_softmax(nullptr, candidates);
  8715. // Estimate s_hat using the most probable m tokens
  8716. float s_hat = 0.0;
  8717. float sum_ti_bi = 0.0;
  8718. float sum_ti_sq = 0.0;
  8719. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  8720. float t_i = logf(float(i + 2) / float(i + 1));
  8721. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  8722. sum_ti_bi += t_i * b_i;
  8723. sum_ti_sq += t_i * t_i;
  8724. }
  8725. s_hat = sum_ti_bi / sum_ti_sq;
  8726. // Compute k from the estimated s_hat and target surprise value
  8727. float epsilon_hat = s_hat - 1;
  8728. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  8729. // Sample the next word X using top-k sampling
  8730. llama_sample_top_k(nullptr, candidates, int(k), 1);
  8731. if (ctx) {
  8732. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8733. }
  8734. llama_token X = llama_sample_token(ctx, candidates);
  8735. t_start_sample_us = ggml_time_us();
  8736. // Compute error as the difference between observed surprise and target surprise value
  8737. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  8738. return candidate.id == X;
  8739. }));
  8740. float observed_surprise = -log2f(candidates->data[X_idx].p);
  8741. float e = observed_surprise - tau;
  8742. // Update mu using the learning rate and error
  8743. *mu = *mu - eta * e;
  8744. if (ctx) {
  8745. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8746. }
  8747. return X;
  8748. }
  8749. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  8750. int64_t t_start_sample_us;
  8751. t_start_sample_us = ggml_time_us();
  8752. llama_sample_softmax(ctx, candidates);
  8753. // Truncate the words with surprise values greater than mu
  8754. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  8755. return -log2f(candidate.p) > *mu;
  8756. }));
  8757. if (candidates->size == 0) {
  8758. candidates->size = 1;
  8759. }
  8760. if (ctx) {
  8761. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8762. }
  8763. // Normalize the probabilities of the remaining words
  8764. llama_sample_softmax(ctx, candidates);
  8765. // Sample the next word X from the remaining words
  8766. llama_token X = llama_sample_token(ctx, candidates);
  8767. t_start_sample_us = ggml_time_us();
  8768. // Compute error as the difference between observed surprise and target surprise value
  8769. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  8770. return candidate.id == X;
  8771. }));
  8772. float observed_surprise = -log2f(candidates->data[X_idx].p);
  8773. float e = observed_surprise - tau;
  8774. // Update mu using the learning rate and error
  8775. *mu = *mu - eta * e;
  8776. if (ctx) {
  8777. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8778. }
  8779. return X;
  8780. }
  8781. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  8782. const int64_t t_start_sample_us = ggml_time_us();
  8783. // Find max element
  8784. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  8785. return a.logit < b.logit;
  8786. });
  8787. llama_token result = max_iter->id;
  8788. if (ctx) {
  8789. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8790. ctx->n_sample++;
  8791. }
  8792. return result;
  8793. }
  8794. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  8795. GGML_ASSERT(ctx);
  8796. const int64_t t_start_sample_us = ggml_time_us();
  8797. llama_sample_softmax(nullptr, candidates);
  8798. std::vector<float> probs;
  8799. probs.reserve(candidates->size);
  8800. for (size_t i = 0; i < candidates->size; ++i) {
  8801. probs.push_back(candidates->data[i].p);
  8802. }
  8803. std::discrete_distribution<> dist(probs.begin(), probs.end());
  8804. auto & rng = ctx->rng;
  8805. int idx = dist(rng);
  8806. llama_token result = candidates->data[idx].id;
  8807. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8808. ctx->n_sample++;
  8809. return result;
  8810. }
  8811. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  8812. const int64_t t_start_sample_us = ggml_time_us();
  8813. if (token == llama_token_eos(&ctx->model)) {
  8814. for (const auto & stack : grammar->stacks) {
  8815. if (stack.empty()) {
  8816. return;
  8817. }
  8818. }
  8819. GGML_ASSERT(false);
  8820. }
  8821. const std::string piece = llama_token_to_piece(ctx, token);
  8822. // Note terminating 0 in decoded string
  8823. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  8824. const auto & code_points = decoded.first;
  8825. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  8826. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  8827. }
  8828. grammar->partial_utf8 = decoded.second;
  8829. GGML_ASSERT(!grammar->stacks.empty());
  8830. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8831. }
  8832. //
  8833. // Beam search
  8834. //
  8835. struct llama_beam {
  8836. std::vector<llama_token> tokens;
  8837. float p; // Cumulative beam probability (renormalized relative to all beams)
  8838. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  8839. // Sort beams by probability. In case of ties, prefer beams at eob.
  8840. bool operator<(const llama_beam & rhs) const {
  8841. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  8842. }
  8843. // Shift off first n tokens and discard them.
  8844. void shift_tokens(const size_t n) {
  8845. if (n) {
  8846. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  8847. tokens.resize(tokens.size() - n);
  8848. }
  8849. }
  8850. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  8851. };
  8852. // A struct for calculating logit-related info.
  8853. struct llama_logit_info {
  8854. const float * const logits;
  8855. const int n_vocab;
  8856. const float max_l;
  8857. const float normalizer;
  8858. struct sum_exp {
  8859. float max_l;
  8860. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  8861. };
  8862. llama_logit_info(llama_context * ctx)
  8863. : logits(llama_get_logits(ctx))
  8864. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  8865. , max_l(*std::max_element(logits, logits + n_vocab))
  8866. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  8867. { }
  8868. llama_token_data get_token_data(const llama_token token_id) const {
  8869. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  8870. return {token_id, logits[token_id], p};
  8871. }
  8872. // Return top k token_data by logit.
  8873. std::vector<llama_token_data> top_k(size_t k) {
  8874. std::vector<llama_token_data> min_heap; // min-heap by logit
  8875. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  8876. min_heap.reserve(k_min);
  8877. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  8878. min_heap.push_back(get_token_data(token_id));
  8879. }
  8880. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  8881. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  8882. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  8883. if (min_heap.front().logit < logits[token_id]) {
  8884. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  8885. min_heap.back().id = token_id;
  8886. min_heap.back().logit = logits[token_id];
  8887. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  8888. }
  8889. }
  8890. return min_heap;
  8891. }
  8892. float probability_from_logit(float logit) const {
  8893. return normalizer * std::exp(logit - max_l);
  8894. }
  8895. };
  8896. struct llama_beam_search_data {
  8897. llama_context * ctx;
  8898. size_t n_beams;
  8899. int n_past;
  8900. int n_predict;
  8901. std::vector<llama_beam> beams;
  8902. std::vector<llama_beam> next_beams;
  8903. // Re-calculated on each loop iteration
  8904. size_t common_prefix_length;
  8905. // Used to communicate to/from callback on beams state.
  8906. std::vector<llama_beam_view> beam_views;
  8907. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  8908. : ctx(ctx)
  8909. , n_beams(n_beams)
  8910. , n_past(n_past)
  8911. , n_predict(n_predict)
  8912. , beam_views(n_beams) {
  8913. beams.reserve(n_beams);
  8914. next_beams.reserve(n_beams);
  8915. }
  8916. // Collapse beams to a single beam given by index.
  8917. void collapse_beams(const size_t beam_idx) {
  8918. if (0u < beam_idx) {
  8919. std::swap(beams[0], beams[beam_idx]);
  8920. }
  8921. beams.resize(1);
  8922. }
  8923. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  8924. // The repetitive patterns below reflect the 2 stages of heaps:
  8925. // * Gather elements until the vector is full, then call std::make_heap() on it.
  8926. // * If the heap is full and a new element is found that should be included, pop the
  8927. // least element to the back(), replace it with the new, then push it into the heap.
  8928. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  8929. // Min-heaps use a greater-than comparator.
  8930. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  8931. if (beam.eob) {
  8932. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  8933. if (next_beams.size() < n_beams) {
  8934. next_beams.push_back(std::move(beam));
  8935. if (next_beams.size() == n_beams) {
  8936. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  8937. }
  8938. } else if (next_beams.front().p < beam.p) {
  8939. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8940. next_beams.back() = std::move(beam);
  8941. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8942. }
  8943. } else {
  8944. // beam is not at end-of-sentence, so branch with next top_k tokens.
  8945. if (!beam.tokens.empty()) {
  8946. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  8947. }
  8948. llama_logit_info logit_info(ctx);
  8949. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  8950. size_t i=0;
  8951. if (next_beams.size() < n_beams) {
  8952. for (; next_beams.size() < n_beams ; ++i) {
  8953. llama_beam next_beam = beam;
  8954. next_beam.tokens.push_back(next_tokens[i].id);
  8955. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  8956. next_beams.push_back(std::move(next_beam));
  8957. }
  8958. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  8959. } else {
  8960. for (; next_beams.front().p == 0.0f ; ++i) {
  8961. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8962. next_beams.back() = beam;
  8963. next_beams.back().tokens.push_back(next_tokens[i].id);
  8964. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  8965. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8966. }
  8967. }
  8968. for (; i < n_beams ; ++i) {
  8969. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  8970. if (next_beams.front().p < next_p) {
  8971. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8972. next_beams.back() = beam;
  8973. next_beams.back().tokens.push_back(next_tokens[i].id);
  8974. next_beams.back().p = next_p;
  8975. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8976. }
  8977. }
  8978. }
  8979. }
  8980. // Find common_prefix_length based on beams.
  8981. // Requires beams is not empty.
  8982. size_t find_common_prefix_length() {
  8983. size_t common_prefix_length = beams[0].tokens.size();
  8984. for (size_t i = 1 ; i < beams.size() ; ++i) {
  8985. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  8986. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  8987. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  8988. common_prefix_length = j;
  8989. break;
  8990. }
  8991. }
  8992. }
  8993. return common_prefix_length;
  8994. }
  8995. // Construct beams_state to send back to caller via the callback function.
  8996. // Side effect: set common_prefix_length = find_common_prefix_length();
  8997. llama_beams_state get_beams_state(const bool last_call) {
  8998. for (size_t i = 0 ; i < beams.size() ; ++i) {
  8999. beam_views[i] = beams[i].view();
  9000. }
  9001. common_prefix_length = find_common_prefix_length();
  9002. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  9003. }
  9004. // Loop:
  9005. // * while i < n_predict, AND
  9006. // * any of the beams have not yet reached end-of-beam (eob), AND
  9007. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  9008. // (since all other beam probabilities can only decrease)
  9009. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  9010. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  9011. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  9012. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  9013. !beams[top_beam_index()].eob ; ++i) {
  9014. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  9015. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  9016. if (common_prefix_length) {
  9017. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  9018. n_past += common_prefix_length;
  9019. }
  9020. // Zero-out next_beam probabilities to place them last in following min-heap.
  9021. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  9022. for (llama_beam & beam : beams) {
  9023. beam.shift_tokens(common_prefix_length);
  9024. fill_next_beams_by_top_probabilities(beam);
  9025. }
  9026. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  9027. beams.swap(next_beams);
  9028. renormalize_beam_probabilities(beams);
  9029. }
  9030. collapse_beams(top_beam_index());
  9031. callback(callback_data, get_beams_state(true));
  9032. }
  9033. // As beams grow, the cumulative probabilities decrease.
  9034. // Renormalize them to avoid floating point underflow.
  9035. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  9036. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  9037. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  9038. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  9039. }
  9040. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  9041. size_t top_beam_index() {
  9042. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  9043. }
  9044. // Copy (p,eob) for each beam which may have been changed by the callback.
  9045. void update_beams_from_beam_views() {
  9046. for (size_t i = 0 ; i < beams.size() ; ++i) {
  9047. beams[i].p = beam_views[i].p;
  9048. beams[i].eob = beam_views[i].eob;
  9049. }
  9050. }
  9051. };
  9052. void llama_beam_search(llama_context * ctx,
  9053. llama_beam_search_callback_fn_t callback, void * callback_data,
  9054. size_t n_beams, int n_past, int n_predict) {
  9055. assert(ctx);
  9056. const int64_t t_start_sample_us = ggml_time_us();
  9057. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  9058. beam_search_data.loop(callback, callback_data);
  9059. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9060. ctx->n_sample++;
  9061. }
  9062. //
  9063. // quantization
  9064. //
  9065. struct quantize_state_internal {
  9066. const llama_model & model;
  9067. const llama_model_quantize_params * params;
  9068. int n_attention_wv = 0;
  9069. int n_ffn_down = 0;
  9070. int n_ffn_gate = 0;
  9071. int n_ffn_up = 0;
  9072. int i_attention_wv = 0;
  9073. int i_ffn_down = 0;
  9074. int i_ffn_gate = 0;
  9075. int i_ffn_up = 0;
  9076. int n_k_quantized = 0;
  9077. int n_fallback = 0;
  9078. bool has_imatrix = false;
  9079. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  9080. : model(model)
  9081. , params(params)
  9082. {}
  9083. };
  9084. static void llama_tensor_dequantize_internal(
  9085. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  9086. const size_t nelements, const int nthread
  9087. ) {
  9088. if (output.size() < nelements) {
  9089. output.resize(nelements);
  9090. }
  9091. float * f32_output = (float *) output.data();
  9092. ggml_type_traits_t qtype;
  9093. if (ggml_is_quantized(tensor->type)) {
  9094. qtype = ggml_internal_get_type_traits(tensor->type);
  9095. if (qtype.to_float == NULL) {
  9096. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  9097. }
  9098. } else if (tensor->type != GGML_TYPE_F16) {
  9099. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  9100. }
  9101. if (nthread < 2) {
  9102. if (tensor->type == GGML_TYPE_F16) {
  9103. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  9104. } else if (ggml_is_quantized(tensor->type)) {
  9105. qtype.to_float(tensor->data, f32_output, nelements);
  9106. } else {
  9107. GGML_ASSERT(false); // unreachable
  9108. }
  9109. return;
  9110. }
  9111. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  9112. size_t block_size_bytes = ggml_type_size(tensor->type);
  9113. GGML_ASSERT(nelements % block_size == 0);
  9114. size_t nblocks = nelements / block_size;
  9115. size_t blocks_per_thread = nblocks / nthread;
  9116. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  9117. size_t in_buff_offs = 0;
  9118. size_t out_buff_offs = 0;
  9119. for (int tnum = 0; tnum < nthread; tnum++) {
  9120. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  9121. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  9122. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  9123. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  9124. if (typ == GGML_TYPE_F16) {
  9125. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  9126. } else {
  9127. qtype.to_float(inbuf, outbuf, nels);
  9128. }
  9129. };
  9130. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  9131. in_buff_offs += thr_block_bytes;
  9132. out_buff_offs += thr_elems;
  9133. }
  9134. for (auto & w : workers) { w.join(); }
  9135. workers.clear();
  9136. }
  9137. static ggml_type get_k_quant_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  9138. const std::string name = ggml_get_name(tensor);
  9139. // TODO: avoid hardcoded tensor names - use the TN_* constants
  9140. const llm_arch arch = qs.model.arch;
  9141. const auto tn = LLM_TN(arch);
  9142. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  9143. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  9144. };
  9145. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  9146. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  9147. if (n_expert > 1) {
  9148. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  9149. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  9150. // for getting the current layer as I initially thought, and we need to resort to parsing the
  9151. // tensor name.
  9152. n_layer /= n_expert;
  9153. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  9154. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  9155. }
  9156. if (i_layer < 0 || i_layer >= n_layer) {
  9157. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  9158. }
  9159. }
  9160. return std::make_pair(i_layer, n_layer);
  9161. };
  9162. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  9163. // with the quantization of the output tensor
  9164. if (name == tn(LLM_TENSOR_OUTPUT, "weight") ||
  9165. (LLM_TENSOR_NAMES.at(arch).find(LLM_TENSOR_OUTPUT) == LLM_TENSOR_NAMES.at(arch).end() && name == "token_embd.weight")) {
  9166. int nx = tensor->ne[0];
  9167. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  9168. new_type = GGML_TYPE_Q8_0;
  9169. }
  9170. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  9171. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  9172. new_type = GGML_TYPE_Q5_K;
  9173. }
  9174. else if (new_type != GGML_TYPE_Q8_0) {
  9175. new_type = GGML_TYPE_Q6_K;
  9176. }
  9177. } else if (name == "token_embd.weight") {
  9178. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
  9179. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) {
  9180. new_type = GGML_TYPE_Q2_K;
  9181. }
  9182. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  9183. new_type = GGML_TYPE_IQ3_S;
  9184. }
  9185. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  9186. new_type = GGML_TYPE_IQ3_S;
  9187. }
  9188. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  9189. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  9190. if (name.find("attn_v.weight") != std::string::npos) {
  9191. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  9192. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  9193. ++qs.i_attention_wv;
  9194. }
  9195. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  9196. new_type = GGML_TYPE_Q4_K;
  9197. }
  9198. else if (name.find("ffn_down") != std::string::npos) {
  9199. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  9200. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  9201. }
  9202. ++qs.i_ffn_down;
  9203. }
  9204. else if (name.find("attn_output.weight") != std::string::npos) {
  9205. if (qs.model.hparams.n_expert == 8) {
  9206. new_type = GGML_TYPE_Q5_K;
  9207. } else {
  9208. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) new_type = GGML_TYPE_IQ2_XXS;
  9209. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  9210. }
  9211. }
  9212. } else if (name.find("attn_v.weight") != std::string::npos) {
  9213. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  9214. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  9215. }
  9216. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  9217. new_type = GGML_TYPE_Q4_K;
  9218. }
  9219. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  9220. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  9221. }
  9222. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_S && qs.model.hparams.n_gqa() >= 4) {
  9223. new_type = GGML_TYPE_Q4_K;
  9224. }
  9225. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  9226. new_type = GGML_TYPE_Q4_K;
  9227. }
  9228. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_S && qs.model.hparams.n_gqa() >= 4) {
  9229. new_type = GGML_TYPE_Q4_K;
  9230. }
  9231. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  9232. new_type = GGML_TYPE_Q4_K;
  9233. }
  9234. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  9235. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  9236. }
  9237. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  9238. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  9239. new_type = GGML_TYPE_Q5_K;
  9240. }
  9241. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  9242. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  9243. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  9244. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  9245. (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;
  9246. if (qs.model.type == MODEL_70B) {
  9247. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  9248. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  9249. // nearly negligible increase in model size by quantizing this tensor with more bits:
  9250. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  9251. }
  9252. if (qs.model.hparams.n_expert == 8) {
  9253. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  9254. // TODO: explore better strategies
  9255. new_type = GGML_TYPE_Q8_0;
  9256. }
  9257. ++qs.i_attention_wv;
  9258. } else if (name.find("attn_k.weight") != std::string::npos) {
  9259. if (qs.model.hparams.n_expert == 8) {
  9260. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  9261. // TODO: explore better strategies
  9262. new_type = GGML_TYPE_Q8_0;
  9263. }
  9264. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  9265. new_type = GGML_TYPE_IQ3_XXS;
  9266. }
  9267. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  9268. new_type = GGML_TYPE_IQ2_S;
  9269. }
  9270. } else if (name.find("attn_q.weight") != std::string::npos) {
  9271. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  9272. new_type = GGML_TYPE_IQ3_XXS;
  9273. }
  9274. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  9275. new_type = GGML_TYPE_IQ2_S;
  9276. }
  9277. } else if (name.find("ffn_down") != std::string::npos) {
  9278. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  9279. int i_layer = info.first, n_layer = info.second;
  9280. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  9281. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  9282. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  9283. }
  9284. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  9285. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  9286. }
  9287. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  9288. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  9289. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  9290. : GGML_TYPE_Q3_K;
  9291. }
  9292. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  9293. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  9294. new_type = GGML_TYPE_Q4_K;
  9295. }
  9296. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  9297. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  9298. }
  9299. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  9300. if (arch == LLM_ARCH_FALCON) {
  9301. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  9302. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  9303. } else {
  9304. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  9305. }
  9306. }
  9307. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  9308. new_type = GGML_TYPE_Q5_K;
  9309. }
  9310. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  9311. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  9312. new_type = GGML_TYPE_Q5_K;
  9313. }
  9314. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  9315. && qs.has_imatrix && i_layer < n_layer/8) {
  9316. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  9317. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  9318. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  9319. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  9320. }
  9321. ++qs.i_ffn_down;
  9322. } else if (name.find("attn_output.weight") != std::string::npos) {
  9323. if (arch != LLM_ARCH_FALCON) {
  9324. if (qs.model.hparams.n_expert == 8) {
  9325. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  9326. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  9327. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  9328. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  9329. new_type = GGML_TYPE_Q5_K;
  9330. }
  9331. } else {
  9332. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  9333. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  9334. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  9335. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  9336. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  9337. }
  9338. } else {
  9339. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  9340. }
  9341. }
  9342. else if (name.find("attn_qkv.weight") != std::string::npos) {
  9343. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  9344. new_type = GGML_TYPE_Q4_K;
  9345. }
  9346. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  9347. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  9348. }
  9349. else if (name.find("ffn_gate") != std::string::npos) {
  9350. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  9351. int i_layer = info.first, n_layer = info.second;
  9352. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  9353. new_type = GGML_TYPE_IQ3_XXS;
  9354. }
  9355. ++qs.i_ffn_gate;
  9356. }
  9357. else if (name.find("ffn_up") != std::string::npos) {
  9358. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  9359. int i_layer = info.first, n_layer = info.second;
  9360. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  9361. new_type = GGML_TYPE_IQ3_XXS;
  9362. }
  9363. ++qs.i_ffn_up;
  9364. }
  9365. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  9366. //}
  9367. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  9368. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  9369. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  9370. //}
  9371. // This can be used to reduce the size of the Q5_K_S model.
  9372. // The associated PPL increase is fully in line with the size reduction
  9373. //else {
  9374. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  9375. //}
  9376. bool convert_incompatible_tensor = false;
  9377. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  9378. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  9379. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  9380. new_type == GGML_TYPE_IQ3_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || new_type == GGML_TYPE_IQ3_S) {
  9381. int nx = tensor->ne[0];
  9382. int ny = tensor->ne[1];
  9383. if (nx % QK_K != 0) {
  9384. 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));
  9385. convert_incompatible_tensor = true;
  9386. } else {
  9387. ++qs.n_k_quantized;
  9388. }
  9389. }
  9390. if (convert_incompatible_tensor) {
  9391. switch (new_type) {
  9392. case GGML_TYPE_IQ2_XXS:
  9393. case GGML_TYPE_IQ2_XS:
  9394. case GGML_TYPE_IQ2_S:
  9395. case GGML_TYPE_IQ3_XXS:
  9396. case GGML_TYPE_IQ3_S:
  9397. case GGML_TYPE_IQ1_S:
  9398. case GGML_TYPE_Q2_K:
  9399. case GGML_TYPE_Q3_K:
  9400. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  9401. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  9402. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  9403. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  9404. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  9405. }
  9406. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  9407. ++qs.n_fallback;
  9408. }
  9409. return new_type;
  9410. }
  9411. static int32_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, int64_t * hist_cur, const float * imatrix, std::vector<std::thread> & workers, const int nthread) {
  9412. std::mutex mutex;
  9413. int counter = 0;
  9414. size_t new_size = 0;
  9415. if (nthread < 2) {
  9416. // single-thread
  9417. return ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, hist_cur, imatrix);
  9418. }
  9419. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, chunk_size,
  9420. nrows, n_per_row, imatrix]() {
  9421. std::array<int64_t, 1 << 4> local_hist = {};
  9422. const int nrows_per_chunk = chunk_size / n_per_row;
  9423. size_t local_size = 0;
  9424. while (true) {
  9425. std::unique_lock<std::mutex> lock(mutex);
  9426. int first_row = counter; counter += nrows_per_chunk;
  9427. if (first_row >= nrows) {
  9428. if (local_size > 0) {
  9429. for (int j=0; j<int(local_hist.size()); ++j) {
  9430. hist_cur[j] += local_hist[j];
  9431. }
  9432. new_size += local_size;
  9433. }
  9434. break;
  9435. }
  9436. lock.unlock();
  9437. const int this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  9438. local_size += ggml_quantize_chunk(new_type, f32_data, new_data,
  9439. first_row * n_per_row, this_nrow, n_per_row, local_hist.data(), imatrix);
  9440. }
  9441. };
  9442. for (int it = 0; it < nthread - 1; ++it) {
  9443. workers.emplace_back(compute);
  9444. }
  9445. compute();
  9446. for (auto & w : workers) { w.join(); }
  9447. workers.clear();
  9448. return new_size;
  9449. }
  9450. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  9451. ggml_type quantized_type;
  9452. llama_ftype ftype = params->ftype;
  9453. switch (params->ftype) {
  9454. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  9455. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  9456. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  9457. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  9458. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  9459. case LLAMA_FTYPE_MOSTLY_F16: quantized_type = GGML_TYPE_F16; break;
  9460. case LLAMA_FTYPE_ALL_F32: quantized_type = GGML_TYPE_F32; break;
  9461. // K-quants
  9462. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  9463. case LLAMA_FTYPE_MOSTLY_Q2_K: quantized_type = GGML_TYPE_Q2_K; break;
  9464. case LLAMA_FTYPE_MOSTLY_IQ3_XS: quantized_type = GGML_TYPE_IQ3_S; break;
  9465. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  9466. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  9467. case LLAMA_FTYPE_MOSTLY_Q3_K_L: quantized_type = GGML_TYPE_Q3_K; break;
  9468. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  9469. case LLAMA_FTYPE_MOSTLY_Q4_K_M: quantized_type = GGML_TYPE_Q4_K; break;
  9470. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  9471. case LLAMA_FTYPE_MOSTLY_Q5_K_M: quantized_type = GGML_TYPE_Q5_K; break;
  9472. case LLAMA_FTYPE_MOSTLY_Q6_K: quantized_type = GGML_TYPE_Q6_K; break;
  9473. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: quantized_type = GGML_TYPE_IQ2_XXS; break;
  9474. case LLAMA_FTYPE_MOSTLY_IQ2_XS: quantized_type = GGML_TYPE_IQ2_XS; break;
  9475. case LLAMA_FTYPE_MOSTLY_IQ2_S: quantized_type = GGML_TYPE_IQ2_XS; break;
  9476. case LLAMA_FTYPE_MOSTLY_IQ2_M: quantized_type = GGML_TYPE_IQ2_S; break;
  9477. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: quantized_type = GGML_TYPE_IQ3_XXS; break;
  9478. case LLAMA_FTYPE_MOSTLY_IQ1_S: quantized_type = GGML_TYPE_IQ1_S; break;
  9479. case LLAMA_FTYPE_MOSTLY_IQ4_NL: quantized_type = GGML_TYPE_IQ4_NL; break;
  9480. case LLAMA_FTYPE_MOSTLY_IQ4_XS: quantized_type = GGML_TYPE_IQ4_XS; break;
  9481. case LLAMA_FTYPE_MOSTLY_IQ3_S: quantized_type = GGML_TYPE_IQ3_S; break;
  9482. case LLAMA_FTYPE_MOSTLY_IQ3_M: quantized_type = GGML_TYPE_IQ3_S; break;
  9483. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  9484. }
  9485. int nthread = params->nthread;
  9486. if (nthread <= 0) {
  9487. nthread = std::thread::hardware_concurrency();
  9488. }
  9489. // mmap consistently increases speed Linux, and also increases speed on Windows with
  9490. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  9491. #if defined(__linux__) || defined(_WIN32)
  9492. constexpr bool use_mmap = true;
  9493. #else
  9494. constexpr bool use_mmap = false;
  9495. #endif
  9496. llama_model_loader ml(fname_inp, use_mmap, NULL);
  9497. ml.init_mapping(false); // no prefetching?
  9498. llama_model model;
  9499. llm_load_arch(ml, model);
  9500. llm_load_hparams(ml, model);
  9501. struct quantize_state_internal qs(model, params);
  9502. if (params->only_copy) {
  9503. ftype = model.ftype;
  9504. }
  9505. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  9506. if (params->imatrix) {
  9507. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  9508. if (imatrix_data) {
  9509. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  9510. qs.has_imatrix = true;
  9511. }
  9512. }
  9513. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  9514. struct gguf_context * ctx_out = gguf_init_empty();
  9515. // copy the KV pairs from the input file
  9516. gguf_set_kv (ctx_out, ml.ctx_gguf);
  9517. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  9518. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  9519. for (int i = 0; i < ml.n_tensors; ++i) {
  9520. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  9521. const std::string name = ggml_get_name(meta);
  9522. // TODO: avoid hardcoded tensor names - use the TN_* constants
  9523. if (name.find("attn_v.weight") != std::string::npos || name.find("attn_qkv.weight") != std::string::npos) {
  9524. ++qs.n_attention_wv;
  9525. }
  9526. else if (name.find("ffn_down") != std::string::npos) {
  9527. ++qs.n_ffn_down;
  9528. }
  9529. else if (name.find("ffn_gate") != std::string::npos) {
  9530. ++qs.n_ffn_gate;
  9531. }
  9532. else if (name.find("ffn_up") != std::string::npos) {
  9533. ++qs.n_ffn_up;
  9534. }
  9535. }
  9536. if (qs.n_attention_wv != qs.n_ffn_down || (uint32_t)qs.n_attention_wv != model.hparams.n_layer) {
  9537. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_ffn_down = %d, hparams.n_layer = %d\n",
  9538. __func__, qs.n_attention_wv, qs.n_ffn_down, model.hparams.n_layer);
  9539. }
  9540. size_t total_size_org = 0;
  9541. size_t total_size_new = 0;
  9542. std::vector<int64_t> hist_all(1 << 4, 0);
  9543. std::vector<std::thread> workers;
  9544. workers.reserve(nthread);
  9545. int idx = 0;
  9546. std::vector<no_init<uint8_t>> read_data;
  9547. std::vector<no_init<uint8_t>> work;
  9548. std::vector<no_init<float>> f32_conv_buf;
  9549. // populate the original tensors so we get an initial meta data
  9550. for (int i = 0; i < ml.n_tensors; ++i) {
  9551. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  9552. gguf_add_tensor(ctx_out, meta);
  9553. }
  9554. std::ofstream fout(fname_out, std::ios::binary);
  9555. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  9556. const size_t meta_size = gguf_get_meta_size(ctx_out);
  9557. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  9558. // placeholder for the meta data
  9559. ::zeros(fout, meta_size);
  9560. for (int i = 0; i < ml.n_tensors; ++i) {
  9561. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  9562. const std::string name = ggml_get_name(tensor);
  9563. if (!ml.use_mmap) {
  9564. if (read_data.size() < ggml_nbytes(tensor)) {
  9565. read_data.resize(ggml_nbytes(tensor));
  9566. }
  9567. tensor->data = read_data.data();
  9568. }
  9569. ml.load_data_for(tensor);
  9570. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  9571. ++idx, ml.n_tensors,
  9572. ggml_get_name(tensor),
  9573. llama_format_tensor_shape(tensor).c_str(),
  9574. ggml_type_name(tensor->type));
  9575. // This used to be a regex, but <regex> has an extreme cost to compile times.
  9576. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  9577. // quantize only 2D tensors
  9578. quantize &= (ggml_n_dims(tensor) == 2);
  9579. quantize &= params->quantize_output_tensor || name != "output.weight";
  9580. quantize &= !params->only_copy;
  9581. // do not quantize expert gating tensors
  9582. // NOTE: can't use LLM_TN here because the layer number is not known
  9583. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  9584. // do not quantize positional embeddings and token types (BERT)
  9585. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  9586. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  9587. enum ggml_type new_type;
  9588. void * new_data;
  9589. size_t new_size;
  9590. if (quantize) {
  9591. new_type = quantized_type;
  9592. if (!params->pure) {
  9593. new_type = get_k_quant_type(qs, new_type, tensor, ftype);
  9594. }
  9595. // If we've decided to quantize to the same type the tensor is already
  9596. // in then there's nothing to do.
  9597. quantize = tensor->type != new_type;
  9598. }
  9599. if (!quantize) {
  9600. new_type = tensor->type;
  9601. new_data = tensor->data;
  9602. new_size = ggml_nbytes(tensor);
  9603. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  9604. } else {
  9605. const size_t nelements = ggml_nelements(tensor);
  9606. const float * imatrix = nullptr;
  9607. if (imatrix_data) {
  9608. auto it = imatrix_data->find(tensor->name);
  9609. if (it == imatrix_data->end()) {
  9610. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  9611. } else {
  9612. if (it->second.size() == (size_t)tensor->ne[0]) {
  9613. imatrix = it->second.data();
  9614. } else {
  9615. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  9616. int(it->second.size()), int(tensor->ne[0]), tensor->name);
  9617. }
  9618. }
  9619. }
  9620. if ((new_type == GGML_TYPE_IQ2_XXS ||
  9621. new_type == GGML_TYPE_IQ2_XS ||
  9622. new_type == GGML_TYPE_IQ2_S ||
  9623. new_type == GGML_TYPE_IQ1_S ||
  9624. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  9625. LLAMA_LOG_ERROR("\n\n============================================================\n");
  9626. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  9627. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  9628. LLAMA_LOG_ERROR("============================================================\n\n");
  9629. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  9630. }
  9631. float * f32_data;
  9632. if (tensor->type == GGML_TYPE_F32) {
  9633. f32_data = (float *) tensor->data;
  9634. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  9635. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  9636. } else {
  9637. llama_tensor_dequantize_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  9638. f32_data = (float *) f32_conv_buf.data();
  9639. }
  9640. LLAMA_LOG_INFO("quantizing to %s .. ", ggml_type_name(new_type));
  9641. fflush(stdout);
  9642. if (work.size() < nelements * 4) {
  9643. work.resize(nelements * 4); // upper bound on size
  9644. }
  9645. new_data = work.data();
  9646. std::array<int64_t, 1 << 4> hist_cur = {};
  9647. const int n_per_row = tensor->ne[0];
  9648. const int nrows = nelements / n_per_row;
  9649. static const int min_chunk_size = 32 * 512;
  9650. 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);
  9651. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  9652. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  9653. new_size = llama_tensor_quantize_internal(new_type, f32_data, new_data, chunk_size, nrows, n_per_row, hist_cur.data(), imatrix, workers, nthread_use);
  9654. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  9655. int64_t tot_count = 0;
  9656. for (size_t i = 0; i < hist_cur.size(); i++) {
  9657. hist_all[i] += hist_cur[i];
  9658. tot_count += hist_cur[i];
  9659. }
  9660. if (tot_count > 0) {
  9661. LLAMA_LOG_INFO(" | hist: ");
  9662. for (size_t i = 0; i < hist_cur.size(); i++) {
  9663. LLAMA_LOG_INFO("%5.3f ", hist_cur[i] / float(nelements));
  9664. }
  9665. }
  9666. LLAMA_LOG_INFO("\n");
  9667. }
  9668. total_size_org += ggml_nbytes(tensor);
  9669. total_size_new += new_size;
  9670. // update the gguf meta data as we go
  9671. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  9672. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  9673. // write tensor data + padding
  9674. fout.write((const char *) new_data, new_size);
  9675. zeros(fout, GGML_PAD(new_size, align) - new_size);
  9676. }
  9677. // go back to beginning of file and write the updated meta data
  9678. {
  9679. fout.seekp(0);
  9680. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  9681. gguf_get_meta_data(ctx_out, data.data());
  9682. fout.write((const char *) data.data(), data.size());
  9683. }
  9684. fout.close();
  9685. gguf_free(ctx_out);
  9686. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  9687. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  9688. // print histogram for all tensors
  9689. {
  9690. int64_t sum_all = 0;
  9691. for (size_t i = 0; i < hist_all.size(); i++) {
  9692. sum_all += hist_all[i];
  9693. }
  9694. if (sum_all > 0) {
  9695. LLAMA_LOG_INFO("%s: hist: ", __func__);
  9696. for (size_t i = 0; i < hist_all.size(); i++) {
  9697. LLAMA_LOG_INFO("%5.3f ", hist_all[i] / float(sum_all));
  9698. }
  9699. LLAMA_LOG_INFO("\n");
  9700. }
  9701. }
  9702. if (qs.n_fallback > 0) {
  9703. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) incompatible with k-quants and required fallback quantization\n",
  9704. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  9705. }
  9706. }
  9707. static int llama_apply_lora_from_file_internal(
  9708. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  9709. ) {
  9710. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  9711. const int64_t t_start_lora_us = ggml_time_us();
  9712. llama_file fin(path_lora, "rb");
  9713. // verify magic and version
  9714. {
  9715. uint32_t magic = fin.read_u32();
  9716. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  9717. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  9718. return 1;
  9719. }
  9720. uint32_t format_version = fin.read_u32();
  9721. if (format_version != 1) {
  9722. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  9723. return 1;
  9724. }
  9725. }
  9726. int32_t lora_r = fin.read_u32();
  9727. int32_t lora_alpha = fin.read_u32();
  9728. float scaling = scale * (float)lora_alpha / (float)lora_r;
  9729. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  9730. // load base model
  9731. std::unique_ptr<llama_model_loader> ml;
  9732. if (path_base_model) {
  9733. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  9734. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  9735. ml->init_mapping(/*prefetch*/ false); // no prefetching
  9736. }
  9737. struct tensor_meta {
  9738. std::string name;
  9739. ggml_type type;
  9740. int32_t ne[2];
  9741. size_t offset;
  9742. };
  9743. std::map<std::string, tensor_meta> tensor_meta_map;
  9744. // load all tensor meta
  9745. while (true) {
  9746. if (fin.tell() == fin.size) {
  9747. // eof
  9748. break;
  9749. }
  9750. int32_t n_dims;
  9751. int32_t name_len;
  9752. int32_t ftype;
  9753. fin.read_raw(&n_dims, sizeof(n_dims));
  9754. fin.read_raw(&name_len, sizeof(name_len));
  9755. fin.read_raw(&ftype, sizeof(ftype));
  9756. if (n_dims != 1 && n_dims != 2) {
  9757. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  9758. return 1;
  9759. }
  9760. int32_t ne[2] = { 1, 1 };
  9761. for (int i = 0; i < n_dims; ++i) {
  9762. fin.read_raw(&ne[i], sizeof(ne[i]));
  9763. }
  9764. std::string name;
  9765. {
  9766. GGML_ASSERT(name_len < GGML_MAX_NAME);
  9767. char buf[GGML_MAX_NAME];
  9768. fin.read_raw(buf, name_len);
  9769. name = std::string(buf, name_len);
  9770. }
  9771. // check for lora suffix
  9772. std::string lora_suffix;
  9773. if (name.length() > 6) {
  9774. lora_suffix = name.substr(name.length() - 6);
  9775. }
  9776. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  9777. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  9778. return 1;
  9779. }
  9780. // tensor type
  9781. ggml_type wtype;
  9782. switch (ftype) {
  9783. case 0: wtype = GGML_TYPE_F32; break;
  9784. case 1: wtype = GGML_TYPE_F16; break;
  9785. default:
  9786. {
  9787. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  9788. __func__, ftype);
  9789. return 1;
  9790. }
  9791. }
  9792. // data offset
  9793. size_t offset = fin.tell();
  9794. offset = (offset + 31) & -32;
  9795. // skip tensor data
  9796. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  9797. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  9798. }
  9799. bool warned = false;
  9800. int n_tensors = 0;
  9801. // apply
  9802. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  9803. if (backend_cpu == nullptr) {
  9804. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  9805. return 1;
  9806. }
  9807. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  9808. std::vector<no_init<uint8_t>> read_buf;
  9809. for (const auto & it : model.tensors_by_name) {
  9810. const std::string & base_name = it.first;
  9811. ggml_tensor * model_t = it.second;
  9812. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  9813. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  9814. continue;
  9815. }
  9816. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  9817. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  9818. ggml_init_params lora_init_params = {
  9819. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  9820. /* .mem_buffer */ nullptr,
  9821. /* .no_alloc */ true,
  9822. };
  9823. ggml_context * lora_ctx = ggml_init(lora_init_params);
  9824. if (lora_ctx == nullptr) {
  9825. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  9826. ggml_backend_free(backend_cpu);
  9827. return 1;
  9828. }
  9829. // create tensors
  9830. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  9831. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  9832. ggml_set_name(loraA, metaA.name.c_str());
  9833. ggml_set_name(loraB, metaB.name.c_str());
  9834. ggml_tensor * base_t;
  9835. if (ml) {
  9836. if (gguf_find_tensor(ml->ctx_gguf, base_name.c_str()) < 0) {
  9837. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  9838. return 1;
  9839. }
  9840. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  9841. } else {
  9842. base_t = ggml_dup_tensor(lora_ctx, model_t);
  9843. }
  9844. ggml_set_name(base_t, base_name.c_str());
  9845. // allocate in backend buffer
  9846. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  9847. if (lora_buf == nullptr) {
  9848. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  9849. return 1;
  9850. }
  9851. // load tensor data
  9852. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  9853. read_buf.resize(ggml_nbytes(tensor));
  9854. fin.seek(tensor_meta.offset, SEEK_SET);
  9855. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  9856. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  9857. };
  9858. load_tensor(metaA, loraA);
  9859. load_tensor(metaB, loraB);
  9860. // load base model tensor data
  9861. if (ml) {
  9862. ml->load_data_for(base_t);
  9863. } else {
  9864. ggml_backend_tensor_copy(model_t, base_t);
  9865. }
  9866. if (ggml_is_quantized(base_t->type) && !warned) {
  9867. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  9868. "use a f16 or f32 base model with --lora-base\n", __func__);
  9869. warned = true;
  9870. }
  9871. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  9872. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  9873. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  9874. ggml_free(lora_ctx);
  9875. ggml_backend_buffer_free(lora_buf);
  9876. ggml_backend_free(backend_cpu);
  9877. return 1;
  9878. }
  9879. auto build_lora_graph = [&]() {
  9880. // w = w + BA*s
  9881. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  9882. ggml_set_name(BA, "BA");
  9883. if (scaling != 1.0f) {
  9884. BA = ggml_scale(lora_ctx, BA, scaling);
  9885. ggml_set_name(BA, "BA_scaled");
  9886. }
  9887. ggml_tensor * r;
  9888. r = ggml_add_inplace(lora_ctx, base_t, BA);
  9889. ggml_set_name(r, "r_add");
  9890. if (base_t->type != model_t->type) {
  9891. // convert the result to the model type
  9892. r = ggml_cast(lora_ctx, r, model_t->type);
  9893. ggml_set_name(r, "r_cast");
  9894. }
  9895. return r;
  9896. };
  9897. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  9898. ggml_tensor * r = build_lora_graph();
  9899. ggml_build_forward_expand(gf, r);
  9900. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  9901. if (graph_buf == nullptr) {
  9902. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  9903. ggml_free(lora_ctx);
  9904. ggml_backend_buffer_free(lora_buf);
  9905. ggml_backend_free(backend_cpu);
  9906. return 1;
  9907. }
  9908. ggml_backend_graph_compute(backend_cpu, gf);
  9909. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  9910. #if 0
  9911. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  9912. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  9913. // sched compute
  9914. ggml_build_forward_expand(gf, build_graph());
  9915. ggml_backend_sched_init_measure(sched, gf);
  9916. // create the graph again, since the previous one was destroyed by the measure
  9917. ggml_graph_clear(gf);
  9918. ggml_build_forward_expand(gf, build_graph());
  9919. ggml_backend_sched_graph_compute(sched, gf);
  9920. ggml_backend_sched_free(sched);
  9921. #endif
  9922. ggml_backend_buffer_free(lora_buf);
  9923. ggml_backend_buffer_free(graph_buf);
  9924. ggml_free(lora_ctx);
  9925. n_tensors++;
  9926. if (n_tensors % 4 == 0) {
  9927. LLAMA_LOG_INFO(".");
  9928. }
  9929. }
  9930. ggml_backend_free(backend_cpu);
  9931. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  9932. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  9933. return 0;
  9934. }
  9935. //
  9936. // interface implementation
  9937. //
  9938. struct llama_model_params llama_model_default_params() {
  9939. struct llama_model_params result = {
  9940. /*.n_gpu_layers =*/ 0,
  9941. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  9942. /*.main_gpu =*/ 0,
  9943. /*.tensor_split =*/ nullptr,
  9944. /*.progress_callback =*/ nullptr,
  9945. /*.progress_callback_user_data =*/ nullptr,
  9946. /*.kv_overrides =*/ nullptr,
  9947. /*.vocab_only =*/ false,
  9948. /*.use_mmap =*/ true,
  9949. /*.use_mlock =*/ false,
  9950. };
  9951. #ifdef GGML_USE_METAL
  9952. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  9953. result.n_gpu_layers = 999;
  9954. #endif
  9955. return result;
  9956. }
  9957. struct llama_context_params llama_context_default_params() {
  9958. struct llama_context_params result = {
  9959. /*.seed =*/ LLAMA_DEFAULT_SEED,
  9960. /*.n_ctx =*/ 512,
  9961. /*.n_batch =*/ 512,
  9962. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  9963. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  9964. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  9965. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  9966. /*.rope_freq_base =*/ 0.0f,
  9967. /*.rope_freq_scale =*/ 0.0f,
  9968. /*.yarn_ext_factor =*/ -1.0f,
  9969. /*.yarn_attn_factor =*/ 1.0f,
  9970. /*.yarn_beta_fast =*/ 32.0f,
  9971. /*.yarn_beta_slow =*/ 1.0f,
  9972. /*.yarn_orig_ctx =*/ 0,
  9973. /*.defrag_thold =*/ -1.0f,
  9974. /*.cb_eval =*/ nullptr,
  9975. /*.cb_eval_user_data =*/ nullptr,
  9976. /*.type_k =*/ GGML_TYPE_F16,
  9977. /*.type_v =*/ GGML_TYPE_F16,
  9978. /*.logits_all =*/ false,
  9979. /*.embeddings =*/ false,
  9980. /*.offload_kqv =*/ true,
  9981. /*.abort_callback =*/ nullptr,
  9982. /*.abort_callback_data =*/ nullptr,
  9983. };
  9984. return result;
  9985. }
  9986. struct llama_model_quantize_params llama_model_quantize_default_params() {
  9987. struct llama_model_quantize_params result = {
  9988. /*.nthread =*/ 0,
  9989. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  9990. /*.allow_requantize =*/ false,
  9991. /*.quantize_output_tensor =*/ true,
  9992. /*.only_copy =*/ false,
  9993. /*.pure =*/ false,
  9994. /*.imatrix =*/ nullptr,
  9995. };
  9996. return result;
  9997. }
  9998. size_t llama_max_devices(void) {
  9999. #if defined(GGML_USE_METAL)
  10000. return 1;
  10001. #elif defined(GGML_USE_CUBLAS)
  10002. return GGML_CUDA_MAX_DEVICES;
  10003. #elif defined(GGML_USE_SYCL)
  10004. return GGML_SYCL_MAX_DEVICES;
  10005. #elif defined(GGML_USE_VULKAN)
  10006. return GGML_VK_MAX_DEVICES;
  10007. #else
  10008. return 1;
  10009. #endif
  10010. }
  10011. bool llama_supports_mmap(void) {
  10012. return llama_mmap::SUPPORTED;
  10013. }
  10014. bool llama_supports_mlock(void) {
  10015. return llama_mlock::SUPPORTED;
  10016. }
  10017. bool llama_supports_gpu_offload(void) {
  10018. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  10019. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE)
  10020. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  10021. return true;
  10022. #else
  10023. return false;
  10024. #endif
  10025. }
  10026. void llama_backend_init(void) {
  10027. ggml_time_init();
  10028. // needed to initialize f16 tables
  10029. {
  10030. struct ggml_init_params params = { 0, NULL, false };
  10031. struct ggml_context * ctx = ggml_init(params);
  10032. ggml_free(ctx);
  10033. }
  10034. #ifdef GGML_USE_MPI
  10035. ggml_mpi_backend_init();
  10036. #endif
  10037. }
  10038. void llama_numa_init(enum ggml_numa_strategy numa) {
  10039. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  10040. ggml_numa_init(numa);
  10041. }
  10042. }
  10043. void llama_backend_free(void) {
  10044. #ifdef GGML_USE_MPI
  10045. ggml_mpi_backend_free();
  10046. #endif
  10047. ggml_quantize_free();
  10048. }
  10049. int64_t llama_time_us(void) {
  10050. return ggml_time_us();
  10051. }
  10052. struct llama_model * llama_load_model_from_file(
  10053. const char * path_model,
  10054. struct llama_model_params params) {
  10055. ggml_time_init();
  10056. llama_model * model = new llama_model;
  10057. unsigned cur_percentage = 0;
  10058. if (params.progress_callback == NULL) {
  10059. params.progress_callback_user_data = &cur_percentage;
  10060. params.progress_callback = [](float progress, void * ctx) {
  10061. unsigned * cur_percentage_p = (unsigned *) ctx;
  10062. unsigned percentage = (unsigned) (100 * progress);
  10063. while (percentage > *cur_percentage_p) {
  10064. *cur_percentage_p = percentage;
  10065. LLAMA_LOG_INFO(".");
  10066. if (percentage >= 100) {
  10067. LLAMA_LOG_INFO("\n");
  10068. }
  10069. }
  10070. return true;
  10071. };
  10072. }
  10073. int status = llama_model_load(path_model, *model, params);
  10074. GGML_ASSERT(status <= 0);
  10075. if (status < 0) {
  10076. if (status == -1) {
  10077. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  10078. } else if (status == -2) {
  10079. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  10080. }
  10081. delete model;
  10082. return nullptr;
  10083. }
  10084. return model;
  10085. }
  10086. void llama_free_model(struct llama_model * model) {
  10087. delete model;
  10088. }
  10089. struct llama_context * llama_new_context_with_model(
  10090. struct llama_model * model,
  10091. struct llama_context_params params) {
  10092. if (!model) {
  10093. return nullptr;
  10094. }
  10095. llama_context * ctx = new llama_context(*model);
  10096. const auto & hparams = model->hparams;
  10097. auto & cparams = ctx->cparams;
  10098. cparams.n_batch = params.n_batch;
  10099. cparams.n_threads = params.n_threads;
  10100. cparams.n_threads_batch = params.n_threads_batch;
  10101. cparams.yarn_ext_factor = params.yarn_ext_factor;
  10102. cparams.yarn_attn_factor = params.yarn_attn_factor;
  10103. cparams.yarn_beta_fast = params.yarn_beta_fast;
  10104. cparams.yarn_beta_slow = params.yarn_beta_slow;
  10105. cparams.defrag_thold = params.defrag_thold;
  10106. cparams.embeddings = params.embeddings;
  10107. cparams.offload_kqv = params.offload_kqv;
  10108. cparams.pooling_type = params.pooling_type;
  10109. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  10110. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  10111. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  10112. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  10113. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  10114. hparams.n_ctx_train;
  10115. cparams.cb_eval = params.cb_eval;
  10116. cparams.cb_eval_user_data = params.cb_eval_user_data;
  10117. auto rope_scaling_type = params.rope_scaling_type;
  10118. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  10119. rope_scaling_type = hparams.rope_scaling_type_train;
  10120. }
  10121. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  10122. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  10123. }
  10124. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  10125. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  10126. }
  10127. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  10128. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  10129. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  10130. } else {
  10131. cparams.pooling_type = hparams.pooling_type;
  10132. }
  10133. }
  10134. if (params.seed == LLAMA_DEFAULT_SEED) {
  10135. params.seed = time(NULL);
  10136. }
  10137. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  10138. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  10139. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  10140. ctx->abort_callback = params.abort_callback;
  10141. ctx->abort_callback_data = params.abort_callback_data;
  10142. ctx->rng = std::mt19937(params.seed);
  10143. ctx->logits_all = params.logits_all;
  10144. const ggml_type type_k = params.type_k;
  10145. const ggml_type type_v = params.type_v;
  10146. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  10147. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  10148. if (!hparams.vocab_only) {
  10149. // initialize backends
  10150. #ifdef GGML_USE_METAL
  10151. if (model->n_gpu_layers > 0) {
  10152. ctx->backend_metal = ggml_backend_metal_init();
  10153. if (ctx->backend_metal == nullptr) {
  10154. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  10155. llama_free(ctx);
  10156. return nullptr;
  10157. }
  10158. ctx->backends.push_back(ctx->backend_metal);
  10159. }
  10160. #elif defined(GGML_USE_CUBLAS)
  10161. if (model->n_gpu_layers > 0) {
  10162. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  10163. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  10164. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  10165. if (backend == nullptr) {
  10166. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  10167. llama_free(ctx);
  10168. return nullptr;
  10169. }
  10170. ctx->backends.push_back(backend);
  10171. } else {
  10172. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  10173. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  10174. ggml_backend_t backend = ggml_backend_cuda_init(device);
  10175. if (backend == nullptr) {
  10176. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  10177. llama_free(ctx);
  10178. return nullptr;
  10179. }
  10180. ctx->backends.push_back(backend);
  10181. }
  10182. }
  10183. }
  10184. #elif defined(GGML_USE_VULKAN)
  10185. if (model->n_gpu_layers > 0) {
  10186. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  10187. ggml_backend_t backend = ggml_backend_vk_init(device);
  10188. if (backend == nullptr) {
  10189. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  10190. llama_free(ctx);
  10191. return nullptr;
  10192. }
  10193. ctx->backends.push_back(backend);
  10194. }
  10195. }
  10196. #elif defined(GGML_USE_SYCL)
  10197. if (model->n_gpu_layers > 0) {
  10198. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  10199. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  10200. int main_gpu_index = ggml_backend_sycl_get_device_index(model->main_gpu);
  10201. ggml_backend_t backend = ggml_backend_sycl_init(main_gpu_index);
  10202. if (backend == nullptr) {
  10203. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d)backend\n", __func__, model->main_gpu, main_gpu_index);
  10204. llama_free(ctx);
  10205. return nullptr;
  10206. }
  10207. ctx->backends.push_back(backend);
  10208. } else {
  10209. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  10210. int id_list[GGML_SYCL_MAX_DEVICES];
  10211. ggml_sycl_get_gpu_list(id_list, GGML_SYCL_MAX_DEVICES);
  10212. for (int i = 0; i < ggml_backend_sycl_get_device_count(); ++i) {
  10213. int device_id = id_list[i];
  10214. ggml_backend_t backend = ggml_backend_sycl_init(i);
  10215. if (backend == nullptr) {
  10216. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d)backend\n", __func__, device_id, i);
  10217. llama_free(ctx);
  10218. return nullptr;
  10219. }
  10220. ctx->backends.push_back(backend);
  10221. }
  10222. }
  10223. }
  10224. #elif defined(GGML_USE_KOMPUTE)
  10225. if (model->n_gpu_layers > 0) {
  10226. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  10227. if (backend == nullptr) {
  10228. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  10229. llama_free(ctx);
  10230. return nullptr;
  10231. }
  10232. ctx->backends.push_back(backend);
  10233. }
  10234. #endif
  10235. ctx->backend_cpu = ggml_backend_cpu_init();
  10236. if (ctx->backend_cpu == nullptr) {
  10237. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  10238. llama_free(ctx);
  10239. return nullptr;
  10240. }
  10241. ctx->backends.push_back(ctx->backend_cpu);
  10242. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v, cparams.n_ctx, cparams.offload_kqv)) {
  10243. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  10244. llama_free(ctx);
  10245. return nullptr;
  10246. }
  10247. {
  10248. size_t memory_size_k = 0;
  10249. size_t memory_size_v = 0;
  10250. for (auto & k : ctx->kv_self.k_l) {
  10251. memory_size_k += ggml_nbytes(k);
  10252. }
  10253. for (auto & v : ctx->kv_self.v_l) {
  10254. memory_size_v += ggml_nbytes(v);
  10255. }
  10256. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  10257. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  10258. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  10259. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  10260. }
  10261. // resized during inference, reserve maximum
  10262. ctx->logits.reserve(hparams.n_vocab*cparams.n_batch);
  10263. if (params.embeddings) {
  10264. ctx->embd.reserve(hparams.n_embd*cparams.n_batch);
  10265. }
  10266. // graph inputs
  10267. {
  10268. ggml_init_params init_params = {
  10269. /* .mem_size */ ggml_tensor_overhead()*8,
  10270. /* .mem_buffer */ nullptr,
  10271. /* .no_alloc */ true,
  10272. };
  10273. ctx->ctx_input = ggml_init(init_params);
  10274. ctx->inp_tokens = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  10275. ctx->inp_embd = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, hparams.n_embd, cparams.n_batch);
  10276. ctx->inp_pos = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  10277. ctx->inp_KQ_mask = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_ctx, cparams.n_batch);
  10278. ctx->inp_KQ_pos = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_ctx);
  10279. ctx->inp_K_shift = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_ctx);
  10280. ctx->inp_mean = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_batch, cparams.n_batch);
  10281. ctx->inp_cls = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  10282. ggml_set_name(ctx->inp_tokens, "inp_tokens");
  10283. ggml_set_name(ctx->inp_embd, "inp_embd");
  10284. ggml_set_name(ctx->inp_pos, "inp_pos");
  10285. ggml_set_name(ctx->inp_KQ_mask, "inp_KQ_mask");
  10286. ggml_set_name(ctx->inp_KQ_pos, "inp_KQ_pos");
  10287. ggml_set_name(ctx->inp_K_shift, "inp_K_shift");
  10288. ggml_set_name(ctx->inp_mean, "inp_mean");
  10289. ggml_set_name(ctx->inp_cls, "inp_cls");
  10290. ctx->buf_input = ggml_backend_alloc_ctx_tensors_from_buft(ctx->ctx_input, llama_default_buffer_type_cpu(true));
  10291. LLAMA_LOG_INFO("%s: %10s input buffer size = %8.2f MiB\n", __func__,
  10292. ggml_backend_buffer_name(ctx->buf_input),
  10293. ggml_backend_buffer_get_size(ctx->buf_input) / 1024.0 / 1024.0);
  10294. }
  10295. // scheduler and compute buffers
  10296. {
  10297. // buffer types used for the compute buffer of each backend
  10298. std::vector<ggml_backend_buffer_type_t> backend_buft;
  10299. for (auto * backend : ctx->backends) {
  10300. if (ggml_backend_is_cpu(backend)) {
  10301. // use host buffers for the CPU backend compute buffer
  10302. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  10303. } else {
  10304. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  10305. }
  10306. }
  10307. // buffer used to store the computation graph and the tensor meta data
  10308. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead_custom(LLAMA_MAX_NODES, false));
  10309. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES);
  10310. // build worst-case graph
  10311. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_batch);
  10312. int n_past = cparams.n_ctx - n_tokens;
  10313. 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
  10314. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  10315. // initialize scheduler with the worst-case graph
  10316. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  10317. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  10318. llama_free(ctx);
  10319. return nullptr;
  10320. }
  10321. for (size_t i = 0; i < ctx->backends.size(); i++) {
  10322. ggml_backend_t backend = ctx->backends[i];
  10323. ggml_backend_buffer_type_t buft = backend_buft[i];
  10324. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  10325. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  10326. ggml_backend_buft_name(buft),
  10327. size / 1024.0 / 1024.0);
  10328. }
  10329. // note: the number of splits during measure is higher than during inference due to the kv shift
  10330. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  10331. LLAMA_LOG_INFO("%s: graph splits (measure): %d\n", __func__, n_splits);
  10332. }
  10333. }
  10334. #ifdef GGML_USE_MPI
  10335. ctx->ctx_mpi = ggml_mpi_init();
  10336. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  10337. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  10338. // TODO: needs fix after #3228
  10339. GGML_ASSERT(false && "not implemented");
  10340. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  10341. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  10342. llama_backend_free();
  10343. exit(1);
  10344. }
  10345. #endif
  10346. return ctx;
  10347. }
  10348. void llama_free(struct llama_context * ctx) {
  10349. delete ctx;
  10350. }
  10351. const llama_model * llama_get_model(const struct llama_context * ctx) {
  10352. return &ctx->model;
  10353. }
  10354. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  10355. return ctx->cparams.n_ctx;
  10356. }
  10357. uint32_t llama_n_batch(const struct llama_context * ctx) {
  10358. return ctx->cparams.n_batch;
  10359. }
  10360. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  10361. return model->vocab.type;
  10362. }
  10363. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  10364. switch (model->arch) {
  10365. // these models do not use RoPE
  10366. case LLM_ARCH_GPT2:
  10367. case LLM_ARCH_GPTJ:
  10368. case LLM_ARCH_GPTNEOX:
  10369. case LLM_ARCH_MPT:
  10370. case LLM_ARCH_REFACT:
  10371. case LLM_ARCH_BLOOM:
  10372. return LLAMA_ROPE_TYPE_NONE;
  10373. // use what we call a normal RoPE, operating on pairs of consecutive head values
  10374. case LLM_ARCH_LLAMA:
  10375. case LLM_ARCH_BAICHUAN:
  10376. case LLM_ARCH_STARCODER:
  10377. case LLM_ARCH_PLAMO:
  10378. case LLM_ARCH_CODESHELL:
  10379. case LLM_ARCH_ORION:
  10380. case LLM_ARCH_INTERNLM2:
  10381. case LLM_ARCH_MINICPM:
  10382. return LLAMA_ROPE_TYPE_NORM;
  10383. // the pairs of head values are offset by n_rot/2
  10384. case LLM_ARCH_FALCON:
  10385. case LLM_ARCH_PERSIMMON:
  10386. case LLM_ARCH_BERT:
  10387. case LLM_ARCH_NOMIC_BERT:
  10388. case LLM_ARCH_STABLELM:
  10389. case LLM_ARCH_QWEN:
  10390. case LLM_ARCH_QWEN2:
  10391. case LLM_ARCH_PHI2:
  10392. case LLM_ARCH_GEMMA:
  10393. case LLM_ARCH_STARCODER2:
  10394. return LLAMA_ROPE_TYPE_NEOX;
  10395. // all model arches should be listed explicitly here
  10396. case LLM_ARCH_UNKNOWN:
  10397. GGML_ASSERT(false && "unknown architecture");
  10398. break;
  10399. }
  10400. return LLAMA_ROPE_TYPE_NONE;
  10401. }
  10402. int32_t llama_n_vocab(const struct llama_model * model) {
  10403. return model->vocab.id_to_token.size();
  10404. }
  10405. int32_t llama_n_ctx_train(const struct llama_model * model) {
  10406. return model->hparams.n_ctx_train;
  10407. }
  10408. int32_t llama_n_embd(const struct llama_model * model) {
  10409. return model->hparams.n_embd;
  10410. }
  10411. float llama_rope_freq_scale_train(const struct llama_model * model) {
  10412. return model->hparams.rope_freq_scale_train;
  10413. }
  10414. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  10415. const auto & it = model->gguf_kv.find(key);
  10416. if (it == model->gguf_kv.end()) {
  10417. if (buf_size > 0) {
  10418. buf[0] = '\0';
  10419. }
  10420. return -1;
  10421. }
  10422. return snprintf(buf, buf_size, "%s", it->second.c_str());
  10423. }
  10424. int32_t llama_model_meta_count(const struct llama_model * model) {
  10425. return (int)model->gguf_kv.size();
  10426. }
  10427. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  10428. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  10429. if (buf_size > 0) {
  10430. buf[0] = '\0';
  10431. }
  10432. return -1;
  10433. }
  10434. auto it = model->gguf_kv.begin();
  10435. std::advance(it, i);
  10436. return snprintf(buf, buf_size, "%s", it->first.c_str());
  10437. }
  10438. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  10439. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  10440. if (buf_size > 0) {
  10441. buf[0] = '\0';
  10442. }
  10443. return -1;
  10444. }
  10445. auto it = model->gguf_kv.begin();
  10446. std::advance(it, i);
  10447. return snprintf(buf, buf_size, "%s", it->second.c_str());
  10448. }
  10449. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  10450. return snprintf(buf, buf_size, "%s %s %s",
  10451. llama_model_arch_name(model->arch),
  10452. llama_model_type_name(model->type),
  10453. llama_model_ftype_name(model->ftype).c_str());
  10454. }
  10455. uint64_t llama_model_size(const struct llama_model * model) {
  10456. uint64_t size = 0;
  10457. for (const auto & it : model->tensors_by_name) {
  10458. size += ggml_nbytes(it.second);
  10459. }
  10460. return size;
  10461. }
  10462. uint64_t llama_model_n_params(const struct llama_model * model) {
  10463. uint64_t nparams = 0;
  10464. for (const auto & it : model->tensors_by_name) {
  10465. nparams += ggml_nelements(it.second);
  10466. }
  10467. return nparams;
  10468. }
  10469. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  10470. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  10471. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  10472. return it.first == name;
  10473. });
  10474. if (it == model->tensors_by_name.end()) {
  10475. return nullptr;
  10476. }
  10477. return it->second;
  10478. }
  10479. uint32_t llama_model_quantize(
  10480. const char * fname_inp,
  10481. const char * fname_out,
  10482. const llama_model_quantize_params * params) {
  10483. try {
  10484. llama_model_quantize_internal(fname_inp, fname_out, params);
  10485. return 0;
  10486. } catch (const std::exception & err) {
  10487. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  10488. return 1;
  10489. }
  10490. }
  10491. 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) {
  10492. try {
  10493. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  10494. } catch (const std::exception & err) {
  10495. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  10496. return 1;
  10497. }
  10498. }
  10499. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_max_seq) {
  10500. struct llama_kv_cache_view result = {
  10501. /*.n_cells = */ 0,
  10502. /*.n_max_seq = */ n_max_seq,
  10503. /*.token_count = */ 0,
  10504. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  10505. /*.max_contiguous = */ 0,
  10506. /*.max_contiguous_idx = */ -1,
  10507. /*.cells = */ nullptr,
  10508. /*.cells_sequences = */ nullptr,
  10509. };
  10510. return result;
  10511. }
  10512. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  10513. if (view->cells != nullptr) {
  10514. free(view->cells);
  10515. view->cells = nullptr;
  10516. }
  10517. if (view->cells_sequences != nullptr) {
  10518. free(view->cells_sequences);
  10519. view->cells_sequences = nullptr;
  10520. }
  10521. }
  10522. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  10523. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  10524. view->n_cells = int32_t(ctx->kv_self.size);
  10525. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  10526. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  10527. view->cells = (struct llama_kv_cache_view_cell *)p;
  10528. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_max_seq * view->n_cells);
  10529. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  10530. view->cells_sequences = (llama_seq_id *)p;
  10531. }
  10532. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  10533. llama_kv_cache_view_cell * c_curr = view->cells;
  10534. llama_seq_id * cs_curr = view->cells_sequences;
  10535. int32_t used_cells = 0;
  10536. int32_t token_count = 0;
  10537. int32_t curr_contig_idx = -1;
  10538. uint32_t max_contig = 0;
  10539. int32_t max_contig_idx = -1;
  10540. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_max_seq) {
  10541. const size_t curr_size = kv_cells[i].seq_id.size();
  10542. token_count += curr_size;
  10543. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  10544. if (curr_size > 0) {
  10545. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  10546. max_contig = i - curr_contig_idx;
  10547. max_contig_idx = curr_contig_idx;
  10548. }
  10549. curr_contig_idx = -1;
  10550. } else if (curr_contig_idx < 0) {
  10551. curr_contig_idx = i;
  10552. }
  10553. int seq_idx = 0;
  10554. for (const llama_seq_id it : kv_cells[i].seq_id) {
  10555. if (seq_idx >= view->n_max_seq) {
  10556. break;
  10557. }
  10558. cs_curr[seq_idx] = it;
  10559. seq_idx++;
  10560. }
  10561. if (seq_idx != 0) {
  10562. used_cells++;
  10563. }
  10564. for (; seq_idx < view->n_max_seq; seq_idx++) {
  10565. cs_curr[seq_idx] = -1;
  10566. }
  10567. }
  10568. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  10569. max_contig_idx = curr_contig_idx;
  10570. max_contig = kv_cells.size() - curr_contig_idx;
  10571. }
  10572. view->max_contiguous = max_contig;
  10573. view->max_contiguous_idx = max_contig_idx;
  10574. view->token_count = token_count;
  10575. view->used_cells = used_cells;
  10576. if (uint32_t(used_cells) != ctx->kv_self.used) {
  10577. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  10578. __func__, ctx->kv_self.used, used_cells);
  10579. }
  10580. }
  10581. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  10582. int result = 0;
  10583. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  10584. result += ctx->kv_self.cells[i].seq_id.size();
  10585. }
  10586. return result;
  10587. }
  10588. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  10589. return ctx->kv_self.used;
  10590. }
  10591. void llama_kv_cache_clear(struct llama_context * ctx) {
  10592. llama_kv_cache_clear(ctx->kv_self);
  10593. }
  10594. void llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  10595. llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  10596. }
  10597. 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) {
  10598. if (seq_id_src == seq_id_dst) {
  10599. return;
  10600. }
  10601. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  10602. }
  10603. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  10604. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  10605. }
  10606. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  10607. if (delta == 0) {
  10608. return;
  10609. }
  10610. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  10611. }
  10612. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  10613. if (d == 1) {
  10614. return;
  10615. }
  10616. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  10617. }
  10618. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  10619. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  10620. }
  10621. void llama_kv_cache_defrag(struct llama_context * ctx) {
  10622. llama_kv_cache_defrag(ctx->kv_self);
  10623. }
  10624. void llama_kv_cache_update(struct llama_context * ctx) {
  10625. llama_kv_cache_update_internal(*ctx);
  10626. }
  10627. // Returns the *maximum* size of the state
  10628. size_t llama_get_state_size(const struct llama_context * ctx) {
  10629. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  10630. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  10631. const size_t s_rng_size = sizeof(size_t);
  10632. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  10633. const size_t s_logits_size = sizeof(size_t);
  10634. // assume worst case for logits although only currently set ones are serialized
  10635. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  10636. const size_t s_embedding_size = sizeof(size_t);
  10637. const size_t s_embedding = ctx->embd.capacity() * sizeof(float);
  10638. const size_t s_kv_buf_size = sizeof(size_t);
  10639. const size_t s_kv_head = sizeof(uint32_t);
  10640. const size_t s_kv_size = sizeof(uint32_t);
  10641. const size_t s_kv_used = sizeof(uint32_t);
  10642. const size_t s_kv = ctx->kv_self.total_size();
  10643. // TODO: assume the max is more than 1 seq_id per KV cell
  10644. const size_t s_kv_cell = sizeof(llama_pos) + sizeof(size_t) + sizeof(llama_seq_id);
  10645. const size_t s_kv_cells = ctx->kv_self.size * s_kv_cell;
  10646. const size_t s_total = (
  10647. + s_rng_size
  10648. + s_rng
  10649. + s_logits_size
  10650. + s_logits
  10651. + s_embedding_size
  10652. + s_embedding
  10653. + s_kv_buf_size
  10654. + s_kv_head
  10655. + s_kv_size
  10656. + s_kv_used
  10657. + s_kv
  10658. + s_kv_cells
  10659. );
  10660. return s_total;
  10661. }
  10662. // llama_context_data
  10663. struct llama_data_context {
  10664. virtual void write(const void * src, size_t size) = 0;
  10665. virtual size_t get_size_written() = 0;
  10666. virtual ~llama_data_context() = default;
  10667. };
  10668. struct llama_data_buffer_context : llama_data_context {
  10669. uint8_t * ptr;
  10670. size_t size_written = 0;
  10671. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  10672. void write(const void * src, size_t size) override {
  10673. memcpy(ptr, src, size);
  10674. ptr += size;
  10675. size_written += size;
  10676. }
  10677. size_t get_size_written() override {
  10678. return size_written;
  10679. }
  10680. };
  10681. struct llama_data_file_context : llama_data_context {
  10682. llama_file * file;
  10683. size_t size_written = 0;
  10684. llama_data_file_context(llama_file * f) : file(f) {}
  10685. void write(const void * src, size_t size) override {
  10686. file->write_raw(src, size);
  10687. size_written += size;
  10688. }
  10689. size_t get_size_written() override {
  10690. return size_written;
  10691. }
  10692. };
  10693. /** copy state data into either a buffer or file depending on the passed in context
  10694. *
  10695. * file context:
  10696. * llama_file file("/path", "wb");
  10697. * llama_data_file_context data_ctx(&file);
  10698. * llama_copy_state_data(ctx, &data_ctx);
  10699. *
  10700. * buffer context:
  10701. * std::vector<uint8_t> buf(max_size, 0);
  10702. * llama_data_buffer_context data_ctx(&buf.data());
  10703. * llama_copy_state_data(ctx, &data_ctx);
  10704. *
  10705. */
  10706. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  10707. // copy rng
  10708. {
  10709. std::ostringstream rng_ss;
  10710. rng_ss << ctx->rng;
  10711. const std::string & rng_str = rng_ss.str();
  10712. const size_t rng_size = rng_str.size();
  10713. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  10714. data_ctx->write(&rng_size, sizeof(rng_size));
  10715. data_ctx->write(rng_str.data(), rng_size);
  10716. }
  10717. // copy logits
  10718. {
  10719. const size_t logits_size = ctx->logits.size();
  10720. data_ctx->write(&logits_size, sizeof(logits_size));
  10721. if (logits_size) {
  10722. data_ctx->write(ctx->logits.data(), logits_size * sizeof(float));
  10723. }
  10724. }
  10725. // copy embeddings
  10726. {
  10727. const size_t embeddings_size = ctx->embd.size();
  10728. data_ctx->write(&embeddings_size, sizeof(embeddings_size));
  10729. if (embeddings_size) {
  10730. data_ctx->write(ctx->embd.data(), embeddings_size * sizeof(float));
  10731. }
  10732. }
  10733. // copy kv cache
  10734. {
  10735. const auto & kv_self = ctx->kv_self;
  10736. const auto & hparams = ctx->model.hparams;
  10737. const uint32_t n_layer = hparams.n_layer;
  10738. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  10739. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  10740. const size_t kv_buf_size = kv_self.total_size();
  10741. const uint32_t kv_head = llama_kv_cache_cell_max(kv_self);
  10742. const uint32_t kv_size = kv_self.size;
  10743. const uint32_t kv_used = kv_self.used;
  10744. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  10745. data_ctx->write(&kv_head, sizeof(kv_head));
  10746. data_ctx->write(&kv_size, sizeof(kv_size));
  10747. data_ctx->write(&kv_used, sizeof(kv_used));
  10748. if (kv_buf_size) {
  10749. std::vector<uint8_t> tmp_buf;
  10750. for (int il = 0; il < (int) n_layer; ++il) {
  10751. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  10752. tmp_buf.resize(k_size);
  10753. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  10754. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  10755. // v is not contiguous, copy row by row
  10756. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  10757. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_size);
  10758. tmp_buf.resize(v_row_size);
  10759. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  10760. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*v_row_stride, tmp_buf.size());
  10761. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  10762. }
  10763. }
  10764. }
  10765. for (uint32_t i = 0; i < kv_head; ++i) {
  10766. const auto & cell = kv_self.cells[i];
  10767. const llama_pos pos = cell.pos;
  10768. const size_t seq_id_size = cell.seq_id.size();
  10769. data_ctx->write(&pos, sizeof(pos));
  10770. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  10771. for (auto seq_id : cell.seq_id) {
  10772. data_ctx->write(&seq_id, sizeof(seq_id));
  10773. }
  10774. }
  10775. }
  10776. }
  10777. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  10778. llama_data_buffer_context data_ctx(dst);
  10779. llama_copy_state_data_internal(ctx, &data_ctx);
  10780. return data_ctx.get_size_written();
  10781. }
  10782. // Sets the state reading from the specified source address
  10783. size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
  10784. const uint8_t * inp = src;
  10785. // set rng
  10786. {
  10787. size_t rng_size;
  10788. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  10789. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  10790. std::string rng_str((const char *)inp, rng_size); inp += rng_size;
  10791. std::istringstream rng_ss(rng_str);
  10792. rng_ss >> ctx->rng;
  10793. GGML_ASSERT(!rng_ss.fail());
  10794. }
  10795. // set logits
  10796. {
  10797. size_t logits_size;
  10798. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  10799. GGML_ASSERT(ctx->logits.capacity() >= logits_size);
  10800. if (logits_size) {
  10801. ctx->logits.resize(logits_size);
  10802. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  10803. inp += logits_size * sizeof(float);
  10804. }
  10805. }
  10806. // set embeddings
  10807. {
  10808. size_t embeddings_size;
  10809. memcpy(&embeddings_size, inp, sizeof(embeddings_size)); inp += sizeof(embeddings_size);
  10810. GGML_ASSERT(ctx->embd.capacity() == embeddings_size);
  10811. if (embeddings_size) {
  10812. ctx->embd.resize(embeddings_size);
  10813. memcpy(ctx->embd.data(), inp, embeddings_size * sizeof(float));
  10814. inp += embeddings_size * sizeof(float);
  10815. }
  10816. }
  10817. // set kv cache
  10818. {
  10819. const auto & kv_self = ctx->kv_self;
  10820. const auto & hparams = ctx->model.hparams;
  10821. const uint32_t n_layer = hparams.n_layer;
  10822. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  10823. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  10824. size_t kv_buf_size;
  10825. uint32_t kv_head;
  10826. uint32_t kv_size;
  10827. uint32_t kv_used;
  10828. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  10829. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  10830. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  10831. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  10832. if (kv_buf_size) {
  10833. GGML_ASSERT(kv_self.total_size() == kv_buf_size);
  10834. for (int il = 0; il < (int) n_layer; ++il) {
  10835. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  10836. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  10837. inp += k_size;
  10838. // v is not contiguous, copy row by row
  10839. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  10840. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_size);
  10841. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  10842. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*v_row_stride, v_row_size);
  10843. inp += v_row_size;
  10844. }
  10845. }
  10846. }
  10847. GGML_ASSERT(kv_self.size == kv_size);
  10848. ctx->kv_self.head = kv_head;
  10849. ctx->kv_self.size = kv_size;
  10850. ctx->kv_self.used = kv_used;
  10851. ctx->kv_self.cells.resize(kv_size);
  10852. for (uint32_t i = 0; i < kv_head; ++i) {
  10853. llama_pos pos;
  10854. size_t seq_id_size;
  10855. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  10856. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  10857. ctx->kv_self.cells[i].pos = pos;
  10858. llama_seq_id seq_id;
  10859. for (size_t j = 0; j < seq_id_size; ++j) {
  10860. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  10861. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  10862. }
  10863. }
  10864. for (uint32_t i = kv_head; i < kv_size; ++i) {
  10865. ctx->kv_self.cells[i].pos = -1;
  10866. ctx->kv_self.cells[i].seq_id.clear();
  10867. }
  10868. }
  10869. const size_t nread = inp - src;
  10870. const size_t max_size = llama_get_state_size(ctx);
  10871. GGML_ASSERT(nread <= max_size);
  10872. return nread;
  10873. }
  10874. 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) {
  10875. llama_file file(path_session, "rb");
  10876. // sanity checks
  10877. {
  10878. const uint32_t magic = file.read_u32();
  10879. const uint32_t version = file.read_u32();
  10880. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  10881. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  10882. return false;
  10883. }
  10884. llama_hparams session_hparams;
  10885. file.read_raw(&session_hparams, sizeof(llama_hparams));
  10886. if (session_hparams != ctx->model.hparams) {
  10887. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  10888. return false;
  10889. }
  10890. }
  10891. // load the prompt
  10892. {
  10893. const uint32_t n_token_count = file.read_u32();
  10894. if (n_token_count > n_token_capacity) {
  10895. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  10896. return false;
  10897. }
  10898. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  10899. *n_token_count_out = n_token_count;
  10900. }
  10901. // restore the context state
  10902. {
  10903. const size_t n_state_size_cur = file.size - file.tell();
  10904. const size_t n_state_size_max = llama_get_state_size(ctx);
  10905. if (n_state_size_cur > n_state_size_max) {
  10906. 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);
  10907. return false;
  10908. }
  10909. std::vector<uint8_t> state_data(n_state_size_max);
  10910. file.read_raw(state_data.data(), n_state_size_cur);
  10911. llama_set_state_data(ctx, state_data.data());
  10912. }
  10913. return true;
  10914. }
  10915. 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) {
  10916. try {
  10917. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  10918. } catch (const std::exception & err) {
  10919. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  10920. return false;
  10921. }
  10922. }
  10923. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  10924. llama_file file(path_session, "wb");
  10925. file.write_u32(LLAMA_SESSION_MAGIC);
  10926. file.write_u32(LLAMA_SESSION_VERSION);
  10927. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  10928. // save the prompt
  10929. file.write_u32((uint32_t) n_token_count);
  10930. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  10931. // save the context state using stream saving
  10932. llama_data_file_context data_ctx(&file);
  10933. llama_copy_state_data_internal(ctx, &data_ctx);
  10934. return true;
  10935. }
  10936. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  10937. ctx->cparams.n_threads = n_threads;
  10938. ctx->cparams.n_threads_batch = n_threads_batch;
  10939. }
  10940. void llama_set_abort_callback(struct llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
  10941. ctx->abort_callback = abort_callback;
  10942. ctx->abort_callback_data = abort_callback_data;
  10943. }
  10944. struct llama_batch llama_batch_get_one(
  10945. llama_token * tokens,
  10946. int32_t n_tokens,
  10947. llama_pos pos_0,
  10948. llama_seq_id seq_id) {
  10949. return {
  10950. /*n_tokens =*/ n_tokens,
  10951. /*tokens =*/ tokens,
  10952. /*embd =*/ nullptr,
  10953. /*pos =*/ nullptr,
  10954. /*n_seq_id =*/ nullptr,
  10955. /*seq_id =*/ nullptr,
  10956. /*logits =*/ nullptr,
  10957. /*all_pos_0 =*/ pos_0,
  10958. /*all_pos_1 =*/ 1,
  10959. /*all_seq_id =*/ seq_id,
  10960. };
  10961. }
  10962. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  10963. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  10964. if (embd) {
  10965. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  10966. } else {
  10967. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  10968. }
  10969. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  10970. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  10971. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  10972. for (int i = 0; i < n_tokens_alloc; ++i) {
  10973. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  10974. }
  10975. batch.seq_id[n_tokens_alloc] = nullptr;
  10976. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  10977. return batch;
  10978. }
  10979. void llama_batch_free(struct llama_batch batch) {
  10980. if (batch.token) free(batch.token);
  10981. if (batch.embd) free(batch.embd);
  10982. if (batch.pos) free(batch.pos);
  10983. if (batch.n_seq_id) free(batch.n_seq_id);
  10984. if (batch.seq_id) {
  10985. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  10986. free(batch.seq_id[i]);
  10987. }
  10988. free(batch.seq_id);
  10989. }
  10990. if (batch.logits) free(batch.logits);
  10991. }
  10992. int32_t llama_decode(
  10993. struct llama_context * ctx,
  10994. struct llama_batch batch) {
  10995. const int ret = llama_decode_internal(*ctx, batch);
  10996. if (ret < 0) {
  10997. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  10998. }
  10999. return ret;
  11000. }
  11001. float * llama_get_logits(struct llama_context * ctx) {
  11002. return ctx->logits.data();
  11003. }
  11004. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  11005. assert(ctx->logits_valid.at(i));
  11006. return ctx->logits.data() + i*ctx->model.hparams.n_vocab;
  11007. }
  11008. float * llama_get_embeddings(struct llama_context * ctx) {
  11009. return ctx->embd.data();
  11010. }
  11011. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  11012. return ctx->embd.data() + i*ctx->model.hparams.n_embd;
  11013. }
  11014. float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id) {
  11015. auto it = ctx->embd_seq.find(seq_id);
  11016. if (it == ctx->embd_seq.end()) {
  11017. return nullptr;
  11018. }
  11019. return it->second.data();
  11020. }
  11021. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  11022. return model->vocab.id_to_token[token].text.c_str();
  11023. }
  11024. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  11025. return model->vocab.id_to_token[token].score;
  11026. }
  11027. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  11028. return model->vocab.id_to_token[token].type;
  11029. }
  11030. llama_token llama_token_bos(const struct llama_model * model) {
  11031. return model->vocab.special_bos_id;
  11032. }
  11033. llama_token llama_token_eos(const struct llama_model * model) {
  11034. return model->vocab.special_eos_id;
  11035. }
  11036. llama_token llama_token_nl(const struct llama_model * model) {
  11037. return model->vocab.linefeed_id;
  11038. }
  11039. int32_t llama_add_bos_token(const struct llama_model * model) {
  11040. return model->vocab.special_add_bos;
  11041. }
  11042. int32_t llama_add_eos_token(const struct llama_model * model) {
  11043. return model->vocab.special_add_eos;
  11044. }
  11045. llama_token llama_token_prefix(const struct llama_model * model) {
  11046. return model->vocab.special_prefix_id;
  11047. }
  11048. llama_token llama_token_middle(const struct llama_model * model) {
  11049. return model->vocab.special_middle_id;
  11050. }
  11051. llama_token llama_token_suffix(const struct llama_model * model) {
  11052. return model->vocab.special_suffix_id;
  11053. }
  11054. llama_token llama_token_eot(const struct llama_model * model) {
  11055. return model->vocab.special_eot_id;
  11056. }
  11057. int32_t llama_tokenize(
  11058. const struct llama_model * model,
  11059. const char * text,
  11060. int32_t text_len,
  11061. llama_token * tokens,
  11062. int32_t n_max_tokens,
  11063. bool add_bos,
  11064. bool special) {
  11065. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  11066. if (n_max_tokens < (int) res.size()) {
  11067. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  11068. return -((int) res.size());
  11069. }
  11070. for (size_t i = 0; i < res.size(); i++) {
  11071. tokens[i] = res[i];
  11072. }
  11073. return res.size();
  11074. }
  11075. static std::string llama_decode_text(const std::string & text) {
  11076. std::string decoded_text;
  11077. auto unicode_sequences = codepoints_from_utf8(text);
  11078. for (auto& unicode_sequence : unicode_sequences) {
  11079. decoded_text += unicode_to_bytes_bpe(codepoint_to_utf8(unicode_sequence));
  11080. }
  11081. return decoded_text;
  11082. }
  11083. // does not write null-terminator to buf
  11084. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  11085. if (0 <= token && token < llama_n_vocab(model)) {
  11086. switch (llama_vocab_get_type(model->vocab)) {
  11087. case LLAMA_VOCAB_TYPE_WPM:
  11088. case LLAMA_VOCAB_TYPE_SPM: {
  11089. // NOTE: we accept all unsupported token types,
  11090. // suppressing them like CONTROL tokens.
  11091. if (llama_is_normal_token(model->vocab, token)) {
  11092. std::string result = model->vocab.id_to_token[token].text;
  11093. llama_unescape_whitespace(result);
  11094. if (length < (int) result.length()) {
  11095. return -(int) result.length();
  11096. }
  11097. memcpy(buf, result.c_str(), result.length());
  11098. return result.length();
  11099. } else if (llama_is_user_defined_token(model->vocab, token)) {
  11100. std::string result = model->vocab.id_to_token[token].text;
  11101. if (length < (int) result.length()) {
  11102. return -result.length();
  11103. }
  11104. memcpy(buf, result.c_str(), result.length());
  11105. return result.length();
  11106. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  11107. if (length < 3) {
  11108. return -3;
  11109. }
  11110. memcpy(buf, "\xe2\x96\x85", 3);
  11111. return 3;
  11112. } else if (llama_is_control_token(model->vocab, token)) {
  11113. ;
  11114. } else if (llama_is_byte_token(model->vocab, token)) {
  11115. if (length < 1) {
  11116. return -1;
  11117. }
  11118. buf[0] = llama_token_to_byte(model->vocab, token);
  11119. return 1;
  11120. }
  11121. break;
  11122. }
  11123. case LLAMA_VOCAB_TYPE_BPE: {
  11124. // NOTE: we accept all unsupported token types,
  11125. // suppressing them like CONTROL tokens.
  11126. if (llama_is_normal_token(model->vocab, token)) {
  11127. std::string result = model->vocab.id_to_token[token].text;
  11128. result = llama_decode_text(result);
  11129. if (length < (int) result.length()) {
  11130. return -(int) result.length();
  11131. }
  11132. memcpy(buf, result.c_str(), result.length());
  11133. return result.length();
  11134. } else if (llama_is_user_defined_token(model->vocab, token)) {
  11135. std::string result = model->vocab.id_to_token[token].text;
  11136. if (length < (int) result.length()) {
  11137. return -result.length();
  11138. }
  11139. memcpy(buf, result.c_str(), result.length());
  11140. return result.length();
  11141. } else if (llama_is_control_token(model->vocab, token)) {
  11142. ;
  11143. }
  11144. break;
  11145. }
  11146. default:
  11147. GGML_ASSERT(false);
  11148. }
  11149. }
  11150. return 0;
  11151. }
  11152. // trim whitespace from the beginning and end of a string
  11153. static std::string trim(const std::string & str) {
  11154. size_t start = 0;
  11155. size_t end = str.size();
  11156. while (start < end && isspace(str[start])) {
  11157. start += 1;
  11158. }
  11159. while (end > start && isspace(str[end - 1])) {
  11160. end -= 1;
  11161. }
  11162. return str.substr(start, end - start);
  11163. }
  11164. // Simple version of "llama_apply_chat_template" that only works with strings
  11165. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  11166. static int32_t llama_chat_apply_template_internal(
  11167. const std::string & tmpl,
  11168. const std::vector<const llama_chat_message *> & chat,
  11169. std::string & dest, bool add_ass) {
  11170. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  11171. std::stringstream ss;
  11172. if (tmpl == "chatml" || tmpl.find("<|im_start|>") != std::string::npos) {
  11173. // chatml template
  11174. for (auto message : chat) {
  11175. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  11176. }
  11177. if (add_ass) {
  11178. ss << "<|im_start|>assistant\n";
  11179. }
  11180. } else if (tmpl == "llama2" || tmpl.find("[INST]") != std::string::npos) {
  11181. // llama2 template and its variants
  11182. // [variant] support system message
  11183. bool support_system_message = tmpl.find("<<SYS>>") != std::string::npos;
  11184. // [variant] space before + after response
  11185. bool space_around_response = tmpl.find("' ' + eos_token") != std::string::npos;
  11186. // [variant] add BOS inside history
  11187. bool add_bos_inside_history = tmpl.find("bos_token + '[INST]") != std::string::npos;
  11188. // [variant] trim spaces from the input message
  11189. bool strip_message = tmpl.find("content.strip()") != std::string::npos;
  11190. // construct the prompt
  11191. bool is_inside_turn = true; // skip BOS at the beginning
  11192. ss << "[INST] ";
  11193. for (auto message : chat) {
  11194. std::string content = strip_message ? trim(message->content) : message->content;
  11195. std::string role(message->role);
  11196. if (!is_inside_turn) {
  11197. is_inside_turn = true;
  11198. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  11199. }
  11200. if (role == "system") {
  11201. if (support_system_message) {
  11202. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  11203. } else {
  11204. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  11205. ss << content << "\n";
  11206. }
  11207. } else if (role == "user") {
  11208. ss << content << " [/INST]";
  11209. } else {
  11210. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  11211. is_inside_turn = false;
  11212. }
  11213. }
  11214. // llama2 templates seem to not care about "add_generation_prompt"
  11215. } else if (tmpl == "zephyr" || tmpl.find("<|user|>") != std::string::npos) {
  11216. // zephyr template
  11217. for (auto message : chat) {
  11218. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  11219. }
  11220. if (add_ass) {
  11221. ss << "<|assistant|>\n";
  11222. }
  11223. } else if (tmpl == "monarch" || tmpl.find("bos_token + message['role']") != std::string::npos) {
  11224. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  11225. for (auto message : chat) {
  11226. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  11227. ss << bos << message->role << "\n" << message->content << "</s>\n";
  11228. }
  11229. if (add_ass) {
  11230. ss << "<s>assistant\n";
  11231. }
  11232. } else if (tmpl == "gemma" || tmpl.find("<start_of_turn>") != std::string::npos) {
  11233. // google/gemma-7b-it
  11234. std::string system_prompt = "";
  11235. for (auto message : chat) {
  11236. std::string role(message->role);
  11237. if (role == "system") {
  11238. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  11239. system_prompt = trim(message->content);
  11240. continue;
  11241. }
  11242. // in gemma, "assistant" is "model"
  11243. role = role == "assistant" ? "model" : message->role;
  11244. ss << "<start_of_turn>" << role << "\n";
  11245. if (!system_prompt.empty() && role != "model") {
  11246. ss << system_prompt << "\n\n";
  11247. system_prompt = "";
  11248. }
  11249. ss << trim(message->content) << "<end_of_turn>\n";
  11250. }
  11251. if (add_ass) {
  11252. ss << "<start_of_turn>model\n";
  11253. }
  11254. } else {
  11255. // template not supported
  11256. return -1;
  11257. }
  11258. dest = ss.str();
  11259. return dest.size();
  11260. }
  11261. LLAMA_API int32_t llama_chat_apply_template(
  11262. const struct llama_model * model,
  11263. const char * tmpl,
  11264. const struct llama_chat_message * chat,
  11265. size_t n_msg,
  11266. bool add_ass,
  11267. char * buf,
  11268. int32_t length) {
  11269. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  11270. if (tmpl == nullptr) {
  11271. GGML_ASSERT(model != nullptr);
  11272. // load template from model
  11273. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  11274. std::string template_key = "tokenizer.chat_template";
  11275. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  11276. if (res < 0) {
  11277. // worst case: there is no information about template, we will use chatml by default
  11278. curr_tmpl = "chatml"; // see llama_chat_apply_template_internal
  11279. } else {
  11280. curr_tmpl = std::string(model_template.data(), model_template.size());
  11281. }
  11282. }
  11283. // format the chat to string
  11284. std::vector<const llama_chat_message *> chat_vec;
  11285. chat_vec.resize(n_msg);
  11286. for (size_t i = 0; i < n_msg; i++) {
  11287. chat_vec[i] = &chat[i];
  11288. }
  11289. std::string formatted_chat;
  11290. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  11291. if (res < 0) {
  11292. return res;
  11293. }
  11294. if (buf && length > 0) {
  11295. strncpy(buf, formatted_chat.c_str(), length);
  11296. }
  11297. return res;
  11298. }
  11299. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  11300. struct llama_timings result = {
  11301. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  11302. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  11303. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  11304. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  11305. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  11306. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  11307. /*.n_sample =*/ std::max(1, ctx->n_sample),
  11308. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  11309. /*.n_eval =*/ std::max(1, ctx->n_eval),
  11310. };
  11311. return result;
  11312. }
  11313. void llama_print_timings(struct llama_context * ctx) {
  11314. const llama_timings timings = llama_get_timings(ctx);
  11315. LLAMA_LOG_INFO("\n");
  11316. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  11317. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  11318. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  11319. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  11320. __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);
  11321. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  11322. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  11323. 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));
  11324. }
  11325. void llama_reset_timings(struct llama_context * ctx) {
  11326. ctx->t_start_us = ggml_time_us();
  11327. ctx->t_sample_us = ctx->n_sample = 0;
  11328. ctx->t_eval_us = ctx->n_eval = 0;
  11329. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  11330. }
  11331. const char * llama_print_system_info(void) {
  11332. static std::string s;
  11333. s = "";
  11334. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  11335. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  11336. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  11337. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  11338. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  11339. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  11340. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  11341. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  11342. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  11343. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  11344. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  11345. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  11346. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  11347. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  11348. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  11349. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  11350. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  11351. return s.c_str();
  11352. }
  11353. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  11354. fprintf(stream, "\n");
  11355. fprintf(stream, "###########\n");
  11356. fprintf(stream, "# Timings #\n");
  11357. fprintf(stream, "###########\n");
  11358. fprintf(stream, "\n");
  11359. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  11360. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  11361. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  11362. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  11363. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  11364. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  11365. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  11366. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  11367. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  11368. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  11369. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  11370. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  11371. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  11372. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  11373. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  11374. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  11375. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  11376. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  11377. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  11378. }
  11379. // For internal test use
  11380. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  11381. struct llama_context * ctx
  11382. ) {
  11383. return ctx->model.tensors_by_name;
  11384. }
  11385. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  11386. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  11387. g_state.log_callback_user_data = user_data;
  11388. #ifdef GGML_USE_METAL
  11389. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  11390. #endif
  11391. }
  11392. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  11393. va_list args_copy;
  11394. va_copy(args_copy, args);
  11395. char buffer[128];
  11396. int len = vsnprintf(buffer, 128, format, args);
  11397. if (len < 128) {
  11398. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  11399. } else {
  11400. char* buffer2 = new char[len+1];
  11401. vsnprintf(buffer2, len+1, format, args_copy);
  11402. buffer2[len] = 0;
  11403. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  11404. delete[] buffer2;
  11405. }
  11406. va_end(args_copy);
  11407. }
  11408. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  11409. va_list args;
  11410. va_start(args, format);
  11411. llama_log_internal_v(level, format, args);
  11412. va_end(args);
  11413. }
  11414. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  11415. (void) level;
  11416. (void) user_data;
  11417. fputs(text, stderr);
  11418. fflush(stderr);
  11419. }