llama.cpp 479 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412
  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 <forward_list>
  65. #include <fstream>
  66. #include <functional>
  67. #include <initializer_list>
  68. #include <map>
  69. #include <memory>
  70. #include <mutex>
  71. #include <numeric>
  72. #include <queue>
  73. #include <random>
  74. #include <regex>
  75. #include <set>
  76. #include <sstream>
  77. #include <thread>
  78. #include <type_traits>
  79. #include <unordered_map>
  80. #if defined(_MSC_VER)
  81. #pragma warning(disable: 4244 4267) // possible loss of data
  82. #endif
  83. #ifdef __GNUC__
  84. #ifdef __MINGW32__
  85. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  86. #else
  87. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  88. #endif
  89. #else
  90. #define LLAMA_ATTRIBUTE_FORMAT(...)
  91. #endif
  92. #define LLAMA_MAX_NODES 8192
  93. #define LLAMA_MAX_EXPERTS 8
  94. //
  95. // logging
  96. //
  97. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  98. static void llama_log_internal (ggml_log_level level, const char* format, ...);
  99. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
  100. #define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  101. #define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  102. #define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  103. //
  104. // helpers
  105. //
  106. static size_t utf8_len(char src) {
  107. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  108. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  109. return lookup[highbits];
  110. }
  111. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  112. std::string result;
  113. for (size_t pos = 0; ; pos += search.length()) {
  114. auto new_pos = s.find(search, pos);
  115. if (new_pos == std::string::npos) {
  116. result += s.substr(pos, s.size() - pos);
  117. break;
  118. }
  119. result += s.substr(pos, new_pos - pos) + replace;
  120. pos = new_pos;
  121. }
  122. s = std::move(result);
  123. }
  124. static bool is_float_close(float a, float b, float abs_tol) {
  125. // Check for non-negative tolerance
  126. if (abs_tol < 0.0) {
  127. throw std::invalid_argument("Tolerance must be non-negative");
  128. }
  129. // Exact equality check
  130. if (a == b) {
  131. return true;
  132. }
  133. // Check for infinities
  134. if (std::isinf(a) || std::isinf(b)) {
  135. return false;
  136. }
  137. // Regular comparison using the provided absolute tolerance
  138. return std::fabs(b - a) <= abs_tol;
  139. }
  140. static void zeros(std::ofstream & file, size_t n) {
  141. char zero = 0;
  142. for (size_t i = 0; i < n; ++i) {
  143. file.write(&zero, 1);
  144. }
  145. }
  146. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  147. static std::string format(const char * fmt, ...) {
  148. va_list ap;
  149. va_list ap2;
  150. va_start(ap, fmt);
  151. va_copy(ap2, ap);
  152. int size = vsnprintf(NULL, 0, fmt, ap);
  153. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  154. std::vector<char> buf(size + 1);
  155. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  156. GGML_ASSERT(size2 == size);
  157. va_end(ap2);
  158. va_end(ap);
  159. return std::string(buf.data(), size);
  160. }
  161. //
  162. // gguf constants (sync with gguf.py)
  163. //
  164. enum llm_arch {
  165. LLM_ARCH_LLAMA,
  166. LLM_ARCH_FALCON,
  167. LLM_ARCH_BAICHUAN,
  168. LLM_ARCH_GPT2,
  169. LLM_ARCH_GPTJ,
  170. LLM_ARCH_GPTNEOX,
  171. LLM_ARCH_MPT,
  172. LLM_ARCH_STARCODER,
  173. LLM_ARCH_PERSIMMON,
  174. LLM_ARCH_REFACT,
  175. LLM_ARCH_BERT,
  176. LLM_ARCH_BLOOM,
  177. LLM_ARCH_STABLELM,
  178. LLM_ARCH_QWEN,
  179. LLM_ARCH_QWEN2,
  180. LLM_ARCH_PHI2,
  181. LLM_ARCH_PLAMO,
  182. LLM_ARCH_CODESHELL,
  183. LLM_ARCH_ORION,
  184. LLM_ARCH_INTERNLM2,
  185. LLM_ARCH_MINICPM,
  186. LLM_ARCH_UNKNOWN,
  187. };
  188. static std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  189. { LLM_ARCH_LLAMA, "llama" },
  190. { LLM_ARCH_FALCON, "falcon" },
  191. { LLM_ARCH_GPT2, "gpt2" },
  192. { LLM_ARCH_GPTJ, "gptj" },
  193. { LLM_ARCH_GPTNEOX, "gptneox" },
  194. { LLM_ARCH_MPT, "mpt" },
  195. { LLM_ARCH_BAICHUAN, "baichuan" },
  196. { LLM_ARCH_STARCODER, "starcoder" },
  197. { LLM_ARCH_PERSIMMON, "persimmon" },
  198. { LLM_ARCH_REFACT, "refact" },
  199. { LLM_ARCH_BERT, "bert" },
  200. { LLM_ARCH_BLOOM, "bloom" },
  201. { LLM_ARCH_STABLELM, "stablelm" },
  202. { LLM_ARCH_QWEN, "qwen" },
  203. { LLM_ARCH_QWEN2, "qwen2" },
  204. { LLM_ARCH_PHI2, "phi2" },
  205. { LLM_ARCH_PLAMO, "plamo" },
  206. { LLM_ARCH_CODESHELL, "codeshell" },
  207. { LLM_ARCH_ORION, "orion" },
  208. { LLM_ARCH_INTERNLM2, "internlm2" },
  209. { LLM_ARCH_MINICPM, "minicpm" },
  210. };
  211. enum llm_kv {
  212. LLM_KV_GENERAL_ARCHITECTURE,
  213. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  214. LLM_KV_GENERAL_ALIGNMENT,
  215. LLM_KV_GENERAL_NAME,
  216. LLM_KV_GENERAL_AUTHOR,
  217. LLM_KV_GENERAL_URL,
  218. LLM_KV_GENERAL_DESCRIPTION,
  219. LLM_KV_GENERAL_LICENSE,
  220. LLM_KV_GENERAL_SOURCE_URL,
  221. LLM_KV_GENERAL_SOURCE_HF_REPO,
  222. LLM_KV_CONTEXT_LENGTH,
  223. LLM_KV_EMBEDDING_LENGTH,
  224. LLM_KV_BLOCK_COUNT,
  225. LLM_KV_FEED_FORWARD_LENGTH,
  226. LLM_KV_USE_PARALLEL_RESIDUAL,
  227. LLM_KV_TENSOR_DATA_LAYOUT,
  228. LLM_KV_EXPERT_COUNT,
  229. LLM_KV_EXPERT_USED_COUNT,
  230. LLM_KV_ATTENTION_HEAD_COUNT,
  231. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  232. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  233. LLM_KV_ATTENTION_CLAMP_KQV,
  234. LLM_KV_ATTENTION_KEY_LENGTH,
  235. LLM_KV_ATTENTION_VALUE_LENGTH,
  236. LLM_KV_ATTENTION_LAYERNORM_EPS,
  237. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  238. LLM_KV_ATTENTION_CAUSAL,
  239. LLM_KV_ROPE_DIMENSION_COUNT,
  240. LLM_KV_ROPE_FREQ_BASE,
  241. LLM_KV_ROPE_SCALE_LINEAR,
  242. LLM_KV_ROPE_SCALING_TYPE,
  243. LLM_KV_ROPE_SCALING_FACTOR,
  244. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  245. LLM_KV_ROPE_SCALING_FINETUNED,
  246. LLM_KV_TOKENIZER_MODEL,
  247. LLM_KV_TOKENIZER_LIST,
  248. LLM_KV_TOKENIZER_TOKEN_TYPE,
  249. LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT,
  250. LLM_KV_TOKENIZER_SCORES,
  251. LLM_KV_TOKENIZER_MERGES,
  252. LLM_KV_TOKENIZER_BOS_ID,
  253. LLM_KV_TOKENIZER_EOS_ID,
  254. LLM_KV_TOKENIZER_UNK_ID,
  255. LLM_KV_TOKENIZER_SEP_ID,
  256. LLM_KV_TOKENIZER_PAD_ID,
  257. LLM_KV_TOKENIZER_ADD_BOS,
  258. LLM_KV_TOKENIZER_ADD_EOS,
  259. LLM_KV_TOKENIZER_ADD_PREFIX,
  260. LLM_KV_TOKENIZER_HF_JSON,
  261. LLM_KV_TOKENIZER_RWKV,
  262. };
  263. static std::map<llm_kv, const char *> LLM_KV_NAMES = {
  264. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  265. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  266. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  267. { LLM_KV_GENERAL_NAME, "general.name" },
  268. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  269. { LLM_KV_GENERAL_URL, "general.url" },
  270. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  271. { LLM_KV_GENERAL_LICENSE, "general.license" },
  272. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  273. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  274. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  275. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  276. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  277. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  278. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  279. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  280. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  281. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  282. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  283. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  284. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  285. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  286. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  287. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  288. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  289. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  290. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  291. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  292. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  293. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  294. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  295. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  296. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  297. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  298. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  299. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  300. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  301. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  302. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  303. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  304. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  305. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  306. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  307. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  308. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  309. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  310. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  311. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  312. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  313. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  314. };
  315. struct LLM_KV {
  316. LLM_KV(llm_arch arch) : arch(arch) {}
  317. llm_arch arch;
  318. std::string operator()(llm_kv kv) const {
  319. return ::format(LLM_KV_NAMES[kv], LLM_ARCH_NAMES[arch]);
  320. }
  321. };
  322. enum llm_tensor {
  323. LLM_TENSOR_TOKEN_EMBD,
  324. LLM_TENSOR_TOKEN_EMBD_NORM,
  325. LLM_TENSOR_TOKEN_TYPES,
  326. LLM_TENSOR_POS_EMBD,
  327. LLM_TENSOR_OUTPUT,
  328. LLM_TENSOR_OUTPUT_NORM,
  329. LLM_TENSOR_ROPE_FREQS,
  330. LLM_TENSOR_ATTN_Q,
  331. LLM_TENSOR_ATTN_K,
  332. LLM_TENSOR_ATTN_V,
  333. LLM_TENSOR_ATTN_QKV,
  334. LLM_TENSOR_ATTN_OUT,
  335. LLM_TENSOR_ATTN_NORM,
  336. LLM_TENSOR_ATTN_NORM_2,
  337. LLM_TENSOR_ATTN_ROT_EMBD,
  338. LLM_TENSOR_FFN_GATE_INP,
  339. LLM_TENSOR_FFN_NORM,
  340. LLM_TENSOR_FFN_GATE,
  341. LLM_TENSOR_FFN_DOWN,
  342. LLM_TENSOR_FFN_UP,
  343. LLM_TENSOR_FFN_ACT,
  344. LLM_TENSOR_FFN_DOWN_EXP,
  345. LLM_TENSOR_FFN_GATE_EXP,
  346. LLM_TENSOR_FFN_UP_EXP,
  347. LLM_TENSOR_ATTN_Q_NORM,
  348. LLM_TENSOR_ATTN_K_NORM,
  349. };
  350. static std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  351. {
  352. LLM_ARCH_LLAMA,
  353. {
  354. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  355. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  356. { LLM_TENSOR_OUTPUT, "output" },
  357. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  358. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  359. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  360. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  361. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  362. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  363. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  364. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  365. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  366. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  367. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  368. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  369. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  370. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  371. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  372. },
  373. },
  374. {
  375. LLM_ARCH_BAICHUAN,
  376. {
  377. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  378. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  379. { LLM_TENSOR_OUTPUT, "output" },
  380. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  381. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  382. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  383. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  384. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  385. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  386. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  387. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  388. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  389. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  390. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  391. },
  392. },
  393. {
  394. LLM_ARCH_FALCON,
  395. {
  396. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  397. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  398. { LLM_TENSOR_OUTPUT, "output" },
  399. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  400. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  401. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  402. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  403. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  404. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  405. },
  406. },
  407. {
  408. LLM_ARCH_GPT2,
  409. {
  410. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  411. { LLM_TENSOR_POS_EMBD, "position_embd" },
  412. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  413. { LLM_TENSOR_OUTPUT, "output" },
  414. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  415. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  416. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  417. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  418. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  419. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  420. },
  421. },
  422. {
  423. LLM_ARCH_GPTJ,
  424. {
  425. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  426. },
  427. },
  428. {
  429. LLM_ARCH_GPTNEOX,
  430. {
  431. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  432. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  433. { LLM_TENSOR_OUTPUT, "output" },
  434. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  435. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  436. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  437. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  438. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  439. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  440. },
  441. },
  442. {
  443. LLM_ARCH_PERSIMMON,
  444. {
  445. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  446. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  447. { LLM_TENSOR_OUTPUT, "output"},
  448. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  449. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  450. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  451. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  452. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  453. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  454. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  455. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  456. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  457. },
  458. },
  459. {
  460. LLM_ARCH_MPT,
  461. {
  462. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  463. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  464. { LLM_TENSOR_OUTPUT, "output" },
  465. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  466. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  467. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  468. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  469. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  470. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  471. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  472. },
  473. },
  474. {
  475. LLM_ARCH_STARCODER,
  476. {
  477. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  478. { LLM_TENSOR_POS_EMBD, "position_embd" },
  479. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  480. { LLM_TENSOR_OUTPUT, "output" },
  481. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  482. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  483. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  484. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  485. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  486. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  487. },
  488. },
  489. {
  490. LLM_ARCH_REFACT,
  491. {
  492. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  493. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  494. { LLM_TENSOR_OUTPUT, "output" },
  495. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  496. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  497. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  498. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  499. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  500. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  501. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  502. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  503. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  504. },
  505. },
  506. {
  507. LLM_ARCH_BERT,
  508. {
  509. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  510. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  511. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  512. { LLM_TENSOR_POS_EMBD, "position_embd" },
  513. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_output_norm" },
  514. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  515. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  516. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  517. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  518. { LLM_TENSOR_FFN_NORM, "blk.%d.layer_output_norm" },
  519. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  520. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  521. },
  522. },
  523. {
  524. LLM_ARCH_BLOOM,
  525. {
  526. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  527. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  528. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  529. { LLM_TENSOR_OUTPUT, "output" },
  530. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  531. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  532. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  533. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  534. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  535. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  536. },
  537. },
  538. {
  539. LLM_ARCH_STABLELM,
  540. {
  541. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  542. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  543. { LLM_TENSOR_OUTPUT, "output" },
  544. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  545. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  546. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  547. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  548. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  549. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  550. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  551. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  552. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  553. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  554. },
  555. },
  556. {
  557. LLM_ARCH_QWEN,
  558. {
  559. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  560. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  561. { LLM_TENSOR_OUTPUT, "output" },
  562. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  563. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  564. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  565. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  566. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  567. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  568. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  569. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  570. },
  571. },
  572. {
  573. LLM_ARCH_QWEN2,
  574. {
  575. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  576. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  577. { LLM_TENSOR_OUTPUT, "output" },
  578. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  579. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  580. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  581. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  582. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  583. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  584. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  585. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  586. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  587. },
  588. },
  589. {
  590. LLM_ARCH_PHI2,
  591. {
  592. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  593. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  594. { LLM_TENSOR_OUTPUT, "output" },
  595. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  596. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  597. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  598. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  599. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  600. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  601. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  602. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  603. },
  604. },
  605. {
  606. LLM_ARCH_PLAMO,
  607. {
  608. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  609. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  610. { LLM_TENSOR_OUTPUT, "output" },
  611. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  612. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  613. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  614. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  615. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  616. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  617. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  618. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  619. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  620. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  621. },
  622. },
  623. {
  624. LLM_ARCH_CODESHELL,
  625. {
  626. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  627. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  628. { LLM_TENSOR_OUTPUT, "output" },
  629. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  630. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  631. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  632. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  633. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  634. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  635. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  636. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  637. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  638. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  639. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  640. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  641. },
  642. },
  643. {
  644. LLM_ARCH_ORION,
  645. {
  646. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  647. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  648. { LLM_TENSOR_OUTPUT, "output" },
  649. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  650. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  651. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  652. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  653. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  654. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  655. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  656. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  657. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  658. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  659. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  660. },
  661. },
  662. {
  663. LLM_ARCH_INTERNLM2,
  664. {
  665. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  666. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  667. { LLM_TENSOR_OUTPUT, "output" },
  668. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  669. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  670. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  671. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  672. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  673. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  674. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  675. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  676. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  677. },
  678. },
  679. {
  680. LLM_ARCH_MINICPM,
  681. {
  682. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  683. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  684. { LLM_TENSOR_OUTPUT, "output" },
  685. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  686. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  687. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  688. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  689. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  690. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  691. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  692. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  693. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  694. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  695. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  696. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  697. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  698. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  699. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  700. },
  701. },
  702. {
  703. LLM_ARCH_UNKNOWN,
  704. {
  705. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  706. },
  707. },
  708. };
  709. static llm_arch llm_arch_from_string(const std::string & name) {
  710. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  711. if (kv.second == name) {
  712. return kv.first;
  713. }
  714. }
  715. return LLM_ARCH_UNKNOWN;
  716. }
  717. // helper to handle gguf constants
  718. // usage:
  719. //
  720. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  721. //
  722. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  723. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  724. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  725. //
  726. struct LLM_TN {
  727. LLM_TN(llm_arch arch) : arch(arch) {}
  728. llm_arch arch;
  729. std::string operator()(llm_tensor tensor) const {
  730. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  731. return "__missing__";
  732. }
  733. return LLM_TENSOR_NAMES[arch].at(tensor);
  734. }
  735. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  736. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  737. return "__missing__";
  738. }
  739. return LLM_TENSOR_NAMES[arch].at(tensor) + "." + suffix;
  740. }
  741. std::string operator()(llm_tensor tensor, int bid) const {
  742. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  743. return "__missing__";
  744. }
  745. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid);
  746. }
  747. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  748. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  749. return "__missing__";
  750. }
  751. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid) + "." + suffix;
  752. }
  753. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  754. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  755. return "__missing__";
  756. }
  757. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid, xid) + "." + suffix;
  758. }
  759. };
  760. //
  761. // gguf helpers
  762. //
  763. static std::map<int32_t, const char *> LLAMA_ROPE_SCALING_TYPES = {
  764. { LLAMA_ROPE_SCALING_NONE, "none" },
  765. { LLAMA_ROPE_SCALING_LINEAR, "linear" },
  766. { LLAMA_ROPE_SCALING_YARN, "yarn" },
  767. };
  768. static int32_t llama_rope_scaling_type_from_string(const std::string & name) {
  769. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  770. if (kv.second == name) {
  771. return kv.first;
  772. }
  773. }
  774. return LLAMA_ROPE_SCALING_UNSPECIFIED;
  775. }
  776. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  777. switch (type) {
  778. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  779. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  780. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  781. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  782. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  783. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  784. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  785. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  786. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  787. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  788. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  789. default: return format("unknown type %d", type);
  790. }
  791. }
  792. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  793. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  794. switch (type) {
  795. case GGUF_TYPE_STRING:
  796. return gguf_get_val_str(ctx_gguf, i);
  797. case GGUF_TYPE_ARRAY:
  798. {
  799. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  800. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  801. const void * data = gguf_get_arr_data(ctx_gguf, i);
  802. std::stringstream ss;
  803. ss << "[";
  804. for (int j = 0; j < arr_n; j++) {
  805. if (arr_type == GGUF_TYPE_STRING) {
  806. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  807. // escape quotes
  808. replace_all(val, "\\", "\\\\");
  809. replace_all(val, "\"", "\\\"");
  810. ss << '"' << val << '"';
  811. } else if (arr_type == GGUF_TYPE_ARRAY) {
  812. ss << "???";
  813. } else {
  814. ss << gguf_data_to_str(arr_type, data, j);
  815. }
  816. if (j < arr_n - 1) {
  817. ss << ", ";
  818. }
  819. }
  820. ss << "]";
  821. return ss.str();
  822. }
  823. default:
  824. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  825. }
  826. }
  827. //
  828. // ggml helpers
  829. //
  830. static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
  831. struct ggml_cplan plan = ggml_graph_plan(graph, n_threads);
  832. if (plan.work_size > 0) {
  833. buf.resize(plan.work_size);
  834. plan.work_data = buf.data();
  835. }
  836. ggml_graph_compute(graph, &plan);
  837. }
  838. //
  839. // llama helpers
  840. //
  841. #if defined(_WIN32)
  842. static std::string llama_format_win_err(DWORD err) {
  843. LPSTR buf;
  844. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  845. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  846. if (!size) {
  847. return "FormatMessageA failed";
  848. }
  849. std::string ret(buf, size);
  850. LocalFree(buf);
  851. return ret;
  852. }
  853. #endif
  854. template <typename T>
  855. struct no_init {
  856. T value;
  857. no_init() { /* do nothing */ }
  858. };
  859. struct llama_file {
  860. // use FILE * so we don't have to re-open the file to mmap
  861. FILE * fp;
  862. size_t size;
  863. llama_file(const char * fname, const char * mode) {
  864. fp = std::fopen(fname, mode);
  865. if (fp == NULL) {
  866. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  867. }
  868. seek(0, SEEK_END);
  869. size = tell();
  870. seek(0, SEEK_SET);
  871. }
  872. size_t tell() const {
  873. #ifdef _WIN32
  874. __int64 ret = _ftelli64(fp);
  875. #else
  876. long ret = std::ftell(fp);
  877. #endif
  878. GGML_ASSERT(ret != -1); // this really shouldn't fail
  879. return (size_t) ret;
  880. }
  881. void seek(size_t offset, int whence) const {
  882. #ifdef _WIN32
  883. int ret = _fseeki64(fp, (__int64) offset, whence);
  884. #else
  885. int ret = std::fseek(fp, (long) offset, whence);
  886. #endif
  887. GGML_ASSERT(ret == 0); // same
  888. }
  889. void read_raw(void * ptr, size_t len) const {
  890. if (len == 0) {
  891. return;
  892. }
  893. errno = 0;
  894. std::size_t ret = std::fread(ptr, len, 1, fp);
  895. if (ferror(fp)) {
  896. throw std::runtime_error(format("read error: %s", strerror(errno)));
  897. }
  898. if (ret != 1) {
  899. throw std::runtime_error("unexpectedly reached end of file");
  900. }
  901. }
  902. uint32_t read_u32() const {
  903. uint32_t ret;
  904. read_raw(&ret, sizeof(ret));
  905. return ret;
  906. }
  907. void write_raw(const void * ptr, size_t len) const {
  908. if (len == 0) {
  909. return;
  910. }
  911. errno = 0;
  912. size_t ret = std::fwrite(ptr, len, 1, fp);
  913. if (ret != 1) {
  914. throw std::runtime_error(format("write error: %s", strerror(errno)));
  915. }
  916. }
  917. void write_u32(std::uint32_t val) const {
  918. write_raw(&val, sizeof(val));
  919. }
  920. ~llama_file() {
  921. if (fp) {
  922. std::fclose(fp);
  923. }
  924. }
  925. };
  926. struct llama_mmap {
  927. void * addr;
  928. size_t size;
  929. llama_mmap(const llama_mmap &) = delete;
  930. #ifdef _POSIX_MAPPED_FILES
  931. static constexpr bool SUPPORTED = true;
  932. // list of mapped fragments (first_offset, last_offset)
  933. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  934. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  935. size = file->size;
  936. int fd = fileno(file->fp);
  937. int flags = MAP_SHARED;
  938. // prefetch/readahead impairs performance on NUMA systems
  939. if (numa) { prefetch = 0; }
  940. #ifdef __linux__
  941. // advise the kernel to read the file sequentially (increases readahead)
  942. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  943. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  944. strerror(errno));
  945. }
  946. if (prefetch) { flags |= MAP_POPULATE; }
  947. #endif
  948. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  949. if (addr == MAP_FAILED) { // NOLINT
  950. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  951. }
  952. if (prefetch > 0) {
  953. // advise the kernel to preload the mapped memory
  954. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  955. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  956. strerror(errno));
  957. }
  958. }
  959. if (numa) {
  960. // advise the kernel not to use readahead
  961. // (because the next page might not belong on the same node)
  962. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  963. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  964. strerror(errno));
  965. }
  966. }
  967. // initialize list of mapped_fragments
  968. mapped_fragments.emplace_back(0, file->size);
  969. }
  970. static void align_range(size_t * first, size_t * last, size_t page_size) {
  971. // align first to the next page
  972. size_t offset_in_page = *first & (page_size - 1);
  973. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  974. *first += offset_to_page;
  975. // align last to the previous page
  976. *last = *last & ~(page_size - 1);
  977. if (*last <= *first) {
  978. *last = *first;
  979. }
  980. }
  981. // partially unmap the file in the range [first, last)
  982. void unmap_fragment(size_t first, size_t last) {
  983. // note: this function must not be called multiple times with overlapping ranges
  984. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  985. int page_size = sysconf(_SC_PAGESIZE);
  986. align_range(&first, &last, page_size);
  987. size_t len = last - first;
  988. if (len == 0) {
  989. return;
  990. }
  991. GGML_ASSERT(first % page_size == 0);
  992. GGML_ASSERT(last % page_size == 0);
  993. GGML_ASSERT(last > first);
  994. void * next_page_start = (uint8_t *) addr + first;
  995. // unmap the range
  996. if (munmap(next_page_start, len)) {
  997. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  998. }
  999. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  1000. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  1001. for (const auto & frag : mapped_fragments) {
  1002. if (frag.first < first && frag.second > last) {
  1003. // the range is in the middle of the fragment, split it
  1004. new_mapped_fragments.emplace_back(frag.first, first);
  1005. new_mapped_fragments.emplace_back(last, frag.second);
  1006. } else if (frag.first < first && frag.second > first) {
  1007. // the range starts in the middle of the fragment
  1008. new_mapped_fragments.emplace_back(frag.first, first);
  1009. } else if (frag.first < last && frag.second > last) {
  1010. // the range ends in the middle of the fragment
  1011. new_mapped_fragments.emplace_back(last, frag.second);
  1012. } else if (frag.first >= first && frag.second <= last) {
  1013. // the range covers the entire fragment
  1014. } else {
  1015. // the range is outside the fragment
  1016. new_mapped_fragments.push_back(frag);
  1017. }
  1018. }
  1019. mapped_fragments = std::move(new_mapped_fragments);
  1020. }
  1021. ~llama_mmap() {
  1022. for (const auto & frag : mapped_fragments) {
  1023. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  1024. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1025. }
  1026. }
  1027. }
  1028. #elif defined(_WIN32)
  1029. static constexpr bool SUPPORTED = true;
  1030. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  1031. GGML_UNUSED(numa);
  1032. size = file->size;
  1033. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  1034. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  1035. if (hMapping == NULL) {
  1036. DWORD error = GetLastError();
  1037. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  1038. }
  1039. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  1040. DWORD error = GetLastError();
  1041. CloseHandle(hMapping);
  1042. if (addr == NULL) {
  1043. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  1044. }
  1045. if (prefetch > 0) {
  1046. #if _WIN32_WINNT >= 0x602
  1047. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  1048. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  1049. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  1050. // may fail on pre-Windows 8 systems
  1051. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  1052. if (pPrefetchVirtualMemory) {
  1053. // advise the kernel to preload the mapped memory
  1054. WIN32_MEMORY_RANGE_ENTRY range;
  1055. range.VirtualAddress = addr;
  1056. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  1057. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  1058. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  1059. llama_format_win_err(GetLastError()).c_str());
  1060. }
  1061. }
  1062. #else
  1063. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  1064. #endif
  1065. }
  1066. }
  1067. void unmap_fragment(size_t first, size_t last) {
  1068. // not supported
  1069. GGML_UNUSED(first);
  1070. GGML_UNUSED(last);
  1071. }
  1072. ~llama_mmap() {
  1073. if (!UnmapViewOfFile(addr)) {
  1074. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  1075. llama_format_win_err(GetLastError()).c_str());
  1076. }
  1077. }
  1078. #else
  1079. static constexpr bool SUPPORTED = false;
  1080. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  1081. GGML_UNUSED(file);
  1082. GGML_UNUSED(prefetch);
  1083. GGML_UNUSED(numa);
  1084. throw std::runtime_error("mmap not supported");
  1085. }
  1086. void unmap_fragment(size_t first, size_t last) {
  1087. GGML_UNUSED(first);
  1088. GGML_UNUSED(last);
  1089. throw std::runtime_error("mmap not supported");
  1090. }
  1091. #endif
  1092. };
  1093. // Represents some region of memory being locked using mlock or VirtualLock;
  1094. // will automatically unlock on destruction.
  1095. struct llama_mlock {
  1096. void * addr = NULL;
  1097. size_t size = 0;
  1098. bool failed_already = false;
  1099. llama_mlock() {}
  1100. llama_mlock(const llama_mlock &) = delete;
  1101. ~llama_mlock() {
  1102. if (size) {
  1103. raw_unlock(addr, size);
  1104. }
  1105. }
  1106. void init(void * ptr) {
  1107. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1108. addr = ptr;
  1109. }
  1110. void grow_to(size_t target_size) {
  1111. GGML_ASSERT(addr);
  1112. if (failed_already) {
  1113. return;
  1114. }
  1115. size_t granularity = lock_granularity();
  1116. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1117. if (target_size > size) {
  1118. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1119. size = target_size;
  1120. } else {
  1121. failed_already = true;
  1122. }
  1123. }
  1124. }
  1125. #ifdef _POSIX_MEMLOCK_RANGE
  1126. static constexpr bool SUPPORTED = true;
  1127. static size_t lock_granularity() {
  1128. return (size_t) sysconf(_SC_PAGESIZE);
  1129. }
  1130. #ifdef __APPLE__
  1131. #define MLOCK_SUGGESTION \
  1132. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1133. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  1134. #else
  1135. #define MLOCK_SUGGESTION \
  1136. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  1137. #endif
  1138. bool raw_lock(const void * addr, size_t size) const {
  1139. if (!mlock(addr, size)) {
  1140. return true;
  1141. }
  1142. char* errmsg = std::strerror(errno);
  1143. bool suggest = (errno == ENOMEM);
  1144. // Check if the resource limit is fine after all
  1145. struct rlimit lock_limit;
  1146. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1147. suggest = false;
  1148. }
  1149. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1150. suggest = false;
  1151. }
  1152. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1153. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1154. return false;
  1155. }
  1156. #undef MLOCK_SUGGESTION
  1157. static void raw_unlock(void * addr, size_t size) {
  1158. if (munlock(addr, size)) {
  1159. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1160. }
  1161. }
  1162. #elif defined(_WIN32)
  1163. static constexpr bool SUPPORTED = true;
  1164. static size_t lock_granularity() {
  1165. SYSTEM_INFO si;
  1166. GetSystemInfo(&si);
  1167. return (size_t) si.dwPageSize;
  1168. }
  1169. bool raw_lock(void * ptr, size_t len) const {
  1170. for (int tries = 1; ; tries++) {
  1171. if (VirtualLock(ptr, len)) {
  1172. return true;
  1173. }
  1174. if (tries == 2) {
  1175. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1176. len, size, llama_format_win_err(GetLastError()).c_str());
  1177. return false;
  1178. }
  1179. // It failed but this was only the first try; increase the working
  1180. // set size and try again.
  1181. SIZE_T min_ws_size, max_ws_size;
  1182. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1183. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1184. llama_format_win_err(GetLastError()).c_str());
  1185. return false;
  1186. }
  1187. // Per MSDN: "The maximum number of pages that a process can lock
  1188. // is equal to the number of pages in its minimum working set minus
  1189. // a small overhead."
  1190. // Hopefully a megabyte is enough overhead:
  1191. size_t increment = len + 1048576;
  1192. // The minimum must be <= the maximum, so we need to increase both:
  1193. min_ws_size += increment;
  1194. max_ws_size += increment;
  1195. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1196. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1197. llama_format_win_err(GetLastError()).c_str());
  1198. return false;
  1199. }
  1200. }
  1201. }
  1202. static void raw_unlock(void * ptr, size_t len) {
  1203. if (!VirtualUnlock(ptr, len)) {
  1204. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1205. llama_format_win_err(GetLastError()).c_str());
  1206. }
  1207. }
  1208. #else
  1209. static constexpr bool SUPPORTED = false;
  1210. static size_t lock_granularity() {
  1211. return (size_t) 65536;
  1212. }
  1213. bool raw_lock(const void * addr, size_t len) const {
  1214. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1215. return false;
  1216. }
  1217. static void raw_unlock(const void * addr, size_t len) {}
  1218. #endif
  1219. };
  1220. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1221. std::vector<char> result(8, 0);
  1222. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1223. if (n_tokens < 0) {
  1224. result.resize(-n_tokens);
  1225. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1226. GGML_ASSERT(check == -n_tokens);
  1227. }
  1228. else {
  1229. result.resize(n_tokens);
  1230. }
  1231. return std::string(result.data(), result.size());
  1232. }
  1233. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1234. ggml_backend_buffer_type_t buft = nullptr;
  1235. #if defined(GGML_USE_CUBLAS)
  1236. // host buffers should only be used when data is expected to be copied to/from the GPU
  1237. if (host_buffer) {
  1238. buft = ggml_backend_cuda_host_buffer_type();
  1239. }
  1240. #elif defined(GGML_USE_SYCL)
  1241. buft = ggml_backend_sycl_host_buffer_type();
  1242. #elif defined(GGML_USE_CPU_HBM)
  1243. buft = ggml_backend_cpu_hbm_buffer_type();
  1244. #elif defined(GGML_USE_VULKAN)
  1245. if (host_buffer) {
  1246. buft = ggml_backend_vk_host_buffer_type();
  1247. }
  1248. #endif
  1249. if (buft == nullptr) {
  1250. buft = ggml_backend_cpu_buffer_type();
  1251. }
  1252. return buft;
  1253. GGML_UNUSED(host_buffer);
  1254. }
  1255. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(int gpu) {
  1256. ggml_backend_buffer_type_t buft = nullptr;
  1257. #ifdef GGML_USE_METAL
  1258. buft = ggml_backend_metal_buffer_type();
  1259. #elif defined(GGML_USE_CUBLAS)
  1260. buft = ggml_backend_cuda_buffer_type(gpu);
  1261. #elif defined(GGML_USE_VULKAN)
  1262. buft = ggml_backend_vk_buffer_type(gpu);
  1263. #elif defined(GGML_USE_SYCL)
  1264. buft = ggml_backend_sycl_buffer_type(gpu);
  1265. #elif defined(GGML_USE_CLBLAST)
  1266. buft = ggml_backend_opencl_buffer_type();
  1267. #elif defined(GGML_USE_KOMPUTE)
  1268. buft = ggml_backend_kompute_buffer_type(gpu);
  1269. if (buft == nullptr) {
  1270. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, gpu);
  1271. }
  1272. #endif
  1273. if (buft == nullptr) {
  1274. buft = llama_default_buffer_type_cpu(true);
  1275. }
  1276. return buft;
  1277. GGML_UNUSED(gpu);
  1278. }
  1279. static ggml_backend_buffer_type_t llama_default_buffer_type_split(int fallback_gpu, const float * tensor_split) {
  1280. ggml_backend_buffer_type_t buft = nullptr;
  1281. #ifdef GGML_USE_CUBLAS
  1282. if (ggml_backend_cuda_get_device_count() > 1) {
  1283. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  1284. }
  1285. #endif
  1286. if (buft == nullptr) {
  1287. buft = llama_default_buffer_type_offload(fallback_gpu);
  1288. }
  1289. return buft;
  1290. GGML_UNUSED(tensor_split);
  1291. }
  1292. static size_t llama_get_device_count() {
  1293. #if defined(GGML_USE_CUBLAS)
  1294. return ggml_backend_cuda_get_device_count();
  1295. #elif defined(GGML_USE_VULKAN)
  1296. return ggml_backend_vk_get_device_count();
  1297. #else
  1298. return 1;
  1299. #endif
  1300. }
  1301. static size_t llama_get_device_memory(int device) {
  1302. #if defined(GGML_USE_CUBLAS)
  1303. size_t total;
  1304. size_t free;
  1305. ggml_backend_cuda_get_device_memory(device, &total, &free);
  1306. return free;
  1307. #elif defined(GGML_USE_VULKAN)
  1308. size_t total;
  1309. size_t free;
  1310. ggml_backend_vk_get_device_memory(device, &total, &free);
  1311. return free;
  1312. #else
  1313. return 1;
  1314. GGML_UNUSED(device);
  1315. #endif
  1316. }
  1317. //
  1318. // globals
  1319. //
  1320. struct llama_state {
  1321. llama_state() {
  1322. #ifdef GGML_USE_METAL
  1323. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1324. #endif
  1325. }
  1326. // We save the log callback globally
  1327. ggml_log_callback log_callback = llama_log_callback_default;
  1328. void * log_callback_user_data = nullptr;
  1329. };
  1330. static llama_state g_state;
  1331. // available llama models
  1332. enum e_model {
  1333. MODEL_UNKNOWN,
  1334. MODEL_17M,
  1335. MODEL_22M,
  1336. MODEL_33M,
  1337. MODEL_109M,
  1338. MODEL_335M,
  1339. MODEL_0_5B,
  1340. MODEL_1B,
  1341. MODEL_2B,
  1342. MODEL_3B,
  1343. MODEL_4B,
  1344. MODEL_7B,
  1345. MODEL_8B,
  1346. MODEL_13B,
  1347. MODEL_14B,
  1348. MODEL_15B,
  1349. MODEL_20B,
  1350. MODEL_30B,
  1351. MODEL_34B,
  1352. MODEL_40B,
  1353. MODEL_65B,
  1354. MODEL_70B,
  1355. MODEL_SMALL,
  1356. MODEL_MEDIUM,
  1357. MODEL_LARGE,
  1358. MODEL_XL,
  1359. };
  1360. static const size_t kiB = 1024;
  1361. static const size_t MiB = 1024*kiB;
  1362. static const size_t GiB = 1024*MiB;
  1363. struct llama_hparams {
  1364. bool vocab_only;
  1365. bool rope_finetuned;
  1366. uint32_t n_vocab;
  1367. uint32_t n_ctx_train; // context size the model was trained on
  1368. uint32_t n_embd;
  1369. uint32_t n_head;
  1370. uint32_t n_head_kv;
  1371. uint32_t n_layer;
  1372. uint32_t n_rot;
  1373. 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
  1374. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1375. uint32_t n_ff;
  1376. uint32_t n_expert = 0;
  1377. uint32_t n_expert_used = 0;
  1378. uint32_t n_vocab_type = 0; // for BERT-style token types
  1379. float f_norm_eps;
  1380. float f_norm_rms_eps;
  1381. float rope_freq_base_train;
  1382. float rope_freq_scale_train;
  1383. uint32_t n_yarn_orig_ctx;
  1384. int32_t rope_scaling_type_train;
  1385. float f_clamp_kqv;
  1386. float f_max_alibi_bias;
  1387. bool causal_attn = true;
  1388. bool operator!=(const llama_hparams & other) const {
  1389. if (this->vocab_only != other.vocab_only) return true;
  1390. if (this->n_vocab != other.n_vocab) return true;
  1391. if (this->n_ctx_train != other.n_ctx_train) return true;
  1392. if (this->n_embd != other.n_embd) return true;
  1393. if (this->n_head != other.n_head) return true;
  1394. if (this->n_head_kv != other.n_head_kv) return true;
  1395. if (this->n_layer != other.n_layer) return true;
  1396. if (this->n_rot != other.n_rot) return true;
  1397. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1398. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1399. if (this->n_ff != other.n_ff) return true;
  1400. if (this->n_expert != other.n_expert) return true;
  1401. if (this->n_expert_used != other.n_expert_used) return true;
  1402. if (this->rope_finetuned != other.rope_finetuned) return true;
  1403. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1404. const float EPSILON = 1e-9f;
  1405. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1406. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1407. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1408. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1409. return false;
  1410. }
  1411. uint32_t n_gqa() const {
  1412. return n_head/n_head_kv;
  1413. }
  1414. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1415. return n_embd_head_k * n_head_kv;
  1416. }
  1417. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1418. return n_embd_head_v * n_head_kv;
  1419. }
  1420. };
  1421. struct llama_cparams {
  1422. uint32_t n_ctx; // context size used during inference
  1423. uint32_t n_batch;
  1424. uint32_t n_threads; // number of threads to use for generation
  1425. uint32_t n_threads_batch; // number of threads to use for batch processing
  1426. float rope_freq_base;
  1427. float rope_freq_scale;
  1428. uint32_t n_yarn_orig_ctx;
  1429. // These hyperparameters are not exposed in GGUF, because all
  1430. // existing YaRN models use the same values for them.
  1431. float yarn_ext_factor;
  1432. float yarn_attn_factor;
  1433. float yarn_beta_fast;
  1434. float yarn_beta_slow;
  1435. bool mul_mat_q;
  1436. bool offload_kqv;
  1437. ggml_backend_sched_eval_callback cb_eval;
  1438. void * cb_eval_user_data;
  1439. };
  1440. struct llama_layer {
  1441. // normalization
  1442. struct ggml_tensor * attn_norm;
  1443. struct ggml_tensor * attn_norm_b;
  1444. struct ggml_tensor * attn_norm_2;
  1445. struct ggml_tensor * attn_norm_2_b;
  1446. struct ggml_tensor * attn_q_norm;
  1447. struct ggml_tensor * attn_q_norm_b;
  1448. struct ggml_tensor * attn_k_norm;
  1449. struct ggml_tensor * attn_k_norm_b;
  1450. // attention
  1451. struct ggml_tensor * wq;
  1452. struct ggml_tensor * wk;
  1453. struct ggml_tensor * wv;
  1454. struct ggml_tensor * wo;
  1455. struct ggml_tensor * wqkv;
  1456. // attention bias
  1457. struct ggml_tensor * bq;
  1458. struct ggml_tensor * bk;
  1459. struct ggml_tensor * bv;
  1460. struct ggml_tensor * bo;
  1461. struct ggml_tensor * bqkv;
  1462. // normalization
  1463. struct ggml_tensor * ffn_norm;
  1464. struct ggml_tensor * ffn_norm_b;
  1465. // ff
  1466. struct ggml_tensor * ffn_gate; // w1
  1467. struct ggml_tensor * ffn_down; // w2
  1468. struct ggml_tensor * ffn_up; // w3
  1469. // ff MoE
  1470. struct ggml_tensor * ffn_gate_inp;
  1471. struct ggml_tensor * ffn_gate_exp[LLAMA_MAX_EXPERTS];
  1472. struct ggml_tensor * ffn_down_exp[LLAMA_MAX_EXPERTS];
  1473. struct ggml_tensor * ffn_up_exp [LLAMA_MAX_EXPERTS];
  1474. // ff bias
  1475. struct ggml_tensor * ffn_down_b; // b2
  1476. struct ggml_tensor * ffn_up_b; // b3
  1477. struct ggml_tensor * ffn_act;
  1478. };
  1479. struct llama_kv_cell {
  1480. llama_pos pos = -1;
  1481. llama_pos delta = 0;
  1482. std::set<llama_seq_id> seq_id;
  1483. bool has_seq_id(const llama_seq_id & id) const {
  1484. return seq_id.find(id) != seq_id.end();
  1485. }
  1486. };
  1487. // ring-buffer of cached KV data
  1488. struct llama_kv_cache {
  1489. bool has_shift = false;
  1490. // Note: The value of head isn't only used to optimize searching
  1491. // for a free KV slot. llama_decode_internal also uses it, so it
  1492. // cannot be freely changed after a slot has been allocated.
  1493. uint32_t head = 0;
  1494. uint32_t size = 0;
  1495. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1496. // computed before each graph build
  1497. uint32_t n = 0;
  1498. std::vector<llama_kv_cell> cells;
  1499. std::vector<struct ggml_tensor *> k_l; // per layer
  1500. std::vector<struct ggml_tensor *> v_l;
  1501. std::vector<struct ggml_context *> ctxs;
  1502. std::vector<ggml_backend_buffer_t> bufs;
  1503. size_t total_size() const {
  1504. size_t size = 0;
  1505. for (ggml_backend_buffer_t buf : bufs) {
  1506. size += ggml_backend_buffer_get_size(buf);
  1507. }
  1508. return size;
  1509. }
  1510. ~llama_kv_cache() {
  1511. for (struct ggml_context * ctx : ctxs) {
  1512. ggml_free(ctx);
  1513. }
  1514. for (ggml_backend_buffer_t buf : bufs) {
  1515. ggml_backend_buffer_free(buf);
  1516. }
  1517. }
  1518. };
  1519. struct llama_vocab {
  1520. using id = int32_t;
  1521. using token = std::string;
  1522. using ttype = llama_token_type;
  1523. struct token_data {
  1524. token text;
  1525. float score;
  1526. ttype type;
  1527. };
  1528. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1529. std::unordered_map<token, id> token_to_id;
  1530. std::vector<token_data> id_to_token;
  1531. std::unordered_map<token, id> special_tokens_cache;
  1532. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1533. // default LLaMA special tokens
  1534. id special_bos_id = 1;
  1535. id special_eos_id = 2;
  1536. id special_unk_id = 0;
  1537. id special_sep_id = -1;
  1538. id special_pad_id = -1;
  1539. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1540. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1541. id linefeed_id = 13;
  1542. id special_prefix_id = 32007;
  1543. id special_middle_id = 32009;
  1544. id special_suffix_id = 32008;
  1545. id special_eot_id = 32010;
  1546. bool add_space_prefix = true;
  1547. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1548. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1549. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1550. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1551. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1552. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1553. if (it == bpe_ranks.end()) {
  1554. return -1;
  1555. }
  1556. return it->second;
  1557. }
  1558. };
  1559. struct llama_model {
  1560. e_model type = MODEL_UNKNOWN;
  1561. llm_arch arch = LLM_ARCH_UNKNOWN;
  1562. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1563. std::string name = "n/a";
  1564. llama_hparams hparams = {};
  1565. llama_vocab vocab;
  1566. struct ggml_tensor * tok_embd;
  1567. struct ggml_tensor * type_embd;
  1568. struct ggml_tensor * pos_embd;
  1569. struct ggml_tensor * tok_norm;
  1570. struct ggml_tensor * tok_norm_b;
  1571. struct ggml_tensor * output_norm;
  1572. struct ggml_tensor * output_norm_b;
  1573. struct ggml_tensor * output;
  1574. struct ggml_tensor * output_b;
  1575. std::vector<llama_layer> layers;
  1576. llama_split_mode split_mode;
  1577. int main_gpu;
  1578. int n_gpu_layers;
  1579. // gguf metadata
  1580. std::unordered_map<std::string, std::string> gguf_kv;
  1581. // layer -> buffer type mapping
  1582. struct layer_buft {
  1583. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1584. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1585. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1586. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1587. ggml_backend_buffer_type_t buft; // everything else
  1588. };
  1589. layer_buft buft_input;
  1590. layer_buft buft_output;
  1591. std::vector<layer_buft> buft_layer;
  1592. // contexts where the model tensors metadata is stored
  1593. std::vector<struct ggml_context *> ctxs;
  1594. // the model memory buffers for the tensor data
  1595. std::vector<ggml_backend_buffer_t> bufs;
  1596. // model memory mapped file
  1597. std::unique_ptr<llama_mmap> mapping;
  1598. // objects representing data potentially being locked in memory
  1599. std::vector<std::unique_ptr<llama_mlock>> mlock_bufs;
  1600. llama_mlock mlock_mmap;
  1601. // for quantize-stats only
  1602. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1603. int64_t t_load_us = 0;
  1604. int64_t t_start_us = 0;
  1605. ~llama_model() {
  1606. for (struct ggml_context * ctx : ctxs) {
  1607. ggml_free(ctx);
  1608. }
  1609. for (ggml_backend_buffer_t buf : bufs) {
  1610. ggml_backend_buffer_free(buf);
  1611. }
  1612. }
  1613. };
  1614. struct llama_context {
  1615. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1616. ~llama_context() {
  1617. ggml_backend_sched_free(sched);
  1618. for (ggml_backend_t backend : backends) {
  1619. ggml_backend_free(backend);
  1620. }
  1621. #ifdef GGML_USE_VULKAN
  1622. ggml_vk_free_cpu_assist();
  1623. #endif
  1624. ggml_backend_buffer_free(buf_input);
  1625. ggml_free(ctx_input);
  1626. }
  1627. llama_cparams cparams;
  1628. std::vector<ggml_backend_t> backends;
  1629. #ifdef GGML_USE_METAL
  1630. ggml_backend_t backend_metal = nullptr;
  1631. #endif
  1632. ggml_backend_t backend_cpu = nullptr;
  1633. const llama_model & model;
  1634. // key + value cache for the self attention
  1635. struct llama_kv_cache kv_self;
  1636. std::mt19937 rng;
  1637. bool has_evaluated_once = false;
  1638. int64_t t_start_us;
  1639. int64_t t_load_us;
  1640. int64_t t_sample_us = 0;
  1641. int64_t t_p_eval_us = 0;
  1642. int64_t t_eval_us = 0;
  1643. int32_t n_sample = 0; // number of tokens sampled
  1644. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1645. int32_t n_eval = 0; // number of eval calls
  1646. // decode output (2-dimensional array: [n_tokens][n_vocab])
  1647. std::vector<float> logits;
  1648. #ifndef NDEBUG
  1649. // guard against access to unset logits
  1650. std::vector<bool> logits_valid;
  1651. #endif
  1652. bool logits_all = false;
  1653. // input embedding (1-dimensional array: [n_embd])
  1654. std::vector<float> embedding;
  1655. // memory buffers used to evaluate the model
  1656. std::vector<uint8_t> buf_compute_meta;
  1657. ggml_backend_sched_t sched = nullptr;
  1658. // input tensors
  1659. ggml_backend_buffer_t buf_input = nullptr;
  1660. ggml_context * ctx_input = nullptr;
  1661. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  1662. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  1663. struct ggml_tensor * inp_pos; // I32 [n_batch]
  1664. struct ggml_tensor * inp_KQ_mask; // F32 [n_ctx, n_batch]
  1665. struct ggml_tensor * inp_K_shift; // I32 [n_ctx]
  1666. struct ggml_tensor * inp_sum; // F32 [1, n_batch]
  1667. #ifdef GGML_USE_MPI
  1668. ggml_mpi_context * ctx_mpi = NULL;
  1669. #endif
  1670. };
  1671. //
  1672. // kv cache helpers
  1673. //
  1674. static bool llama_kv_cache_init(
  1675. struct llama_kv_cache & cache,
  1676. const llama_model & model,
  1677. ggml_type ktype,
  1678. ggml_type vtype,
  1679. uint32_t n_ctx,
  1680. bool offload) {
  1681. const struct llama_hparams & hparams = model.hparams;
  1682. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  1683. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  1684. const int64_t n_layer = hparams.n_layer;
  1685. cache.has_shift = false;
  1686. cache.head = 0;
  1687. cache.size = n_ctx;
  1688. cache.used = 0;
  1689. cache.cells.clear();
  1690. cache.cells.resize(n_ctx);
  1691. #ifdef GGML_USE_CLBLAST
  1692. offload = false;
  1693. #endif
  1694. // count used buffer types
  1695. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  1696. if (offload) {
  1697. for (int64_t i = 0; i < n_layer; ++i) {
  1698. buft_layer_count[model.buft_layer[i].buft]++;
  1699. }
  1700. } else {
  1701. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  1702. }
  1703. // create a context for each buffer type
  1704. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  1705. for (auto & it : buft_layer_count) {
  1706. int n_layers = it.second;
  1707. struct ggml_init_params params = {
  1708. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  1709. /*.mem_buffer =*/ NULL,
  1710. /*.no_alloc =*/ true,
  1711. };
  1712. ggml_context * ctx = ggml_init(params);
  1713. if (!ctx) {
  1714. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  1715. return false;
  1716. }
  1717. ctx_map[it.first] = ctx;
  1718. cache.ctxs.push_back(ctx);
  1719. }
  1720. cache.k_l.reserve(n_layer);
  1721. cache.v_l.reserve(n_layer);
  1722. for (int i = 0; i < (int) n_layer; i++) {
  1723. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  1724. ggml_tensor * k = ggml_new_tensor_1d(ctx, ktype, n_embd_k_gqa*n_ctx);
  1725. ggml_tensor * v = ggml_new_tensor_1d(ctx, vtype, n_embd_v_gqa*n_ctx);
  1726. ggml_format_name(k, "cache_k_l%d", i);
  1727. ggml_format_name(v, "cache_v_l%d", i);
  1728. cache.k_l.push_back(k);
  1729. cache.v_l.push_back(v);
  1730. }
  1731. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  1732. for (auto it : ctx_map) {
  1733. ggml_backend_buffer_type_t buft = it.first;
  1734. ggml_context * ctx = it.second;
  1735. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  1736. if (!buf) {
  1737. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  1738. return false;
  1739. }
  1740. ggml_backend_buffer_clear(buf, 0);
  1741. 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);
  1742. cache.bufs.push_back(buf);
  1743. }
  1744. return true;
  1745. }
  1746. // find an empty slot of size "n_tokens" in the cache
  1747. // updates the cache head
  1748. // Note: On success, it's important that cache.head points
  1749. // to the first cell of the slot.
  1750. static bool llama_kv_cache_find_slot(
  1751. struct llama_kv_cache & cache,
  1752. const struct llama_batch & batch) {
  1753. const uint32_t n_ctx = cache.size;
  1754. const uint32_t n_tokens = batch.n_tokens;
  1755. if (n_tokens > n_ctx) {
  1756. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  1757. return false;
  1758. }
  1759. uint32_t n_tested = 0;
  1760. while (true) {
  1761. if (cache.head + n_tokens > n_ctx) {
  1762. n_tested += n_ctx - cache.head;
  1763. cache.head = 0;
  1764. continue;
  1765. }
  1766. bool found = true;
  1767. for (uint32_t i = 0; i < n_tokens; i++) {
  1768. if (cache.cells[cache.head + i].pos >= 0) {
  1769. found = false;
  1770. cache.head += i + 1;
  1771. n_tested += i + 1;
  1772. break;
  1773. }
  1774. }
  1775. if (found) {
  1776. break;
  1777. }
  1778. if (n_tested >= n_ctx) {
  1779. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  1780. return false;
  1781. }
  1782. }
  1783. for (uint32_t i = 0; i < n_tokens; i++) {
  1784. cache.cells[cache.head + i].pos = batch.pos[i];
  1785. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  1786. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  1787. }
  1788. }
  1789. cache.used += n_tokens;
  1790. return true;
  1791. }
  1792. // find how many cells are currently in use
  1793. static int32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  1794. for (uint32_t i = cache.size - 1; i > 0; --i) {
  1795. if (cache.cells[i].pos >= 0 && !cache.cells[i].seq_id.empty()) {
  1796. return i + 1;
  1797. }
  1798. }
  1799. return 0;
  1800. }
  1801. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  1802. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  1803. cache.cells[i].pos = -1;
  1804. cache.cells[i].seq_id.clear();
  1805. }
  1806. cache.head = 0;
  1807. cache.used = 0;
  1808. }
  1809. static void llama_kv_cache_seq_rm(
  1810. struct llama_kv_cache & cache,
  1811. llama_seq_id seq_id,
  1812. llama_pos p0,
  1813. llama_pos p1) {
  1814. uint32_t new_head = cache.size;
  1815. if (p0 < 0) p0 = 0;
  1816. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1817. for (uint32_t i = 0; i < cache.size; ++i) {
  1818. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1819. if (seq_id < 0) {
  1820. cache.cells[i].seq_id.clear();
  1821. } else if (cache.cells[i].has_seq_id(seq_id)) {
  1822. cache.cells[i].seq_id.erase(seq_id);
  1823. } else {
  1824. continue;
  1825. }
  1826. if (cache.cells[i].seq_id.empty()) {
  1827. // keep count of the number of used cells
  1828. if (cache.cells[i].pos >= 0) cache.used--;
  1829. cache.cells[i].pos = -1;
  1830. if (new_head == cache.size) new_head = i;
  1831. }
  1832. }
  1833. }
  1834. // If we freed up a slot, set head to it so searching can start there.
  1835. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1836. }
  1837. static void llama_kv_cache_seq_cp(
  1838. struct llama_kv_cache & cache,
  1839. llama_seq_id seq_id_src,
  1840. llama_seq_id seq_id_dst,
  1841. llama_pos p0,
  1842. llama_pos p1) {
  1843. if (p0 < 0) p0 = 0;
  1844. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1845. cache.head = 0;
  1846. for (uint32_t i = 0; i < cache.size; ++i) {
  1847. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1848. cache.cells[i].seq_id.insert(seq_id_dst);
  1849. }
  1850. }
  1851. }
  1852. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  1853. uint32_t new_head = cache.size;
  1854. for (uint32_t i = 0; i < cache.size; ++i) {
  1855. if (!cache.cells[i].has_seq_id(seq_id)) {
  1856. if (cache.cells[i].pos >= 0) cache.used--;
  1857. cache.cells[i].pos = -1;
  1858. cache.cells[i].seq_id.clear();
  1859. if (new_head == cache.size) new_head = i;
  1860. } else {
  1861. cache.cells[i].seq_id.clear();
  1862. cache.cells[i].seq_id.insert(seq_id);
  1863. }
  1864. }
  1865. // If we freed up a slot, set head to it so searching can start there.
  1866. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1867. }
  1868. static void llama_kv_cache_seq_shift(
  1869. struct llama_kv_cache & cache,
  1870. llama_seq_id seq_id,
  1871. llama_pos p0,
  1872. llama_pos p1,
  1873. llama_pos delta) {
  1874. uint32_t new_head = cache.size;
  1875. if (p0 < 0) p0 = 0;
  1876. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1877. for (uint32_t i = 0; i < cache.size; ++i) {
  1878. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1879. cache.has_shift = true;
  1880. cache.cells[i].pos += delta;
  1881. cache.cells[i].delta += delta;
  1882. if (cache.cells[i].pos < 0) {
  1883. if (!cache.cells[i].seq_id.empty()) cache.used--;
  1884. cache.cells[i].pos = -1;
  1885. cache.cells[i].seq_id.clear();
  1886. if (new_head == cache.size) new_head = i;
  1887. }
  1888. }
  1889. }
  1890. // If we freed up a slot, set head to it so searching can start there.
  1891. // Otherwise we just start the next search from the beginning.
  1892. cache.head = new_head != cache.size ? new_head : 0;
  1893. }
  1894. static void llama_kv_cache_seq_div(
  1895. struct llama_kv_cache & cache,
  1896. llama_seq_id seq_id,
  1897. llama_pos p0,
  1898. llama_pos p1,
  1899. int d) {
  1900. if (p0 < 0) p0 = 0;
  1901. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1902. for (uint32_t i = 0; i < cache.size; ++i) {
  1903. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1904. cache.has_shift = true;
  1905. {
  1906. llama_pos p_old = cache.cells[i].pos;
  1907. cache.cells[i].pos /= d;
  1908. cache.cells[i].delta += cache.cells[i].pos - p_old;
  1909. }
  1910. }
  1911. }
  1912. }
  1913. //
  1914. // model loading and saving
  1915. //
  1916. enum llama_fver {
  1917. GGUF_FILE_VERSION_V1 = 1,
  1918. GGUF_FILE_VERSION_V2 = 2,
  1919. GGUF_FILE_VERSION_V3 = 3,
  1920. };
  1921. static const char * llama_file_version_name(llama_fver version) {
  1922. switch (version) {
  1923. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  1924. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  1925. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  1926. }
  1927. return "unknown";
  1928. }
  1929. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  1930. char buf[256];
  1931. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  1932. for (size_t i = 1; i < ne.size(); i++) {
  1933. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  1934. }
  1935. return buf;
  1936. }
  1937. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  1938. char buf[256];
  1939. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  1940. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  1941. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  1942. }
  1943. return buf;
  1944. }
  1945. namespace GGUFMeta {
  1946. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  1947. struct GKV_Base_Type {
  1948. static constexpr gguf_type gt = gt_;
  1949. static T getter(const gguf_context * ctx, const int kid) {
  1950. return gfun(ctx, kid);
  1951. }
  1952. };
  1953. template<typename T> struct GKV_Base;
  1954. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  1955. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  1956. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  1957. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  1958. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  1959. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  1960. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  1961. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  1962. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  1963. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  1964. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  1965. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  1966. template<> struct GKV_Base<std::string> {
  1967. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  1968. static std::string getter(const gguf_context * ctx, const int kid) {
  1969. return gguf_get_val_str(ctx, kid);
  1970. }
  1971. };
  1972. struct ArrayInfo{
  1973. const gguf_type gt;
  1974. const size_t length;
  1975. const void * data;
  1976. };
  1977. template<> struct GKV_Base<ArrayInfo> {
  1978. public:
  1979. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  1980. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  1981. return ArrayInfo {
  1982. gguf_get_arr_type(ctx, k),
  1983. size_t(gguf_get_arr_n(ctx, k)),
  1984. gguf_get_arr_data(ctx, k),
  1985. };
  1986. }
  1987. };
  1988. template<typename T>
  1989. class GKV: public GKV_Base<T> {
  1990. GKV() = delete;
  1991. public:
  1992. static T get_kv(const gguf_context * ctx, const int k) {
  1993. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  1994. if (kt != GKV::gt) {
  1995. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  1996. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  1997. }
  1998. return GKV::getter(ctx, k);
  1999. }
  2000. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  2001. switch (ty) {
  2002. case LLAMA_KV_OVERRIDE_BOOL: return "bool";
  2003. case LLAMA_KV_OVERRIDE_INT: return "int";
  2004. case LLAMA_KV_OVERRIDE_FLOAT: return "float";
  2005. }
  2006. return "unknown";
  2007. }
  2008. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override *override) {
  2009. if (!override) { return false; }
  2010. if (override->tag == expected_type) {
  2011. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  2012. __func__, override_type_to_str(override->tag), override->key);
  2013. switch (override->tag) {
  2014. case LLAMA_KV_OVERRIDE_BOOL: {
  2015. LLAMA_LOG_INFO("%s\n", override->bool_value ? "true" : "false");
  2016. } break;
  2017. case LLAMA_KV_OVERRIDE_INT: {
  2018. LLAMA_LOG_INFO("%" PRId64 "\n", override->int_value);
  2019. } break;
  2020. case LLAMA_KV_OVERRIDE_FLOAT: {
  2021. LLAMA_LOG_INFO("%.6f\n", override->float_value);
  2022. } break;
  2023. default:
  2024. // Shouldn't be possible to end up here, but just in case...
  2025. throw std::runtime_error(
  2026. format("Unsupported attempt to override %s type for metadata key %s\n",
  2027. override_type_to_str(override->tag), override->key));
  2028. }
  2029. return true;
  2030. }
  2031. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  2032. __func__, override->key, override_type_to_str(expected_type), override_type_to_str(override->tag));
  2033. return false;
  2034. }
  2035. template<typename OT>
  2036. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  2037. try_override(OT & target, const struct llama_model_kv_override *override) {
  2038. if (validate_override(LLAMA_KV_OVERRIDE_BOOL, override)) {
  2039. target = override->bool_value;
  2040. return true;
  2041. }
  2042. return false;
  2043. }
  2044. template<typename OT>
  2045. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  2046. try_override(OT & target, const struct llama_model_kv_override *override) {
  2047. if (validate_override(LLAMA_KV_OVERRIDE_INT, override)) {
  2048. target = override->int_value;
  2049. return true;
  2050. }
  2051. return false;
  2052. }
  2053. template<typename OT>
  2054. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  2055. try_override(T & target, const struct llama_model_kv_override *override) {
  2056. if (validate_override(LLAMA_KV_OVERRIDE_FLOAT, override)) {
  2057. target = override->float_value;
  2058. return true;
  2059. }
  2060. return false;
  2061. }
  2062. template<typename OT>
  2063. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  2064. try_override(T & target, const struct llama_model_kv_override *override) {
  2065. (void)target;
  2066. (void)override;
  2067. if (!override) { return false; }
  2068. // Currently, we should never end up here so it would be a bug if we do.
  2069. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  2070. override ? override->key : "NULL"));
  2071. }
  2072. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override *override = nullptr) {
  2073. if (try_override<T>(target, override)) {
  2074. return true;
  2075. }
  2076. if (k < 0) { return false; }
  2077. target = get_kv(ctx, k);
  2078. return true;
  2079. }
  2080. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override *override = nullptr) {
  2081. return set(ctx, gguf_find_key(ctx, key), target, override);
  2082. }
  2083. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override *override = nullptr) {
  2084. return set(ctx, key.c_str(), target, override);
  2085. }
  2086. };
  2087. }
  2088. struct llama_model_loader {
  2089. int n_kv = 0;
  2090. int n_tensors = 0;
  2091. int n_created = 0;
  2092. int64_t n_elements = 0;
  2093. size_t n_bytes = 0;
  2094. bool use_mmap = false;
  2095. llama_file file;
  2096. llama_ftype ftype;
  2097. llama_fver fver;
  2098. std::unique_ptr<llama_mmap> mapping;
  2099. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  2100. struct gguf_context * ctx_gguf = NULL;
  2101. struct ggml_context * ctx_meta = NULL;
  2102. std::string arch_name;
  2103. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  2104. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) : file(fname.c_str(), "rb") {
  2105. int trace = 0;
  2106. if (getenv("LLAMA_TRACE")) {
  2107. trace = atoi(getenv("LLAMA_TRACE"));
  2108. }
  2109. struct gguf_init_params params = {
  2110. /*.no_alloc = */ true,
  2111. /*.ctx = */ &ctx_meta,
  2112. };
  2113. if (param_overrides_p != nullptr) {
  2114. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  2115. kv_overrides.insert({std::string(p->key), *p});
  2116. }
  2117. }
  2118. ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  2119. if (!ctx_gguf) {
  2120. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  2121. }
  2122. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  2123. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  2124. n_kv = gguf_get_n_kv(ctx_gguf);
  2125. n_tensors = gguf_get_n_tensors(ctx_gguf);
  2126. fver = (enum llama_fver ) gguf_get_version(ctx_gguf);
  2127. for (int i = 0; i < n_tensors; i++) {
  2128. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  2129. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, name);
  2130. n_elements += ggml_nelements(t);
  2131. n_bytes += ggml_nbytes(t);
  2132. }
  2133. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  2134. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  2135. // determine file type based on the number of tensors for each quantization and print meta data
  2136. // TODO: make optional
  2137. {
  2138. std::map<enum ggml_type, uint32_t> n_type;
  2139. uint32_t n_type_max = 0;
  2140. enum ggml_type type_max = GGML_TYPE_F32;
  2141. for (int i = 0; i < n_tensors; i++) {
  2142. enum ggml_type type = gguf_get_tensor_type(ctx_gguf, i);
  2143. n_type[type]++;
  2144. if (n_type_max < n_type[type]) {
  2145. n_type_max = n_type[type];
  2146. type_max = type;
  2147. }
  2148. if (trace > 0) {
  2149. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2150. 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());
  2151. }
  2152. }
  2153. switch (type_max) {
  2154. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  2155. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  2156. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  2157. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  2158. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  2159. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  2160. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  2161. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  2162. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  2163. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  2164. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  2165. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  2166. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  2167. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  2168. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  2169. default:
  2170. {
  2171. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  2172. ftype = LLAMA_FTYPE_ALL_F32;
  2173. } break;
  2174. }
  2175. // this is a way to mark that we have "guessed" the file type
  2176. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  2177. {
  2178. const int kid = gguf_find_key(ctx_gguf, "general.file_type");
  2179. if (kid >= 0) {
  2180. ftype = (llama_ftype) gguf_get_val_u32(ctx_gguf, kid);
  2181. }
  2182. }
  2183. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2184. for (int i = 0; i < n_kv; i++) {
  2185. const char * name = gguf_get_key(ctx_gguf, i);
  2186. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  2187. const std::string type_name =
  2188. type == GGUF_TYPE_ARRAY
  2189. ? 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))
  2190. : gguf_type_name(type);
  2191. std::string value = gguf_kv_to_str(ctx_gguf, i);
  2192. const size_t MAX_VALUE_LEN = 40;
  2193. if (value.size() > MAX_VALUE_LEN) {
  2194. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2195. }
  2196. replace_all(value, "\n", "\\n");
  2197. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2198. }
  2199. // print type counts
  2200. for (auto & kv : n_type) {
  2201. if (kv.second == 0) {
  2202. continue;
  2203. }
  2204. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2205. }
  2206. }
  2207. if (!llama_mmap::SUPPORTED) {
  2208. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2209. use_mmap = false;
  2210. }
  2211. this->use_mmap = use_mmap;
  2212. }
  2213. ~llama_model_loader() {
  2214. if (ctx_gguf) {
  2215. gguf_free(ctx_gguf);
  2216. }
  2217. if (ctx_meta) {
  2218. ggml_free(ctx_meta);
  2219. }
  2220. }
  2221. template<typename T>
  2222. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2223. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2224. const int kid = gguf_find_key(ctx_gguf, key.c_str());
  2225. if (kid < 0) {
  2226. if (required) {
  2227. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2228. }
  2229. return false;
  2230. }
  2231. struct GGUFMeta::ArrayInfo arr_info =
  2232. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(ctx_gguf, kid);
  2233. result = arr_info.length;
  2234. return true;
  2235. }
  2236. template<typename T>
  2237. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2238. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2239. return get_arr_n(llm_kv(kid), result, required);
  2240. }
  2241. template<typename T>
  2242. bool get_key(const std::string & key, T & result, const bool required = true) {
  2243. auto it = kv_overrides.find(key);
  2244. const struct llama_model_kv_override * override =
  2245. it != kv_overrides.end() ? &it->second : nullptr;
  2246. const bool found = GGUFMeta::GKV<T>::set(ctx_gguf, key, result, override);
  2247. if (required && !found) {
  2248. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2249. }
  2250. return found;
  2251. }
  2252. template<typename T>
  2253. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2254. return get_key(llm_kv(kid), result, required);
  2255. }
  2256. std::string get_arch_name() const {
  2257. return arch_name;
  2258. }
  2259. enum llm_arch get_arch() const {
  2260. return llm_kv.arch;
  2261. }
  2262. const char * get_tensor_name(int i) const {
  2263. return gguf_get_tensor_name(ctx_gguf, i);
  2264. }
  2265. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2266. return ggml_get_tensor(ctx_meta, name);
  2267. }
  2268. struct ggml_tensor * get_tensor_meta(int i) const {
  2269. return get_tensor_meta(get_tensor_name(i));
  2270. }
  2271. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, struct ggml_tensor * meta) {
  2272. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
  2273. ggml_set_name(tensor, ggml_get_name(meta));
  2274. n_created++;
  2275. return tensor;
  2276. }
  2277. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  2278. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, name.c_str());
  2279. if (cur == NULL) {
  2280. if (!required) {
  2281. return NULL;
  2282. }
  2283. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2284. }
  2285. {
  2286. bool is_ok = true;
  2287. for (size_t i = 0; i < ne.size(); ++i) {
  2288. if (ne[i] != cur->ne[i]) {
  2289. is_ok = false;
  2290. break;
  2291. }
  2292. }
  2293. if (!is_ok) {
  2294. throw std::runtime_error(
  2295. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2296. __func__, name.c_str(),
  2297. llama_format_tensor_shape(ne).c_str(),
  2298. llama_format_tensor_shape(cur).c_str()));
  2299. }
  2300. }
  2301. return create_tensor_for(ctx, cur);
  2302. }
  2303. void done_getting_tensors() const {
  2304. if (n_created != n_tensors) {
  2305. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  2306. }
  2307. }
  2308. size_t file_offset(const char * name) const {
  2309. const int idx = gguf_find_tensor(ctx_gguf, name);
  2310. if (idx < 0) {
  2311. throw std::runtime_error(format("%s: tensor '%s' not found in the file", __func__, name));
  2312. }
  2313. return gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, idx);
  2314. }
  2315. void init_mapping(bool prefetch = true, llama_mlock * lmlock = nullptr) {
  2316. // prefetch the whole file - all the data is needed anyway
  2317. if (use_mmap) {
  2318. mapping.reset(new llama_mmap(&file, prefetch ? -1 : 0, ggml_is_numa()));
  2319. }
  2320. // compute the total size of all tensors for progress reporting
  2321. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2322. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2323. size_data += ggml_nbytes(cur);
  2324. }
  2325. if (use_mmap && mapping) {
  2326. if (lmlock) {
  2327. lmlock->init(mapping->addr);
  2328. }
  2329. mmap_used_first = mapping->size;
  2330. }
  2331. }
  2332. void get_mapping_range(size_t * first, size_t * last, ggml_context * ctx) const {
  2333. GGML_ASSERT(mapping);
  2334. *first = mapping->size;
  2335. *last = 0;
  2336. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  2337. const size_t offs = file_offset(ggml_get_name(tensor));
  2338. *first = std::min(*first, offs);
  2339. *last = std::max(*last, offs + ggml_nbytes(tensor));
  2340. }
  2341. }
  2342. // for backwards compatibility, does not support ggml-backend
  2343. void load_data_for(struct ggml_tensor * cur) const {
  2344. const size_t offs = file_offset(ggml_get_name(cur));
  2345. if (use_mmap && mapping) {
  2346. if (cur->data == nullptr) {
  2347. cur->data = (uint8_t *)mapping->addr + offs;
  2348. } else {
  2349. memcpy(cur->data, (uint8_t *)mapping->addr + offs, ggml_nbytes(cur));
  2350. }
  2351. } else {
  2352. GGML_ASSERT(cur->data != nullptr);
  2353. file.seek(offs, SEEK_SET);
  2354. file.read_raw(cur->data, ggml_nbytes(cur));
  2355. }
  2356. }
  2357. size_t size_done = 0;
  2358. size_t size_data = 0;
  2359. size_t mmap_used_first = -1;
  2360. size_t mmap_used_last = 0;
  2361. // Returns false if cancelled by progress_callback
  2362. 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) {
  2363. GGML_ASSERT(size_data != 0 && "call init_mapping() first");
  2364. std::vector<no_init<uint8_t>> read_buf;
  2365. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2366. struct ggml_tensor * cur = ggml_get_tensor(ctx, gguf_get_tensor_name(ctx_gguf, i));
  2367. if (!cur) {
  2368. // some tensors may be allocated in a different context
  2369. continue;
  2370. }
  2371. if (progress_callback) {
  2372. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2373. return false;
  2374. }
  2375. }
  2376. const size_t offs = file_offset(ggml_get_name(cur));
  2377. if (use_mmap && mapping) {
  2378. if (buf_mmap && cur->data == nullptr) {
  2379. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + offs);
  2380. if (lmlock) {
  2381. lmlock->grow_to(offs + ggml_nbytes(cur));
  2382. }
  2383. mmap_used_first = std::min(mmap_used_first, offs);
  2384. mmap_used_last = std::max(mmap_used_last, offs + ggml_nbytes(cur));
  2385. } else {
  2386. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + offs, 0, ggml_nbytes(cur));
  2387. }
  2388. } else {
  2389. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2390. file.seek(offs, SEEK_SET);
  2391. file.read_raw(cur->data, ggml_nbytes(cur));
  2392. } else {
  2393. read_buf.resize(ggml_nbytes(cur));
  2394. file.seek(offs, SEEK_SET);
  2395. file.read_raw(read_buf.data(), ggml_nbytes(cur));
  2396. ggml_backend_tensor_set(cur, read_buf.data(), 0, ggml_nbytes(cur));
  2397. }
  2398. }
  2399. size_done += ggml_nbytes(cur);
  2400. }
  2401. // check if this is the last call and do final cleanup
  2402. if (size_done >= size_data) {
  2403. // unmap offloaded tensors and metadata
  2404. if (use_mmap && mapping) {
  2405. mapping->unmap_fragment(0, mmap_used_first);
  2406. if (mmap_used_last != 0) {
  2407. mapping->unmap_fragment(mmap_used_last, mapping->size);
  2408. }
  2409. }
  2410. if (progress_callback) {
  2411. // Even though the model is done loading, we still honor
  2412. // cancellation since we need to free allocations.
  2413. return progress_callback(1.0f, progress_callback_user_data);
  2414. }
  2415. }
  2416. return true;
  2417. }
  2418. };
  2419. //
  2420. // load LLaMA models
  2421. //
  2422. static const char * llama_model_arch_name(llm_arch arch) {
  2423. auto it = LLM_ARCH_NAMES.find(arch);
  2424. if (it == LLM_ARCH_NAMES.end()) {
  2425. return "unknown";
  2426. }
  2427. return it->second;
  2428. }
  2429. static std::string llama_model_ftype_name(llama_ftype ftype) {
  2430. if (ftype & LLAMA_FTYPE_GUESSED) {
  2431. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  2432. }
  2433. switch (ftype) {
  2434. case LLAMA_FTYPE_ALL_F32: return "all F32";
  2435. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  2436. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  2437. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  2438. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  2439. return "Q4_1, some F16";
  2440. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  2441. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  2442. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  2443. // K-quants
  2444. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  2445. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  2446. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  2447. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  2448. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  2449. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  2450. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  2451. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  2452. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  2453. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  2454. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XXS - 2.0625 bpw";
  2455. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  2456. case LLAMA_FTYPE_MOSTLY_Q3_K_XS:return "Q3_K - Extra small";
  2457. case LLAMA_FTYPE_MOSTLY_IQ3_XXS:return "IQ3_XXS - 3.0625 bpw";
  2458. default: return "unknown, may not work";
  2459. }
  2460. }
  2461. static const char * llama_model_type_name(e_model type) {
  2462. switch (type) {
  2463. case MODEL_1B: return "1B";
  2464. case MODEL_2B: return "2B";
  2465. case MODEL_3B: return "3B";
  2466. case MODEL_7B: return "7B";
  2467. case MODEL_8B: return "8B";
  2468. case MODEL_13B: return "13B";
  2469. case MODEL_14B: return "14B";
  2470. case MODEL_15B: return "15B";
  2471. case MODEL_20B: return "20B";
  2472. case MODEL_30B: return "30B";
  2473. case MODEL_34B: return "34B";
  2474. case MODEL_40B: return "40B";
  2475. case MODEL_65B: return "65B";
  2476. case MODEL_70B: return "70B";
  2477. case MODEL_SMALL: return "0.1B";
  2478. case MODEL_MEDIUM: return "0.4B";
  2479. case MODEL_LARGE: return "0.8B";
  2480. case MODEL_XL: return "1.5B";
  2481. default: return "?B";
  2482. }
  2483. }
  2484. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  2485. switch (type) {
  2486. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  2487. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  2488. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  2489. default: return "unknown";
  2490. }
  2491. }
  2492. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  2493. model.arch = ml.get_arch();
  2494. if (model.arch == LLM_ARCH_UNKNOWN) {
  2495. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  2496. }
  2497. }
  2498. static void llm_load_hparams(
  2499. llama_model_loader & ml,
  2500. llama_model & model) {
  2501. auto & hparams = model.hparams;
  2502. const gguf_context * ctx = ml.ctx_gguf;
  2503. // get metadata as string
  2504. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  2505. enum gguf_type type = gguf_get_kv_type(ctx, i);
  2506. if (type == GGUF_TYPE_ARRAY) {
  2507. continue;
  2508. }
  2509. const char * name = gguf_get_key(ctx, i);
  2510. const std::string value = gguf_kv_to_str(ctx, i);
  2511. model.gguf_kv.emplace(name, value);
  2512. }
  2513. // get general kv
  2514. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  2515. // get hparams kv
  2516. ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  2517. ml.get_key (LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  2518. ml.get_key (LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  2519. ml.get_key (LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  2520. ml.get_key (LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  2521. ml.get_key (LLM_KV_BLOCK_COUNT, hparams.n_layer);
  2522. ml.get_key (LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  2523. ml.get_key (LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  2524. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  2525. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  2526. if (hparams.n_expert > 0) {
  2527. GGML_ASSERT(hparams.n_expert_used > 0);
  2528. } else {
  2529. GGML_ASSERT(hparams.n_expert_used == 0);
  2530. }
  2531. // n_head_kv is optional, default to n_head
  2532. hparams.n_head_kv = hparams.n_head;
  2533. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  2534. bool rope_finetuned = false;
  2535. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  2536. hparams.rope_finetuned = rope_finetuned;
  2537. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  2538. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  2539. // rope_freq_base (optional)
  2540. hparams.rope_freq_base_train = 10000.0f;
  2541. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  2542. std::string rope_scaling("linear");
  2543. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  2544. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  2545. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_UNSPECIFIED);
  2546. // rope_freq_scale (inverse of the kv) is optional
  2547. float ropescale = 0.0f;
  2548. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  2549. // try the old key name
  2550. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  2551. }
  2552. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  2553. // sanity check for n_rot (optional)
  2554. {
  2555. hparams.n_rot = hparams.n_embd / hparams.n_head;
  2556. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  2557. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  2558. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  2559. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  2560. }
  2561. }
  2562. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  2563. // gpt-j n_rot = rotary_dim
  2564. }
  2565. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head;
  2566. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  2567. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head;
  2568. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  2569. // arch-specific KVs
  2570. switch (model.arch) {
  2571. case LLM_ARCH_LLAMA:
  2572. {
  2573. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2574. switch (hparams.n_layer) {
  2575. case 22: model.type = e_model::MODEL_1B; break;
  2576. case 26: model.type = e_model::MODEL_3B; break;
  2577. case 32: model.type = e_model::MODEL_7B; break;
  2578. case 40: model.type = e_model::MODEL_13B; break;
  2579. case 48: model.type = e_model::MODEL_34B; break;
  2580. case 60: model.type = e_model::MODEL_30B; break;
  2581. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  2582. default: model.type = e_model::MODEL_UNKNOWN;
  2583. }
  2584. } break;
  2585. case LLM_ARCH_MINICPM:
  2586. {
  2587. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2588. switch (hparams.n_layer) {
  2589. case 40: model.type = e_model::MODEL_2B; break;
  2590. default: model.type = e_model::MODEL_UNKNOWN;
  2591. }
  2592. } break;
  2593. case LLM_ARCH_FALCON:
  2594. {
  2595. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2596. switch (hparams.n_layer) {
  2597. case 32: model.type = e_model::MODEL_7B; break;
  2598. case 60: model.type = e_model::MODEL_40B; break;
  2599. default: model.type = e_model::MODEL_UNKNOWN;
  2600. }
  2601. } break;
  2602. case LLM_ARCH_BAICHUAN:
  2603. {
  2604. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2605. switch (hparams.n_layer) {
  2606. case 32: model.type = e_model::MODEL_7B; break;
  2607. case 40: model.type = e_model::MODEL_13B; break;
  2608. default: model.type = e_model::MODEL_UNKNOWN;
  2609. }
  2610. } break;
  2611. case LLM_ARCH_STARCODER:
  2612. {
  2613. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2614. switch (hparams.n_layer) {
  2615. case 24: model.type = e_model::MODEL_1B; break;
  2616. case 36: model.type = e_model::MODEL_3B; break;
  2617. case 42: model.type = e_model::MODEL_7B; break;
  2618. case 40: model.type = e_model::MODEL_15B; break;
  2619. default: model.type = e_model::MODEL_UNKNOWN;
  2620. }
  2621. } break;
  2622. case LLM_ARCH_PERSIMMON:
  2623. {
  2624. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2625. switch (hparams.n_layer) {
  2626. case 36: model.type = e_model::MODEL_8B; break;
  2627. default: model.type = e_model::MODEL_UNKNOWN;
  2628. }
  2629. } break;
  2630. case LLM_ARCH_REFACT:
  2631. {
  2632. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2633. switch (hparams.n_layer) {
  2634. case 32: model.type = e_model::MODEL_1B; break;
  2635. default: model.type = e_model::MODEL_UNKNOWN;
  2636. }
  2637. } break;
  2638. case LLM_ARCH_BERT:
  2639. {
  2640. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2641. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  2642. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  2643. switch (hparams.n_layer) {
  2644. case 3:
  2645. model.type = e_model::MODEL_17M; break; // bge-micro
  2646. case 6:
  2647. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  2648. case 12:
  2649. switch (hparams.n_embd) {
  2650. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  2651. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  2652. } break;
  2653. case 24:
  2654. model.type = e_model::MODEL_335M; break; // bge-large
  2655. }
  2656. } break;
  2657. case LLM_ARCH_BLOOM:
  2658. {
  2659. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2660. switch (hparams.n_layer) {
  2661. case 24: model.type = e_model::MODEL_1B; break;
  2662. case 30:
  2663. switch (hparams.n_embd) {
  2664. case 2560: model.type = e_model::MODEL_3B; break;
  2665. case 4096: model.type = e_model::MODEL_7B; break;
  2666. } break;
  2667. }
  2668. } break;
  2669. case LLM_ARCH_MPT:
  2670. {
  2671. hparams.f_clamp_kqv = 0.0f;
  2672. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2673. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  2674. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  2675. switch (hparams.n_layer) {
  2676. case 32: model.type = e_model::MODEL_7B; break;
  2677. case 48: model.type = e_model::MODEL_30B; break;
  2678. default: model.type = e_model::MODEL_UNKNOWN;
  2679. }
  2680. } break;
  2681. case LLM_ARCH_STABLELM:
  2682. {
  2683. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2684. switch (hparams.n_layer) {
  2685. case 24: model.type = e_model::MODEL_1B; break;
  2686. case 32: model.type = e_model::MODEL_3B; break;
  2687. default: model.type = e_model::MODEL_UNKNOWN;
  2688. }
  2689. } break;
  2690. case LLM_ARCH_QWEN:
  2691. {
  2692. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2693. switch (hparams.n_layer) {
  2694. case 32: model.type = e_model::MODEL_7B; break;
  2695. case 40: model.type = e_model::MODEL_13B; break;
  2696. default: model.type = e_model::MODEL_UNKNOWN;
  2697. }
  2698. } break;
  2699. case LLM_ARCH_QWEN2:
  2700. {
  2701. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2702. switch (hparams.n_layer) {
  2703. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  2704. case 32: model.type = e_model::MODEL_7B; break;
  2705. case 40: model.type = hparams.n_head == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  2706. case 80: model.type = e_model::MODEL_70B; break;
  2707. default: model.type = e_model::MODEL_UNKNOWN;
  2708. }
  2709. } break;
  2710. case LLM_ARCH_PHI2:
  2711. {
  2712. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2713. switch (hparams.n_layer) {
  2714. case 24: model.type = e_model::MODEL_1B; break;
  2715. case 32: model.type = e_model::MODEL_3B; break;
  2716. default: model.type = e_model::MODEL_UNKNOWN;
  2717. }
  2718. } break;
  2719. case LLM_ARCH_PLAMO:
  2720. {
  2721. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2722. switch (hparams.n_layer) {
  2723. case 40: model.type = e_model::MODEL_13B; break;
  2724. default: model.type = e_model::MODEL_UNKNOWN;
  2725. }
  2726. } break;
  2727. case LLM_ARCH_GPT2:
  2728. {
  2729. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2730. switch (hparams.n_layer) {
  2731. case 12: model.type = e_model::MODEL_SMALL; break;
  2732. case 24: model.type = e_model::MODEL_MEDIUM; break;
  2733. case 36: model.type = e_model::MODEL_LARGE; break;
  2734. case 48: model.type = e_model::MODEL_XL; break;
  2735. default: model.type = e_model::MODEL_UNKNOWN;
  2736. }
  2737. } break;
  2738. case LLM_ARCH_CODESHELL:
  2739. {
  2740. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2741. switch (hparams.n_layer) {
  2742. case 42: model.type = e_model::MODEL_SMALL; break;
  2743. default: model.type = e_model::MODEL_UNKNOWN;
  2744. }
  2745. } break;
  2746. case LLM_ARCH_ORION:
  2747. {
  2748. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2749. switch (hparams.n_layer) {
  2750. case 40: model.type = e_model::MODEL_14B; break;
  2751. default: model.type = e_model::MODEL_UNKNOWN;
  2752. }
  2753. } break;
  2754. case LLM_ARCH_INTERNLM2:
  2755. {
  2756. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2757. switch (hparams.n_layer) {
  2758. case 32: model.type = e_model::MODEL_7B; break;
  2759. case 48: model.type = e_model::MODEL_20B; break;
  2760. default: model.type = e_model::MODEL_UNKNOWN;
  2761. }
  2762. } break;
  2763. default: (void)0;
  2764. }
  2765. model.ftype = ml.ftype;
  2766. }
  2767. // TODO: This should probably be in llama.h
  2768. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  2769. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  2770. static void llm_load_vocab(
  2771. llama_model_loader & ml,
  2772. llama_model & model) {
  2773. auto & vocab = model.vocab;
  2774. struct gguf_context * ctx = ml.ctx_gguf;
  2775. const auto kv = LLM_KV(model.arch);
  2776. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  2777. if (token_idx == -1) {
  2778. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  2779. }
  2780. const float * scores = nullptr;
  2781. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  2782. if (score_idx != -1) {
  2783. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  2784. }
  2785. const int * toktypes = nullptr;
  2786. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  2787. if (toktype_idx != -1) {
  2788. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  2789. }
  2790. // determine vocab type
  2791. {
  2792. std::string tokenizer_name;
  2793. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  2794. if (tokenizer_name == "llama") {
  2795. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2796. // default special tokens
  2797. vocab.special_bos_id = 1;
  2798. vocab.special_eos_id = 2;
  2799. vocab.special_unk_id = 0;
  2800. vocab.special_sep_id = -1;
  2801. vocab.special_pad_id = -1;
  2802. const int add_space_prefix_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_ADD_PREFIX).c_str());
  2803. if (add_space_prefix_keyidx != -1) {
  2804. vocab.add_space_prefix = gguf_get_val_bool(ctx, add_space_prefix_keyidx);
  2805. } // The default value of add_space_prefix is true.
  2806. } else if (tokenizer_name == "gpt2") {
  2807. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  2808. // read bpe merges and populate bpe ranks
  2809. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  2810. if (merges_keyidx == -1) {
  2811. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  2812. }
  2813. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  2814. for (int i = 0; i < n_merges; i++) {
  2815. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  2816. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2817. std::string first;
  2818. std::string second;
  2819. const size_t pos = word.find(' ', 1);
  2820. if (pos != std::string::npos) {
  2821. first = word.substr(0, pos);
  2822. second = word.substr(pos + 1);
  2823. }
  2824. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  2825. }
  2826. // default special tokens
  2827. vocab.special_bos_id = 11;
  2828. vocab.special_eos_id = 11;
  2829. vocab.special_unk_id = -1;
  2830. vocab.special_sep_id = -1;
  2831. vocab.special_pad_id = -1;
  2832. } else if (tokenizer_name == "bert") {
  2833. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  2834. // default special tokens
  2835. vocab.special_bos_id = 101;
  2836. vocab.special_eos_id = 102;
  2837. vocab.special_unk_id = 100;
  2838. vocab.special_sep_id = -1;
  2839. vocab.special_pad_id = -1;
  2840. vocab.add_space_prefix = false;
  2841. } else {
  2842. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  2843. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  2844. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2845. }
  2846. }
  2847. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  2848. vocab.id_to_token.resize(n_vocab);
  2849. for (uint32_t i = 0; i < n_vocab; i++) {
  2850. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  2851. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2852. vocab.token_to_id[word] = i;
  2853. auto & token_data = vocab.id_to_token[i];
  2854. token_data.text = std::move(word);
  2855. token_data.score = scores ? scores[i] : 0.0f;
  2856. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  2857. }
  2858. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  2859. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  2860. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  2861. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  2862. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  2863. vocab.linefeed_id = vocab.special_pad_id;
  2864. } else {
  2865. const std::vector<int> ids = llama_tokenize_internal(vocab, "\u010A", false);
  2866. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  2867. vocab.linefeed_id = ids[0];
  2868. }
  2869. // special tokens
  2870. {
  2871. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  2872. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  2873. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  2874. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  2875. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  2876. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  2877. };
  2878. for (const auto & it : special_token_types) {
  2879. const std::string & key = kv(std::get<0>(it));
  2880. int32_t & id = std::get<1>(it);
  2881. uint32_t new_id;
  2882. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  2883. continue;
  2884. }
  2885. if (new_id >= vocab.id_to_token.size()) {
  2886. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  2887. __func__, key.c_str(), new_id, id);
  2888. } else {
  2889. id = new_id;
  2890. }
  2891. }
  2892. // Handle add_bos_token and add_eos_token
  2893. {
  2894. bool temp = true;
  2895. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  2896. vocab.special_add_bos = int(temp);
  2897. }
  2898. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  2899. vocab.special_add_eos = int(temp);
  2900. }
  2901. }
  2902. }
  2903. // build special tokens cache
  2904. {
  2905. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  2906. // and will always be correctly labeled in 'added_tokens.json' etc.
  2907. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  2908. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  2909. // are special tokens.
  2910. // From testing, this appears to correlate 1:1 with special tokens.
  2911. //
  2912. // Counting special tokens and verifying in only one direction
  2913. // is sufficient to detect difference in those two sets.
  2914. //
  2915. uint32_t special_tokens_count_by_type = 0;
  2916. uint32_t special_tokens_count_from_verification = 0;
  2917. bool special_tokens_definition_mismatch = false;
  2918. for (const auto & t : vocab.token_to_id) {
  2919. const auto & token = t.first;
  2920. const auto & id = t.second;
  2921. // Count all non-normal tokens in the vocab while iterating
  2922. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  2923. special_tokens_count_by_type++;
  2924. }
  2925. // Skip single character tokens
  2926. if (token.length() > 1) {
  2927. bool is_tokenizable = false;
  2928. // Split token string representation in two, in all possible ways
  2929. // and check if both halves can be matched to a valid token
  2930. for (unsigned i = 1; i < token.length();) {
  2931. const auto left = token.substr(0, i);
  2932. const auto right = token.substr(i);
  2933. // check if we didnt partition in the middle of a utf sequence
  2934. auto utf = utf8_len(left.at(left.length() - 1));
  2935. if (utf == 1) {
  2936. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  2937. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  2938. is_tokenizable = true;
  2939. break;
  2940. }
  2941. i++;
  2942. } else {
  2943. // skip over the rest of multibyte utf sequence
  2944. i += utf - 1;
  2945. }
  2946. }
  2947. if (!is_tokenizable) {
  2948. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  2949. // it's faster to re-filter them here, since there are way less candidates now
  2950. // Calculate a total "utf" length of a token string representation
  2951. size_t utf8_str_len = 0;
  2952. for (unsigned i = 0; i < token.length();) {
  2953. utf8_str_len++;
  2954. i += utf8_len(token.at(i));
  2955. }
  2956. // And skip the ones which are one character
  2957. if (utf8_str_len > 1) {
  2958. // At this point what we have left are special tokens only
  2959. vocab.special_tokens_cache[token] = id;
  2960. // Count manually found special tokens
  2961. special_tokens_count_from_verification++;
  2962. // If this manually found special token is not marked as such, flag a mismatch
  2963. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  2964. special_tokens_definition_mismatch = true;
  2965. }
  2966. }
  2967. }
  2968. }
  2969. }
  2970. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  2971. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  2972. __func__,
  2973. special_tokens_count_from_verification, vocab.id_to_token.size(),
  2974. special_tokens_count_by_type, vocab.id_to_token.size()
  2975. );
  2976. } else {
  2977. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  2978. __func__,
  2979. special_tokens_count_from_verification, vocab.id_to_token.size()
  2980. );
  2981. }
  2982. }
  2983. }
  2984. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  2985. const auto & hparams = model.hparams;
  2986. const auto & vocab = model.vocab;
  2987. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  2988. // hparams
  2989. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  2990. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  2991. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  2992. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  2993. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  2994. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  2995. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  2996. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  2997. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  2998. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  2999. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  3000. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  3001. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  3002. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  3003. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  3004. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  3005. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  3006. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  3007. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  3008. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  3009. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  3010. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  3011. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  3012. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  3013. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  3014. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  3015. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  3016. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  3017. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  3018. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  3019. if (ml.n_elements >= 1e12) {
  3020. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  3021. } else if (ml.n_elements >= 1e9) {
  3022. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  3023. } else if (ml.n_elements >= 1e6) {
  3024. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  3025. } else {
  3026. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  3027. }
  3028. if (ml.n_bytes < GiB) {
  3029. 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);
  3030. } else {
  3031. 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);
  3032. }
  3033. // general kv
  3034. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  3035. // special tokens
  3036. 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() ); }
  3037. 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() ); }
  3038. 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() ); }
  3039. 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() ); }
  3040. 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() ); }
  3041. 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() ); }
  3042. }
  3043. // Returns false if cancelled by progress_callback
  3044. static bool llm_load_tensors(
  3045. llama_model_loader & ml,
  3046. llama_model & model,
  3047. int n_gpu_layers,
  3048. enum llama_split_mode split_mode,
  3049. int main_gpu,
  3050. const float * tensor_split,
  3051. bool use_mlock,
  3052. llama_progress_callback progress_callback,
  3053. void * progress_callback_user_data) {
  3054. model.t_start_us = ggml_time_us();
  3055. auto & hparams = model.hparams;
  3056. model.split_mode = split_mode;
  3057. model.main_gpu = main_gpu;
  3058. model.n_gpu_layers = n_gpu_layers;
  3059. const int64_t n_layer = hparams.n_layer;
  3060. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  3061. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  3062. model.buft_input = llama_default_buffer_type_cpu(true);
  3063. model.buft_layer.resize(n_layer);
  3064. // assign cpu layers
  3065. for (int64_t i = 0; i < i_gpu_start; ++i) {
  3066. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  3067. }
  3068. if (split_mode == LLAMA_SPLIT_LAYER) {
  3069. // calculate the split points
  3070. int device_count = llama_get_device_count();
  3071. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  3072. std::vector<float> splits(device_count);
  3073. if (all_zero) {
  3074. // default split, by free memory
  3075. for (int i = 0; i < device_count; ++i) {
  3076. splits[i] = llama_get_device_memory(i);
  3077. }
  3078. } else {
  3079. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  3080. }
  3081. // sum and normalize the splits to get the split points
  3082. float split_sum = 0.0f;
  3083. for (int i = 0; i < device_count; ++i) {
  3084. split_sum += splits[i];
  3085. splits[i] = split_sum;
  3086. }
  3087. for (int i = 0; i < device_count; ++i) {
  3088. splits[i] /= split_sum;
  3089. }
  3090. // assign the repeating layers to the devices according to the splits
  3091. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  3092. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3093. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  3094. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  3095. }
  3096. // assign the output layer
  3097. if (n_gpu_layers > n_layer) {
  3098. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  3099. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  3100. } else {
  3101. model.buft_output = llama_default_buffer_type_cpu(true);
  3102. }
  3103. } else {
  3104. ggml_backend_buffer_type_t split_buft;
  3105. if (split_mode == LLAMA_SPLIT_ROW) {
  3106. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  3107. } else {
  3108. // LLAMA_SPLIT_NONE or LLAMA_SPLIT_LAYER in backends where it is not supported
  3109. split_buft = llama_default_buffer_type_offload(main_gpu);
  3110. }
  3111. // assign the repeating layers
  3112. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3113. model.buft_layer[i] = {
  3114. split_buft,
  3115. llama_default_buffer_type_offload(main_gpu)
  3116. };
  3117. }
  3118. // assign the output layer
  3119. if (n_gpu_layers > n_layer) {
  3120. model.buft_output = {
  3121. split_buft,
  3122. llama_default_buffer_type_offload(main_gpu)
  3123. };
  3124. } else {
  3125. model.buft_output = llama_default_buffer_type_cpu(true);
  3126. }
  3127. }
  3128. // count used buffer types
  3129. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  3130. buft_layer_count[model.buft_input.buft]++;
  3131. buft_layer_count[model.buft_input.buft_matrix]++;
  3132. buft_layer_count[model.buft_output.buft]++;
  3133. buft_layer_count[model.buft_output.buft_matrix]++;
  3134. for (int64_t i = 0; i < n_layer; ++i) {
  3135. buft_layer_count[model.buft_layer[i].buft]++;
  3136. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  3137. }
  3138. // create one context per buffer type
  3139. size_t ctx_size = ggml_tensor_overhead()*ml.n_tensors;
  3140. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3141. for (auto & it : buft_layer_count) {
  3142. struct ggml_init_params params = {
  3143. /*.mem_size =*/ ctx_size,
  3144. /*.mem_buffer =*/ NULL,
  3145. /*.no_alloc =*/ true,
  3146. };
  3147. ggml_context * ctx = ggml_init(params);
  3148. if (!ctx) {
  3149. throw std::runtime_error(format("failed to create context"));
  3150. }
  3151. ctx_map[it.first] = ctx;
  3152. model.ctxs.push_back(ctx);
  3153. }
  3154. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  3155. // create tensors for the weights
  3156. {
  3157. const int64_t n_embd = hparams.n_embd;
  3158. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3159. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3160. const int64_t n_embd_gqa = n_embd_v_gqa;
  3161. const int64_t n_vocab = hparams.n_vocab;
  3162. const int64_t n_vocab_type = hparams.n_vocab_type;
  3163. const int64_t n_ff = hparams.n_ff;
  3164. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  3165. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  3166. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  3167. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  3168. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  3169. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  3170. model.layers.resize(n_layer);
  3171. const auto tn = LLM_TN(model.arch);
  3172. switch (model.arch) {
  3173. case LLM_ARCH_LLAMA:
  3174. case LLM_ARCH_REFACT:
  3175. case LLM_ARCH_MINICPM:
  3176. {
  3177. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3178. // output
  3179. {
  3180. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3181. if (model.arch != LLM_ARCH_MINICPM){
  3182. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3183. }
  3184. }
  3185. for (int i = 0; i < n_layer; ++i) {
  3186. ggml_context * ctx_layer = ctx_for_layer(i);
  3187. ggml_context * ctx_split = ctx_for_layer_split(i);
  3188. auto & layer = model.layers[i];
  3189. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3190. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3191. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3192. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3193. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3194. // optional bias tensors
  3195. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3196. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3197. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3198. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3199. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3200. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd}, false);
  3201. if (layer.ffn_gate_inp == nullptr) {
  3202. GGML_ASSERT(hparams.n_expert == 0);
  3203. GGML_ASSERT(hparams.n_expert_used == 0);
  3204. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3205. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3206. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3207. } else {
  3208. GGML_ASSERT(hparams.n_expert > 0);
  3209. GGML_ASSERT(hparams.n_expert_used > 0);
  3210. // MoE branch
  3211. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  3212. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  3213. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  3214. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  3215. }
  3216. }
  3217. }
  3218. } break;
  3219. case LLM_ARCH_BAICHUAN:
  3220. {
  3221. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3222. {
  3223. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3224. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3225. }
  3226. for (int i = 0; i < n_layer; ++i) {
  3227. ggml_context * ctx_layer = ctx_for_layer(i);
  3228. ggml_context * ctx_split = ctx_for_layer_split(i);
  3229. auto & layer = model.layers[i];
  3230. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3231. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3232. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3233. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3234. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3235. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3236. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3237. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3238. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3239. }
  3240. } break;
  3241. case LLM_ARCH_FALCON:
  3242. {
  3243. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3244. // output
  3245. {
  3246. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3247. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3248. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_OUTPUT, "weight").c_str()) >= 0) {
  3249. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3250. } else {
  3251. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  3252. ml.n_created--; // artificial tensor
  3253. }
  3254. }
  3255. for (int i = 0; i < n_layer; ++i) {
  3256. ggml_context * ctx_layer = ctx_for_layer(i);
  3257. ggml_context * ctx_split = ctx_for_layer_split(i);
  3258. auto & layer = model.layers[i];
  3259. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3260. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3261. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i).c_str()) >= 0) {
  3262. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd});
  3263. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd});
  3264. }
  3265. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3266. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3267. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3268. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3269. }
  3270. } break;
  3271. case LLM_ARCH_STARCODER:
  3272. {
  3273. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3274. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3275. // output
  3276. {
  3277. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3278. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3279. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3280. }
  3281. for (int i = 0; i < n_layer; ++i) {
  3282. ggml_context * ctx_layer = ctx_for_layer(i);
  3283. ggml_context * ctx_split = ctx_for_layer_split(i);
  3284. auto & layer = model.layers[i];
  3285. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3286. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3287. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3288. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3289. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3290. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3291. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3292. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3293. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3294. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3295. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3296. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3297. }
  3298. } break;
  3299. case LLM_ARCH_PERSIMMON:
  3300. {
  3301. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3302. {
  3303. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3304. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3305. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3306. }
  3307. for (int i = 0; i < n_layer; ++i) {
  3308. ggml_context * ctx_layer = ctx_for_layer(i);
  3309. ggml_context * ctx_split = ctx_for_layer_split(i);
  3310. auto & layer = model.layers[i];
  3311. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3312. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3313. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3314. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3315. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3316. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3317. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3318. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3319. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3320. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3321. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3322. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3323. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  3324. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  3325. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  3326. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  3327. }
  3328. } break;
  3329. case LLM_ARCH_BERT:
  3330. {
  3331. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3332. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  3333. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3334. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3335. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3336. for (int i = 0; i < n_layer; ++i) {
  3337. ggml_context * ctx_layer = ctx_for_layer(i);
  3338. ggml_context * ctx_split = ctx_for_layer_split(i);
  3339. auto & layer = model.layers[i];
  3340. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3341. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3342. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3343. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3344. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3345. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3346. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3347. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3348. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3349. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3350. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3351. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3352. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3353. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3354. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3355. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3356. }
  3357. } break;
  3358. case LLM_ARCH_BLOOM:
  3359. {
  3360. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3361. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3362. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3363. // output
  3364. {
  3365. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3366. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3367. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3368. }
  3369. for (int i = 0; i < n_layer; ++i) {
  3370. ggml_context * ctx_layer = ctx_for_layer(i);
  3371. ggml_context * ctx_split = ctx_for_layer_split(i);
  3372. auto & layer = model.layers[i];
  3373. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3374. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3375. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3376. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3377. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3378. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3379. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3380. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3381. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3382. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3383. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3384. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3385. }
  3386. } break;
  3387. case LLM_ARCH_MPT:
  3388. {
  3389. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3390. // output
  3391. {
  3392. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3393. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3394. }
  3395. for (int i = 0; i < n_layer; ++i) {
  3396. ggml_context * ctx_layer = ctx_for_layer(i);
  3397. ggml_context * ctx_split = ctx_for_layer_split(i);
  3398. auto & layer = model.layers[i];
  3399. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3400. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3401. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3402. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  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. // AWQ ScaleActivation layer
  3406. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  3407. }
  3408. } break;
  3409. case LLM_ARCH_STABLELM:
  3410. {
  3411. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3412. // output
  3413. {
  3414. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3415. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3416. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3417. }
  3418. for (int i = 0; i < n_layer; ++i) {
  3419. ggml_context * ctx_layer = ctx_for_layer(i);
  3420. ggml_context * ctx_split = ctx_for_layer_split(i);
  3421. auto & layer = model.layers[i];
  3422. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3423. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3424. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3425. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3426. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3427. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3428. // optional bias tensors, present in Stable LM 2 1.6B
  3429. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3430. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3431. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3432. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3433. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", 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_QWEN:
  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 = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3446. }
  3447. for (int i = 0; i < n_layer; ++i) {
  3448. ggml_context * ctx_layer = ctx_for_layer(i);
  3449. ggml_context * ctx_split = ctx_for_layer_split(i);
  3450. auto & layer = model.layers[i];
  3451. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3452. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  3453. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  3454. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3455. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3456. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  3457. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  3458. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  3459. }
  3460. } break;
  3461. case LLM_ARCH_QWEN2:
  3462. {
  3463. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3464. // output
  3465. {
  3466. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3467. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3468. }
  3469. for (int i = 0; i < n_layer; ++i) {
  3470. ggml_context * ctx_layer = ctx_for_layer(i);
  3471. ggml_context * ctx_split = ctx_for_layer_split(i);
  3472. auto & layer = model.layers[i];
  3473. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3474. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3475. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3476. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3477. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3478. // optional bias tensors
  3479. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3480. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3481. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3482. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3483. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3484. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3485. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3486. }
  3487. } break;
  3488. case LLM_ARCH_PHI2:
  3489. {
  3490. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3491. // output
  3492. {
  3493. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3494. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3495. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3496. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  3497. }
  3498. for (int i = 0; i < n_layer; ++i) {
  3499. ggml_context * ctx_layer = ctx_for_layer(i);
  3500. ggml_context * ctx_split = ctx_for_layer_split(i);
  3501. auto & layer = model.layers[i];
  3502. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3503. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3504. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  3505. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3506. if (layer.wqkv == nullptr) {
  3507. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3508. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3509. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3510. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3511. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3512. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3513. }
  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. }
  3521. } break;
  3522. case LLM_ARCH_PLAMO:
  3523. {
  3524. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3525. // output
  3526. {
  3527. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3528. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3529. }
  3530. for (int i = 0; i < n_layer; ++i) {
  3531. ggml_context * ctx_layer = ctx_for_layer(i);
  3532. ggml_context * ctx_split = ctx_for_layer_split(i);
  3533. auto & layer = model.layers[i];
  3534. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3535. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3536. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3537. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3538. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3539. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3540. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3541. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3542. }
  3543. } break;
  3544. case LLM_ARCH_GPT2:
  3545. {
  3546. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3547. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3548. // output
  3549. {
  3550. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3551. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3552. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3553. }
  3554. for (int i = 0; i < n_layer; ++i) {
  3555. ggml_context * ctx_layer = ctx_for_layer(i);
  3556. ggml_context * ctx_split = ctx_for_layer_split(i);
  3557. auto & layer = model.layers[i];
  3558. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3559. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3560. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3561. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3562. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3563. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3564. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3565. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3566. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3567. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3568. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3569. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3570. }
  3571. } break;
  3572. case LLM_ARCH_CODESHELL:
  3573. {
  3574. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3575. // output
  3576. {
  3577. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3578. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3579. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3580. }
  3581. for (int i = 0; i < n_layer; ++i) {
  3582. ggml_context * ctx_layer = ctx_for_layer(i);
  3583. ggml_context * ctx_split = ctx_for_layer_split(i);
  3584. auto & layer = model.layers[i];
  3585. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3586. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3587. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3588. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3589. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3590. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3591. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3592. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3593. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3594. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3595. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3596. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3597. }
  3598. } break;
  3599. case LLM_ARCH_ORION:
  3600. {
  3601. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3602. {
  3603. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3604. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3605. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3606. }
  3607. for (int i = 0; i < n_layer; ++i) {
  3608. ggml_context * ctx_layer = ctx_for_layer(i);
  3609. ggml_context * ctx_split = ctx_for_layer_split(i);
  3610. auto & layer = model.layers[i];
  3611. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3612. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3613. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3614. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3615. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3616. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3617. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3618. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3619. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3620. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3621. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3622. }
  3623. } break;
  3624. case LLM_ARCH_INTERNLM2:
  3625. {
  3626. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3627. // output
  3628. {
  3629. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3630. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3631. }
  3632. for (int i = 0; i < n_layer; ++i) {
  3633. ggml_context * ctx_layer = ctx_for_layer(i);
  3634. ggml_context * ctx_split = ctx_for_layer_split(i);
  3635. auto & layer = model.layers[i];
  3636. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3637. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3638. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3639. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3640. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3641. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3642. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3643. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3644. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3645. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3646. }
  3647. } break;
  3648. default:
  3649. throw std::runtime_error("unknown architecture");
  3650. }
  3651. }
  3652. ml.done_getting_tensors();
  3653. ml.init_mapping(true, use_mlock ? &model.mlock_mmap : nullptr);
  3654. // create the backend buffers
  3655. std::vector<std::pair<ggml_context *, ggml_backend_buffer_t>> ctx_bufs;
  3656. for (auto & it : ctx_map) {
  3657. ggml_backend_buffer_type_t buft = it.first;
  3658. ggml_context * ctx = it.second;
  3659. ggml_backend_buffer_t buf = nullptr;
  3660. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  3661. // 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
  3662. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  3663. if (ml.use_mmap && buft == llama_default_buffer_type_cpu(true)) {
  3664. size_t first, last;
  3665. ml.get_mapping_range(&first, &last, ctx);
  3666. buf = ggml_backend_cpu_buffer_from_ptr((char *) ml.mapping->addr + first, last - first);
  3667. }
  3668. #ifdef GGML_USE_METAL
  3669. else if (ml.use_mmap && buft == ggml_backend_metal_buffer_type()) {
  3670. const size_t max_size = ggml_get_max_tensor_size(ctx);
  3671. size_t first, last;
  3672. ml.get_mapping_range(&first, &last, ctx);
  3673. buf = ggml_backend_metal_buffer_from_ptr((char *) ml.mapping->addr + first, last - first, max_size);
  3674. }
  3675. #endif
  3676. else {
  3677. buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  3678. if (buf != nullptr && use_mlock && ggml_backend_buffer_is_host(buf)) {
  3679. model.mlock_bufs.emplace_back(new llama_mlock);
  3680. auto & mlock_buf = model.mlock_bufs.back();
  3681. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  3682. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  3683. }
  3684. }
  3685. if (buf == nullptr) {
  3686. throw std::runtime_error("failed to allocate buffer");
  3687. }
  3688. // indicate that this buffer contains weights
  3689. // 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
  3690. ggml_backend_buffer_set_usage(buf, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  3691. model.bufs.push_back(buf);
  3692. ctx_bufs.emplace_back(ctx, buf);
  3693. }
  3694. if (llama_supports_gpu_offload()) {
  3695. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  3696. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  3697. if (n_gpu_layers > (int) hparams.n_layer) {
  3698. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  3699. }
  3700. const int max_backend_supported_layers = hparams.n_layer + 1;
  3701. const int max_offloadable_layers = hparams.n_layer + 1;
  3702. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  3703. }
  3704. // print memory requirements
  3705. for (ggml_backend_buffer_t buf : model.bufs) {
  3706. 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);
  3707. }
  3708. // populate tensors_by_name
  3709. for (ggml_context * ctx : model.ctxs) {
  3710. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  3711. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  3712. }
  3713. }
  3714. // load tensor data
  3715. for (auto & it : ctx_bufs) {
  3716. ggml_context * ctx = it.first;
  3717. ggml_backend_buffer_t buf = it.second;
  3718. if (!ml.load_all_data(ctx, progress_callback, progress_callback_user_data, buf, use_mlock ? &model.mlock_mmap : NULL)) {
  3719. return false;
  3720. }
  3721. }
  3722. model.mapping = std::move(ml.mapping);
  3723. // loading time will be recalculate after the first eval, so
  3724. // we take page faults deferred by mmap() into consideration
  3725. model.t_load_us = ggml_time_us() - model.t_start_us;
  3726. return true;
  3727. }
  3728. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  3729. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  3730. try {
  3731. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  3732. model.hparams.vocab_only = params.vocab_only;
  3733. llm_load_arch (ml, model);
  3734. llm_load_hparams(ml, model);
  3735. llm_load_vocab (ml, model);
  3736. llm_load_print_meta(ml, model);
  3737. if (model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  3738. throw std::runtime_error("vocab size mismatch");
  3739. }
  3740. if (params.vocab_only) {
  3741. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  3742. return 0;
  3743. }
  3744. #ifdef GGML_USE_KOMPUTE
  3745. if (params.n_gpu_layers > 0 && (
  3746. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  3747. || !(
  3748. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  3749. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  3750. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  3751. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  3752. )
  3753. )) {
  3754. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  3755. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  3756. params.n_gpu_layers = 0;
  3757. }
  3758. #endif
  3759. if (!llm_load_tensors(
  3760. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  3761. params.progress_callback, params.progress_callback_user_data
  3762. )) {
  3763. return -2;
  3764. }
  3765. } catch (const std::exception & err) {
  3766. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  3767. return -1;
  3768. }
  3769. return 0;
  3770. }
  3771. //
  3772. // llm_build
  3773. //
  3774. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  3775. enum llm_rope_type {
  3776. LLM_ROPE,
  3777. LLM_ROPE_NEOX,
  3778. LLM_ROPE_GLM,
  3779. };
  3780. enum llm_ffn_op_type {
  3781. LLM_FFN_SILU,
  3782. LLM_FFN_GELU,
  3783. LLM_FFN_RELU,
  3784. LLM_FFN_RELU_SQR,
  3785. };
  3786. enum llm_ffn_gate_type {
  3787. LLM_FFN_SEQ,
  3788. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  3789. };
  3790. enum llm_norm_type {
  3791. LLM_NORM,
  3792. LLM_NORM_RMS,
  3793. };
  3794. static struct ggml_tensor * llm_build_inp_embd(
  3795. struct ggml_context * ctx,
  3796. const llama_hparams & hparams,
  3797. const llama_batch & batch,
  3798. struct ggml_tensor * tok_embd,
  3799. struct ggml_tensor * inp_tokens,
  3800. struct ggml_tensor * inp_embd,
  3801. const llm_build_cb & cb) {
  3802. const int64_t n_embd = hparams.n_embd;
  3803. struct ggml_tensor * inpL;
  3804. if (batch.token) {
  3805. struct ggml_tensor * inp_tokens_v = ggml_view_1d(ctx, inp_tokens, batch.n_tokens, 0);
  3806. cb(inp_tokens, "inp_tokens", -1);
  3807. inpL = ggml_get_rows(ctx, tok_embd, inp_tokens_v);
  3808. } else {
  3809. #ifdef GGML_USE_MPI
  3810. GGML_ASSERT(false && "not implemented");
  3811. #endif
  3812. inpL = ggml_view_2d(ctx, inp_embd, n_embd, batch.n_tokens, inp_embd->nb[1], 0);
  3813. }
  3814. return inpL;
  3815. }
  3816. // Persimmon: n_rot = n_embd_head_k/2
  3817. // Other: n_rot = n_embd_head_k
  3818. static void llm_build_k_shift(
  3819. struct ggml_context * ctx,
  3820. const llama_hparams & hparams,
  3821. const llama_cparams & cparams,
  3822. const llama_kv_cache & kv,
  3823. struct ggml_cgraph * graph,
  3824. struct ggml_tensor * K_shift,
  3825. llm_rope_type type,
  3826. int64_t n_ctx,
  3827. float freq_base,
  3828. float freq_scale,
  3829. const llm_build_cb & cb) {
  3830. const int64_t n_layer = hparams.n_layer;
  3831. const int64_t n_head_kv = hparams.n_head_kv;
  3832. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3833. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3834. const int32_t n_rot = hparams.n_rot;
  3835. const int32_t n_orig_ctx = cparams.n_yarn_orig_ctx;
  3836. const float ext_factor = cparams.yarn_ext_factor;
  3837. const float attn_factor = cparams.yarn_attn_factor;
  3838. const float beta_fast = cparams.yarn_beta_fast;
  3839. const float beta_slow = cparams.yarn_beta_slow;
  3840. int rope_type = 0;
  3841. switch (type) {
  3842. case LLM_ROPE: rope_type = 0; break;
  3843. case LLM_ROPE_NEOX: rope_type = 2; break;
  3844. case LLM_ROPE_GLM: rope_type = 4; break;
  3845. }
  3846. for (int il = 0; il < n_layer; ++il) {
  3847. struct ggml_tensor * tmp =
  3848. // we rotate only the first n_rot dimensions
  3849. ggml_rope_custom_inplace(ctx,
  3850. ggml_view_3d(ctx, kv.k_l[il],
  3851. n_embd_head_k, n_head_kv, n_ctx,
  3852. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  3853. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  3854. 0),
  3855. K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  3856. ext_factor, attn_factor, beta_fast, beta_slow);
  3857. cb(tmp, "K_shifted", il);
  3858. ggml_build_forward_expand(graph, tmp);
  3859. }
  3860. }
  3861. static void llm_build_kv_store(
  3862. struct ggml_context * ctx,
  3863. const llama_hparams & hparams,
  3864. const llama_kv_cache & kv,
  3865. struct ggml_cgraph * graph,
  3866. struct ggml_tensor * k_cur,
  3867. struct ggml_tensor * v_cur,
  3868. int64_t n_ctx,
  3869. int32_t n_tokens,
  3870. int32_t kv_head,
  3871. const llm_build_cb & cb,
  3872. int64_t il) {
  3873. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3874. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3875. // compute the transposed [n_tokens, n_embd] V matrix
  3876. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, ggml_reshape_2d(ctx, v_cur, n_embd_v_gqa, n_tokens));
  3877. //struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur); // TODO: reshape above is likely not needed
  3878. cb(v_cur_t, "v_cur_t", il);
  3879. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  3880. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  3881. cb(k_cache_view, "k_cache_view", il);
  3882. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  3883. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  3884. (kv_head)*ggml_element_size(kv.v_l[il]));
  3885. cb(v_cache_view, "v_cache_view", il);
  3886. // important: storing RoPE-ed version of K in the KV cache!
  3887. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  3888. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  3889. }
  3890. static struct ggml_tensor * llm_build_norm(
  3891. struct ggml_context * ctx,
  3892. struct ggml_tensor * cur,
  3893. const llama_hparams & hparams,
  3894. struct ggml_tensor * mw,
  3895. struct ggml_tensor * mb,
  3896. llm_norm_type type,
  3897. const llm_build_cb & cb,
  3898. int il) {
  3899. switch (type) {
  3900. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  3901. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  3902. }
  3903. if (mw || mb) {
  3904. cb(cur, "norm", il);
  3905. }
  3906. if (mw) {
  3907. cur = ggml_mul(ctx, cur, mw);
  3908. if (mb) {
  3909. cb(cur, "norm_w", il);
  3910. }
  3911. }
  3912. if (mb) {
  3913. cur = ggml_add(ctx, cur, mb);
  3914. }
  3915. return cur;
  3916. }
  3917. static struct ggml_tensor * llm_build_ffn(
  3918. struct ggml_context * ctx,
  3919. struct ggml_tensor * cur,
  3920. struct ggml_tensor * up,
  3921. struct ggml_tensor * up_b,
  3922. struct ggml_tensor * gate,
  3923. struct ggml_tensor * gate_b,
  3924. struct ggml_tensor * down,
  3925. struct ggml_tensor * down_b,
  3926. struct ggml_tensor * act_scales,
  3927. llm_ffn_op_type type_op,
  3928. llm_ffn_gate_type type_gate,
  3929. const llm_build_cb & cb,
  3930. int il) {
  3931. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  3932. cb(tmp, "ffn_up", il);
  3933. if (up_b) {
  3934. tmp = ggml_add(ctx, tmp, up_b);
  3935. cb(tmp, "ffn_up_b", il);
  3936. }
  3937. if (gate) {
  3938. switch (type_gate) {
  3939. case LLM_FFN_SEQ:
  3940. {
  3941. cur = ggml_mul_mat(ctx, gate, tmp);
  3942. cb(cur, "ffn_gate", il);
  3943. } break;
  3944. case LLM_FFN_PAR:
  3945. {
  3946. cur = ggml_mul_mat(ctx, gate, cur);
  3947. cb(cur, "ffn_gate", il);
  3948. } break;
  3949. }
  3950. if (gate_b) {
  3951. cur = ggml_add(ctx, cur, gate_b);
  3952. cb(cur, "ffn_gate_b", il);
  3953. }
  3954. } else {
  3955. cur = tmp;
  3956. }
  3957. switch (type_op) {
  3958. case LLM_FFN_SILU:
  3959. {
  3960. cur = ggml_silu(ctx, cur);
  3961. cb(cur, "ffn_silu", il);
  3962. } break;
  3963. case LLM_FFN_GELU:
  3964. {
  3965. cur = ggml_gelu(ctx, cur);
  3966. cb(cur, "ffn_gelu", il);
  3967. if (act_scales != NULL) {
  3968. cur = ggml_div(ctx, cur, act_scales);
  3969. cb(cur, "ffn_act", il);
  3970. }
  3971. } break;
  3972. case LLM_FFN_RELU:
  3973. {
  3974. cur = ggml_relu(ctx, cur);
  3975. cb(cur, "ffn_relu", il);
  3976. } break;
  3977. case LLM_FFN_RELU_SQR:
  3978. {
  3979. cur = ggml_relu(ctx, cur);
  3980. cb(cur, "ffn_relu", il);
  3981. cur = ggml_sqr(ctx, cur);
  3982. cb(cur, "ffn_sqr(relu)", il);
  3983. } break;
  3984. }
  3985. if (type_gate == LLM_FFN_PAR) {
  3986. cur = ggml_mul(ctx, cur, tmp);
  3987. cb(cur, "ffn_gate_par", il);
  3988. }
  3989. cur = ggml_mul_mat(ctx, down, cur);
  3990. if (down_b) {
  3991. cb(cur, "ffn_down", il);
  3992. }
  3993. if (down_b) {
  3994. cur = ggml_add(ctx, cur, down_b);
  3995. }
  3996. return cur;
  3997. }
  3998. // if max_alibi_bias > 0 then apply ALiBi
  3999. static struct ggml_tensor * llm_build_kqv(
  4000. struct ggml_context * ctx,
  4001. const llama_model & model,
  4002. const llama_hparams & hparams,
  4003. const llama_kv_cache & kv,
  4004. struct ggml_cgraph * graph,
  4005. struct ggml_tensor * wo,
  4006. struct ggml_tensor * wo_b,
  4007. struct ggml_tensor * q_cur,
  4008. struct ggml_tensor * kq_mask,
  4009. int64_t n_ctx,
  4010. int32_t n_tokens,
  4011. int32_t n_kv,
  4012. float max_alibi_bias,
  4013. float kq_scale,
  4014. const llm_build_cb & cb,
  4015. int il) {
  4016. const int64_t n_head = hparams.n_head;
  4017. const int64_t n_head_kv = hparams.n_head_kv;
  4018. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  4019. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4020. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  4021. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  4022. cb(q, "q", il);
  4023. struct ggml_tensor * k =
  4024. ggml_view_3d(ctx, kv.k_l[il],
  4025. n_embd_head_k, n_kv, n_head_kv,
  4026. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  4027. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  4028. 0);
  4029. cb(k, "k", il);
  4030. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  4031. cb(kq, "kq", il);
  4032. if (model.arch == LLM_ARCH_PHI2) {
  4033. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  4034. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  4035. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  4036. }
  4037. if (max_alibi_bias > 0.0f) {
  4038. // temporary branch until we figure out how to handle ggml_alibi through ggml_add
  4039. kq = ggml_scale(ctx, kq, kq_scale);
  4040. cb(kq, "kq_scaled", il);
  4041. if (max_alibi_bias > 0.0f) {
  4042. // TODO: n_head or n_head_kv
  4043. // TODO: K-shift is likely not working
  4044. // TODO: change to ggml_add
  4045. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, max_alibi_bias);
  4046. cb(kq, "kq_scaled_alibi", il);
  4047. }
  4048. kq = ggml_add(ctx, kq, kq_mask);
  4049. cb(kq, "kq_masked", il);
  4050. kq = ggml_soft_max(ctx, kq);
  4051. cb(kq, "kq_soft_max", il);
  4052. } else {
  4053. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_scale);
  4054. cb(kq, "kq_soft_max_ext", il);
  4055. }
  4056. // split cached v into n_head heads
  4057. struct ggml_tensor * v =
  4058. ggml_view_3d(ctx, kv.v_l[il],
  4059. n_kv, n_embd_head_v, n_head_kv,
  4060. ggml_element_size(kv.v_l[il])*n_ctx,
  4061. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  4062. 0);
  4063. cb(v, "v", il);
  4064. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  4065. cb(kqv, "kqv", il);
  4066. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  4067. cb(kqv_merged, "kqv_merged", il);
  4068. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  4069. cb(cur, "kqv_merged_cont", il);
  4070. ggml_build_forward_expand(graph, cur);
  4071. cur = ggml_mul_mat(ctx, wo, cur);
  4072. if (wo_b) {
  4073. cb(cur, "kqv_wo", il);
  4074. }
  4075. if (wo_b) {
  4076. cur = ggml_add(ctx, cur, wo_b);
  4077. }
  4078. return cur;
  4079. }
  4080. static struct ggml_tensor * llm_build_kv(
  4081. struct ggml_context * ctx,
  4082. const llama_model & model,
  4083. const llama_hparams & hparams,
  4084. const llama_kv_cache & kv,
  4085. struct ggml_cgraph * graph,
  4086. struct ggml_tensor * wo,
  4087. struct ggml_tensor * wo_b,
  4088. struct ggml_tensor * k_cur,
  4089. struct ggml_tensor * v_cur,
  4090. struct ggml_tensor * q_cur,
  4091. struct ggml_tensor * kq_mask,
  4092. int64_t n_ctx,
  4093. int32_t n_tokens,
  4094. int32_t kv_head,
  4095. int32_t n_kv,
  4096. float max_alibi_bias,
  4097. float kq_scale,
  4098. const llm_build_cb & cb,
  4099. int il) {
  4100. // these nodes are added to the graph together so that they are not reordered
  4101. // by doing so, the number of splits in the graph is reduced
  4102. ggml_build_forward_expand(graph, q_cur);
  4103. ggml_build_forward_expand(graph, k_cur);
  4104. ggml_build_forward_expand(graph, v_cur);
  4105. llm_build_kv_store(ctx, hparams, kv, graph, k_cur, v_cur, n_ctx, n_tokens, kv_head, cb, il);
  4106. struct ggml_tensor * cur;
  4107. cur = llm_build_kqv(ctx, model, hparams, kv, graph,
  4108. wo, wo_b,
  4109. q_cur, kq_mask, n_ctx, n_tokens, n_kv, max_alibi_bias, kq_scale, cb, il);
  4110. cb(cur, "kqv_out", il);
  4111. return cur;
  4112. }
  4113. struct llm_build_context {
  4114. const llama_model & model;
  4115. const llama_context & lctx;
  4116. const llama_hparams & hparams;
  4117. const llama_cparams & cparams;
  4118. const llama_batch & batch;
  4119. const llama_kv_cache & kv_self;
  4120. const int64_t n_embd;
  4121. const int64_t n_layer;
  4122. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  4123. const int64_t n_head;
  4124. const int64_t n_head_kv;
  4125. const int64_t n_embd_head_k;
  4126. const int64_t n_embd_k_gqa;
  4127. const int64_t n_embd_head_v;
  4128. const int64_t n_embd_v_gqa;
  4129. const int64_t n_expert;
  4130. const int64_t n_expert_used;
  4131. const float freq_base;
  4132. const float freq_scale;
  4133. const float ext_factor;
  4134. const float attn_factor;
  4135. const float beta_fast;
  4136. const float beta_slow;
  4137. const float norm_eps;
  4138. const float norm_rms_eps;
  4139. const int32_t n_tokens;
  4140. const int32_t n_kv; // size of KV cache to consider (n_kv <= n_ctx)
  4141. const int32_t kv_head; // index of where we store new KV data in the cache
  4142. const int32_t n_orig_ctx;
  4143. const bool do_rope_shift;
  4144. const bool causal_attn;
  4145. const llm_build_cb & cb;
  4146. std::vector<uint8_t> & buf_compute_meta;
  4147. struct ggml_context * ctx0 = nullptr;
  4148. // TODO: consider making the entire interface noexcept
  4149. llm_build_context(
  4150. llama_context & lctx,
  4151. const llama_batch & batch,
  4152. const llm_build_cb & cb,
  4153. bool worst_case) :
  4154. model (lctx.model),
  4155. lctx (lctx),
  4156. hparams (model.hparams),
  4157. cparams (lctx.cparams),
  4158. batch (batch),
  4159. kv_self (lctx.kv_self),
  4160. n_embd (hparams.n_embd),
  4161. n_layer (hparams.n_layer),
  4162. n_ctx (cparams.n_ctx),
  4163. n_head (hparams.n_head),
  4164. n_head_kv (hparams.n_head_kv),
  4165. n_embd_head_k (hparams.n_embd_head_k),
  4166. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  4167. n_embd_head_v (hparams.n_embd_head_v),
  4168. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  4169. n_expert (hparams.n_expert),
  4170. n_expert_used (hparams.n_expert_used),
  4171. freq_base (cparams.rope_freq_base),
  4172. freq_scale (cparams.rope_freq_scale),
  4173. ext_factor (cparams.yarn_ext_factor),
  4174. attn_factor (cparams.yarn_attn_factor),
  4175. beta_fast (cparams.yarn_beta_fast),
  4176. beta_slow (cparams.yarn_beta_slow),
  4177. norm_eps (hparams.f_norm_eps),
  4178. norm_rms_eps (hparams.f_norm_rms_eps),
  4179. n_tokens (batch.n_tokens),
  4180. n_kv (worst_case ? n_ctx : kv_self.n),
  4181. kv_head (worst_case ? n_ctx - n_tokens : kv_self.head),
  4182. n_orig_ctx (cparams.n_yarn_orig_ctx),
  4183. do_rope_shift (worst_case || kv_self.has_shift),
  4184. causal_attn (hparams.causal_attn),
  4185. cb (cb),
  4186. buf_compute_meta (lctx.buf_compute_meta) {
  4187. // all initializations should be done in init()
  4188. }
  4189. void init() {
  4190. struct ggml_init_params params = {
  4191. /*.mem_size =*/ buf_compute_meta.size(),
  4192. /*.mem_buffer =*/ buf_compute_meta.data(),
  4193. /*.no_alloc =*/ true,
  4194. };
  4195. ctx0 = ggml_init(params);
  4196. }
  4197. void free() {
  4198. if (ctx0) {
  4199. ggml_free(ctx0);
  4200. ctx0 = nullptr;
  4201. }
  4202. }
  4203. struct ggml_cgraph * build_llama() {
  4204. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4205. const int64_t n_embd_head = hparams.n_embd_head_v;
  4206. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4207. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4208. struct ggml_tensor * cur;
  4209. struct ggml_tensor * inpL;
  4210. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4211. cb(inpL, "inp_embd", -1);
  4212. // inp_pos - contains the positions
  4213. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4214. cb(inp_pos, "inp_pos", -1);
  4215. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4216. 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);
  4217. cb(KQ_mask, "KQ_mask", -1);
  4218. // shift the entire K-cache if needed
  4219. if (do_rope_shift) {
  4220. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  4221. }
  4222. for (int il = 0; il < n_layer; ++il) {
  4223. struct ggml_tensor * inpSA = inpL;
  4224. // norm
  4225. cur = llm_build_norm(ctx0, inpL, hparams,
  4226. model.layers[il].attn_norm, NULL,
  4227. LLM_NORM_RMS, cb, il);
  4228. cb(cur, "attn_norm", il);
  4229. // self-attention
  4230. {
  4231. // compute Q and K and RoPE them
  4232. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4233. cb(Qcur, "Qcur", il);
  4234. if (model.layers[il].bq) {
  4235. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  4236. cb(Qcur, "Qcur", il);
  4237. }
  4238. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4239. cb(Kcur, "Kcur", il);
  4240. if (model.layers[il].bk) {
  4241. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4242. cb(Kcur, "Kcur", il);
  4243. }
  4244. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4245. cb(Vcur, "Vcur", il);
  4246. if (model.layers[il].bv) {
  4247. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4248. cb(Vcur, "Vcur", il);
  4249. }
  4250. Qcur = ggml_rope_custom(
  4251. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4252. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4253. ext_factor, attn_factor, beta_fast, beta_slow
  4254. );
  4255. cb(Qcur, "Qcur", il);
  4256. Kcur = ggml_rope_custom(
  4257. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4258. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4259. ext_factor, attn_factor, beta_fast, beta_slow
  4260. );
  4261. cb(Kcur, "Kcur", il);
  4262. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4263. model.layers[il].wo, model.layers[il].bo,
  4264. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4265. cb(cur, "kqv_out", il);
  4266. }
  4267. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4268. cb(ffn_inp, "ffn_inp", il);
  4269. // feed-forward network
  4270. if (model.layers[il].ffn_gate_inp == nullptr) {
  4271. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4272. model.layers[il].ffn_norm, NULL,
  4273. LLM_NORM_RMS, cb, il);
  4274. cb(cur, "ffn_norm", il);
  4275. cur = llm_build_ffn(ctx0, cur,
  4276. model.layers[il].ffn_up, NULL,
  4277. model.layers[il].ffn_gate, NULL,
  4278. model.layers[il].ffn_down, NULL,
  4279. NULL,
  4280. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4281. cb(cur, "ffn_out", il);
  4282. } else {
  4283. // MoE branch
  4284. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4285. model.layers[il].ffn_norm, NULL,
  4286. LLM_NORM_RMS, cb, il);
  4287. cb(cur, "ffn_norm", il);
  4288. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  4289. cb(logits, "ffn_moe_logits", il);
  4290. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  4291. cb(probs, "ffn_moe_probs", il);
  4292. // select experts
  4293. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  4294. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  4295. ggml_tensor * weights = ggml_get_rows(ctx0,
  4296. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  4297. cb(weights, "ffn_moe_weights", il);
  4298. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  4299. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  4300. cb(weights_sum, "ffn_moe_weights_sum", il);
  4301. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  4302. cb(weights, "ffn_moe_weights_norm", il);
  4303. // compute expert outputs
  4304. ggml_tensor * moe_out = nullptr;
  4305. for (int i = 0; i < n_expert_used; ++i) {
  4306. ggml_tensor * cur_expert;
  4307. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  4308. cb(cur_up, "ffn_moe_up", il);
  4309. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  4310. cb(cur_gate, "ffn_moe_gate", il);
  4311. cur_gate = ggml_silu(ctx0, cur_gate);
  4312. cb(cur_gate, "ffn_moe_silu", il);
  4313. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  4314. cb(cur_expert, "ffn_moe_gate_par", il);
  4315. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  4316. cb(cur_expert, "ffn_moe_down", il);
  4317. cur_expert = ggml_mul(ctx0, cur_expert,
  4318. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  4319. cb(cur_expert, "ffn_moe_weighted", il);
  4320. if (i == 0) {
  4321. moe_out = cur_expert;
  4322. } else {
  4323. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  4324. cb(moe_out, "ffn_moe_out", il);
  4325. }
  4326. }
  4327. cur = moe_out;
  4328. }
  4329. cur = ggml_add(ctx0, cur, ffn_inp);
  4330. cb(cur, "l_out", il);
  4331. // input for next layer
  4332. inpL = cur;
  4333. }
  4334. cur = inpL;
  4335. cur = llm_build_norm(ctx0, cur, hparams,
  4336. model.output_norm, NULL,
  4337. LLM_NORM_RMS, cb, -1);
  4338. cb(cur, "result_norm", -1);
  4339. // lm_head
  4340. cur = ggml_mul_mat(ctx0, model.output, cur);
  4341. cb(cur, "result_output", -1);
  4342. ggml_build_forward_expand(gf, cur);
  4343. return gf;
  4344. }
  4345. struct ggml_cgraph * build_baichuan() {
  4346. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4347. const int64_t n_embd_head = hparams.n_embd_head_v;
  4348. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4349. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4350. struct ggml_tensor * cur;
  4351. struct ggml_tensor * inpL;
  4352. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4353. cb(inpL, "inp_embd", -1);
  4354. // inp_pos - contains the positions
  4355. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4356. cb(inp_pos, "inp_pos", -1);
  4357. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4358. 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);
  4359. cb(KQ_mask, "KQ_mask", -1);
  4360. // shift the entire K-cache if needed
  4361. if (do_rope_shift) {
  4362. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  4363. }
  4364. for (int il = 0; il < n_layer; ++il) {
  4365. struct ggml_tensor * inpSA = inpL;
  4366. cur = llm_build_norm(ctx0, inpL, hparams,
  4367. model.layers[il].attn_norm, NULL,
  4368. LLM_NORM_RMS, cb, il);
  4369. cb(cur, "attn_norm", il);
  4370. // self-attention
  4371. {
  4372. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4373. cb(Qcur, "Qcur", il);
  4374. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4375. cb(Kcur, "Kcur", il);
  4376. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4377. cb(Vcur, "Vcur", il);
  4378. switch (model.type) {
  4379. case MODEL_7B:
  4380. Qcur = ggml_rope_custom(
  4381. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4382. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4383. ext_factor, attn_factor, beta_fast, beta_slow
  4384. );
  4385. Kcur = ggml_rope_custom(
  4386. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4387. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4388. ext_factor, attn_factor, beta_fast, beta_slow
  4389. );
  4390. break;
  4391. case MODEL_13B:
  4392. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  4393. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  4394. break;
  4395. default:
  4396. GGML_ASSERT(false);
  4397. }
  4398. cb(Qcur, "Qcur", il);
  4399. cb(Kcur, "Kcur", il);
  4400. // apply ALiBi for 13B model
  4401. const float max_alibi_bias = model.type == MODEL_13B ? 8.0f : -1.0f;
  4402. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4403. model.layers[il].wo, NULL,
  4404. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, max_alibi_bias, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4405. cb(cur, "kqv_out", il);
  4406. }
  4407. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4408. cb(ffn_inp, "ffn_inp", il);
  4409. // feed-forward network
  4410. {
  4411. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4412. model.layers[il].ffn_norm, NULL,
  4413. LLM_NORM_RMS, cb, il);
  4414. cb(cur, "ffn_norm", il);
  4415. cur = llm_build_ffn(ctx0, cur,
  4416. model.layers[il].ffn_up, NULL,
  4417. model.layers[il].ffn_gate, NULL,
  4418. model.layers[il].ffn_down, NULL,
  4419. NULL,
  4420. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4421. cb(cur, "ffn_out", il);
  4422. }
  4423. cur = ggml_add(ctx0, cur, ffn_inp);
  4424. cb(cur, "l_out", il);
  4425. // input for next layer
  4426. inpL = cur;
  4427. }
  4428. cur = inpL;
  4429. cur = llm_build_norm(ctx0, cur, hparams,
  4430. model.output_norm, NULL,
  4431. LLM_NORM_RMS, cb, -1);
  4432. cb(cur, "result_norm", -1);
  4433. // lm_head
  4434. cur = ggml_mul_mat(ctx0, model.output, cur);
  4435. cb(cur, "result_output", -1);
  4436. ggml_build_forward_expand(gf, cur);
  4437. return gf;
  4438. }
  4439. struct ggml_cgraph * build_falcon() {
  4440. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4441. const int64_t n_embd_head = hparams.n_embd_head_v;
  4442. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4443. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4444. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4445. struct ggml_tensor * cur;
  4446. struct ggml_tensor * inpL;
  4447. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4448. cb(inpL, "inp_embd", -1);
  4449. // inp_pos - contains the positions
  4450. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4451. cb(inp_pos, "inp_pos", -1);
  4452. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4453. 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);
  4454. cb(KQ_mask, "KQ_mask", -1);
  4455. // shift the entire K-cache if needed
  4456. if (do_rope_shift) {
  4457. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4458. }
  4459. for (int il = 0; il < n_layer; ++il) {
  4460. struct ggml_tensor * attn_norm;
  4461. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  4462. model.layers[il].attn_norm,
  4463. model.layers[il].attn_norm_b,
  4464. LLM_NORM, cb, il);
  4465. cb(attn_norm, "attn_norm", il);
  4466. // self-attention
  4467. {
  4468. if (model.layers[il].attn_norm_2) {
  4469. // Falcon-40B
  4470. cur = llm_build_norm(ctx0, inpL, hparams,
  4471. model.layers[il].attn_norm_2,
  4472. model.layers[il].attn_norm_2_b,
  4473. LLM_NORM, cb, il);
  4474. cb(cur, "attn_norm_2", il);
  4475. } else {
  4476. cur = attn_norm;
  4477. }
  4478. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4479. cb(cur, "wqkv", il);
  4480. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4481. 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)));
  4482. 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)));
  4483. cb(Qcur, "Qcur", il);
  4484. cb(Kcur, "Kcur", il);
  4485. cb(Vcur, "Vcur", il);
  4486. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4487. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4488. // using mode = 2 for neox mode
  4489. Qcur = ggml_rope_custom(
  4490. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4491. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4492. );
  4493. cb(Qcur, "Qcur", il);
  4494. Kcur = ggml_rope_custom(
  4495. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4496. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4497. );
  4498. cb(Kcur, "Kcur", il);
  4499. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4500. model.layers[il].wo, NULL,
  4501. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4502. cb(cur, "kqv_out", il);
  4503. }
  4504. struct ggml_tensor * ffn_inp = cur;
  4505. // feed forward
  4506. {
  4507. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  4508. model.layers[il].ffn_up, NULL,
  4509. NULL, NULL,
  4510. model.layers[il].ffn_down, NULL,
  4511. NULL,
  4512. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4513. cb(cur, "ffn_out", il);
  4514. }
  4515. cur = ggml_add(ctx0, cur, ffn_inp);
  4516. cb(cur, "l_out", il);
  4517. cur = ggml_add(ctx0, cur, inpL);
  4518. cb(cur, "l_out", il);
  4519. // input for next layer
  4520. inpL = cur;
  4521. }
  4522. cur = inpL;
  4523. // norm
  4524. cur = llm_build_norm(ctx0, cur, hparams,
  4525. model.output_norm,
  4526. model.output_norm_b,
  4527. LLM_NORM, cb, -1);
  4528. cb(cur, "result_norm", -1);
  4529. cur = ggml_mul_mat(ctx0, model.output, cur);
  4530. cb(cur, "result_output", -1);
  4531. ggml_build_forward_expand(gf, cur);
  4532. return gf;
  4533. }
  4534. struct ggml_cgraph * build_starcoder() {
  4535. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4536. const int64_t n_embd_head = hparams.n_embd_head_v;
  4537. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4538. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4539. struct ggml_tensor * cur;
  4540. struct ggml_tensor * pos;
  4541. struct ggml_tensor * inpL;
  4542. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4543. cb(inpL, "inp_embd", -1);
  4544. // inp_pos - contains the positions
  4545. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4546. cb(inp_pos, "inp_pos", -1);
  4547. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4548. 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);
  4549. cb(KQ_mask, "KQ_mask", -1);
  4550. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  4551. cb(pos, "pos_embd", -1);
  4552. inpL = ggml_add(ctx0, inpL, pos);
  4553. cb(inpL, "inpL", -1);
  4554. for (int il = 0; il < n_layer; ++il) {
  4555. cur = llm_build_norm(ctx0, inpL, hparams,
  4556. model.layers[il].attn_norm,
  4557. model.layers[il].attn_norm_b,
  4558. LLM_NORM, cb, il);
  4559. cb(cur, "attn_norm", il);
  4560. // self-attention
  4561. {
  4562. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4563. cb(cur, "wqkv", il);
  4564. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4565. cb(cur, "bqkv", il);
  4566. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4567. 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)));
  4568. 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)));
  4569. cb(Qcur, "Qcur", il);
  4570. cb(Kcur, "Kcur", il);
  4571. cb(Vcur, "Vcur", il);
  4572. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4573. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4574. model.layers[il].wo, model.layers[il].bo,
  4575. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4576. cb(cur, "kqv_out", il);
  4577. }
  4578. // add the input
  4579. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4580. cb(ffn_inp, "ffn_inp", il);
  4581. // FF
  4582. {
  4583. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4584. model.layers[il].ffn_norm,
  4585. model.layers[il].ffn_norm_b,
  4586. LLM_NORM, cb, il);
  4587. cb(cur, "ffn_norm", il);
  4588. cur = llm_build_ffn(ctx0, cur,
  4589. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4590. NULL, NULL,
  4591. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4592. NULL,
  4593. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4594. cb(cur, "ffn_out", il);
  4595. }
  4596. inpL = ggml_add(ctx0, cur, ffn_inp);
  4597. cb(inpL, "l_out", il);
  4598. }
  4599. cur = llm_build_norm(ctx0, inpL, hparams,
  4600. model.output_norm,
  4601. model.output_norm_b,
  4602. LLM_NORM, cb, -1);
  4603. cb(cur, "result_norm", -1);
  4604. cur = ggml_mul_mat(ctx0, model.output, cur);
  4605. cb(cur, "result_output", -1);
  4606. ggml_build_forward_expand(gf, cur);
  4607. return gf;
  4608. }
  4609. struct ggml_cgraph * build_persimmon() {
  4610. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4611. const int64_t n_embd_head = hparams.n_embd_head_v;
  4612. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4613. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  4614. struct ggml_tensor * cur;
  4615. struct ggml_tensor * inpL;
  4616. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4617. cb(inpL, "inp_embd", -1);
  4618. // inp_pos - contains the positions
  4619. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4620. cb(inp_pos, "inp_pos", -1);
  4621. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4622. 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);
  4623. cb(KQ_mask, "KQ_mask", -1);
  4624. if (do_rope_shift) {
  4625. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4626. }
  4627. for (int il = 0; il < n_layer; ++il) {
  4628. struct ggml_tensor * residual = inpL;
  4629. cur = llm_build_norm(ctx0, inpL, hparams,
  4630. model.layers[il].attn_norm,
  4631. model.layers[il].attn_norm_b,
  4632. LLM_NORM, cb, il);
  4633. cb(cur, "attn_norm", il);
  4634. // self attention
  4635. {
  4636. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4637. cb(cur, "wqkv", il);
  4638. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4639. cb(cur, "bqkv", il);
  4640. // split qkv
  4641. GGML_ASSERT(n_head_kv == n_head);
  4642. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  4643. cb(tmpqkv, "tmpqkv", il);
  4644. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  4645. cb(tmpqkv_perm, "tmpqkv", il);
  4646. struct ggml_tensor * tmpq = ggml_view_3d(
  4647. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4648. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4649. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4650. 0
  4651. );
  4652. cb(tmpq, "tmpq", il);
  4653. struct ggml_tensor * tmpk = ggml_view_3d(
  4654. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4655. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4656. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4657. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  4658. );
  4659. cb(tmpk, "tmpk", il);
  4660. // Q/K Layernorm
  4661. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  4662. model.layers[il].attn_q_norm,
  4663. model.layers[il].attn_q_norm_b,
  4664. LLM_NORM, cb, il);
  4665. cb(tmpq, "tmpq", il);
  4666. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  4667. model.layers[il].attn_k_norm,
  4668. model.layers[il].attn_k_norm_b,
  4669. LLM_NORM, cb, il);
  4670. cb(tmpk, "tmpk", il);
  4671. // RoPE the first n_rot of q/k, pass the other half, and concat.
  4672. struct ggml_tensor * qrot = ggml_view_3d(
  4673. ctx0, tmpq, hparams.n_rot, n_head, n_tokens,
  4674. ggml_element_size(tmpq) * n_embd_head,
  4675. ggml_element_size(tmpq) * n_embd_head * n_head,
  4676. 0
  4677. );
  4678. cb(qrot, "qrot", il);
  4679. struct ggml_tensor * krot = ggml_view_3d(
  4680. ctx0, tmpk, hparams.n_rot, n_head, n_tokens,
  4681. ggml_element_size(tmpk) * n_embd_head,
  4682. ggml_element_size(tmpk) * n_embd_head * n_head,
  4683. 0
  4684. );
  4685. cb(krot, "krot", il);
  4686. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  4687. struct ggml_tensor * qpass = ggml_view_3d(
  4688. ctx0, tmpq, hparams.n_rot, n_head, n_tokens,
  4689. ggml_element_size(tmpq) * n_embd_head,
  4690. ggml_element_size(tmpq) * n_embd_head * n_head,
  4691. ggml_element_size(tmpq) * hparams.n_rot
  4692. );
  4693. cb(qpass, "qpass", il);
  4694. struct ggml_tensor * kpass = ggml_view_3d(
  4695. ctx0, tmpk, hparams.n_rot, n_head, n_tokens,
  4696. ggml_element_size(tmpk) * n_embd_head,
  4697. ggml_element_size(tmpk) * n_embd_head * n_head,
  4698. ggml_element_size(tmpk) * hparams.n_rot
  4699. );
  4700. cb(kpass, "kpass", il);
  4701. struct ggml_tensor * qrotated = ggml_rope_custom(
  4702. ctx0, qrot, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4703. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4704. );
  4705. cb(qrotated, "qrotated", il);
  4706. struct ggml_tensor * krotated = ggml_rope_custom(
  4707. ctx0, krot, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4708. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4709. );
  4710. cb(krotated, "krotated", il);
  4711. // ggml currently only supports concatenation on dim=2
  4712. // so we need to permute qrot, qpass, concat, then permute back.
  4713. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  4714. cb(qrotated, "qrotated", il);
  4715. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  4716. cb(krotated, "krotated", il);
  4717. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  4718. cb(qpass, "qpass", il);
  4719. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  4720. cb(kpass, "kpass", il);
  4721. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  4722. cb(Qcur, "Qcur", il);
  4723. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  4724. cb(Kcur, "Kcur", il);
  4725. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  4726. cb(Q, "Q", il);
  4727. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  4728. cb(Kcur, "Kcur", il);
  4729. struct ggml_tensor * Vcur = ggml_view_3d(
  4730. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4731. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4732. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4733. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  4734. );
  4735. cb(Vcur, "Vcur", il);
  4736. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4737. model.layers[il].wo, model.layers[il].bo,
  4738. Kcur, Vcur, Q, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4739. cb(cur, "kqv_out", il);
  4740. }
  4741. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  4742. cb(ffn_inp, "ffn_inp", il);
  4743. // feed-forward network
  4744. {
  4745. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4746. model.layers[il].ffn_norm,
  4747. model.layers[il].ffn_norm_b,
  4748. LLM_NORM, cb, il);
  4749. cb(cur, "ffn_norm", il);
  4750. cur = llm_build_ffn(ctx0, cur,
  4751. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4752. NULL, NULL,
  4753. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4754. NULL,
  4755. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  4756. cb(cur, "ffn_out", il);
  4757. }
  4758. cur = ggml_add(ctx0, cur, ffn_inp);
  4759. cb(cur, "l_out", il);
  4760. inpL = cur;
  4761. }
  4762. cur = inpL;
  4763. cur = llm_build_norm(ctx0, cur, hparams,
  4764. model.output_norm,
  4765. model.output_norm_b,
  4766. LLM_NORM, cb, -1);
  4767. cb(cur, "result_norm", -1);
  4768. cur = ggml_mul_mat(ctx0, model.output, cur);
  4769. cb(cur, "result_output", -1);
  4770. ggml_build_forward_expand(gf, cur);
  4771. return gf;
  4772. }
  4773. struct ggml_cgraph * build_refact() {
  4774. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4775. const int64_t n_embd_head = hparams.n_embd_head_v;
  4776. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4777. struct ggml_tensor * cur;
  4778. struct ggml_tensor * inpL;
  4779. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4780. cb(inpL, "inp_embd", -1);
  4781. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4782. 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);
  4783. cb(KQ_mask, "KQ_mask", -1);
  4784. for (int il = 0; il < n_layer; ++il) {
  4785. struct ggml_tensor * inpSA = inpL;
  4786. cur = llm_build_norm(ctx0, inpL, hparams,
  4787. model.layers[il].attn_norm, NULL,
  4788. LLM_NORM_RMS, cb, il);
  4789. cb(cur, "attn_norm", il);
  4790. // self-attention
  4791. {
  4792. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4793. cb(Qcur, "Qcur", il);
  4794. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4795. cb(Kcur, "Kcur", il);
  4796. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4797. cb(Vcur, "Vcur", il);
  4798. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4799. cb(Kcur, "Kcur", il);
  4800. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4801. cb(Qcur, "Qcur", il);
  4802. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4803. model.layers[il].wo, NULL,
  4804. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, 8.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4805. cb(cur, "kqv_out", il);
  4806. }
  4807. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4808. cb(ffn_inp, "ffn_inp", il);
  4809. // feed-forward network
  4810. {
  4811. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4812. model.layers[il].ffn_norm, NULL,
  4813. LLM_NORM_RMS, cb, il);
  4814. cb(cur, "ffn_norm", il);
  4815. cur = llm_build_ffn(ctx0, cur,
  4816. model.layers[il].ffn_up, NULL,
  4817. model.layers[il].ffn_gate, NULL,
  4818. model.layers[il].ffn_down, NULL,
  4819. NULL,
  4820. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4821. cb(cur, "ffn_out", il);
  4822. }
  4823. cur = ggml_add(ctx0, cur, ffn_inp);
  4824. cb(cur, "l_out", il);
  4825. // input for next layer
  4826. inpL = cur;
  4827. }
  4828. cur = inpL;
  4829. cur = llm_build_norm(ctx0, cur, hparams,
  4830. model.output_norm, NULL,
  4831. LLM_NORM_RMS, cb, -1);
  4832. cb(cur, "result_norm", -1);
  4833. // lm_head
  4834. cur = ggml_mul_mat(ctx0, model.output, cur);
  4835. cb(cur, "result_output", -1);
  4836. ggml_build_forward_expand(gf, cur);
  4837. return gf;
  4838. }
  4839. struct ggml_cgraph * build_bert() {
  4840. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4841. const int64_t n_embd_head = hparams.n_embd_head_v;
  4842. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4843. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4844. struct ggml_tensor * cur;
  4845. struct ggml_tensor * inpL;
  4846. // get input vectors with right size
  4847. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4848. struct ggml_tensor * inp_sum = ggml_view_1d(ctx0, lctx.inp_sum, n_tokens, 0);
  4849. // construct input embeddings (token, type, position)
  4850. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4851. // token types are hardcoded to zero ("Sentence A")
  4852. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  4853. inpL = ggml_add(ctx0, inpL, type_row0);
  4854. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  4855. cb(inpL, "inp_embd", -1);
  4856. // embed layer norm
  4857. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  4858. cb(inpL, "inp_norm", -1);
  4859. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4860. 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);
  4861. cb(KQ_mask, "KQ_mask", -1); // [n_kv, n_tokens]
  4862. // iterate layers
  4863. for (int il = 0; il < n_layer; ++il) {
  4864. struct ggml_tensor * cur = inpL;
  4865. // self-attention
  4866. {
  4867. struct ggml_tensor * Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  4868. cb(Qcur, "Qcur", il);
  4869. struct ggml_tensor * Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  4870. cb(Kcur, "Kcur", il);
  4871. struct ggml_tensor * Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  4872. cb(Vcur, "Vcur", il);
  4873. // seems like we just need to do this for Q?
  4874. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4875. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4876. model.layers[il].wo, model.layers[il].bo,
  4877. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4878. cb(cur, "kqv_out", il);
  4879. }
  4880. // re-add the layer input
  4881. cur = ggml_add(ctx0, cur, inpL);
  4882. // attention layer norm
  4883. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_norm, model.layers[il].attn_norm_b, LLM_NORM, cb, il);
  4884. struct ggml_tensor * ffn_inp = cur;
  4885. cb(ffn_inp, "ffn_inp", il);
  4886. // feed-forward network
  4887. cur = llm_build_ffn(ctx0, cur,
  4888. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4889. NULL, NULL,
  4890. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4891. NULL,
  4892. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4893. cb(cur, "ffn_out", il);
  4894. // attentions bypass the intermediate layer
  4895. cur = ggml_add(ctx0, cur, ffn_inp);
  4896. // output layer norm
  4897. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].ffn_norm, model.layers[il].ffn_norm_b, LLM_NORM, cb, il);
  4898. // input for next layer
  4899. inpL = cur;
  4900. }
  4901. // final output
  4902. cur = inpL;
  4903. // pooling
  4904. cur = ggml_mul_mat(ctx0, inp_sum, ggml_cont(ctx0, ggml_transpose(ctx0, cur)));
  4905. cb(cur, "result_embed", -1);
  4906. ggml_build_forward_expand(gf, cur);
  4907. return gf;
  4908. }
  4909. struct ggml_cgraph * build_bloom() {
  4910. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4911. const int64_t n_embd_head = hparams.n_embd_head_v;
  4912. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4913. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4914. struct ggml_tensor * cur;
  4915. struct ggml_tensor * inpL;
  4916. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4917. cb(inpL, "inp_embd", -1);
  4918. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4919. 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);
  4920. cb(KQ_mask, "KQ_mask", -1);
  4921. inpL = llm_build_norm(ctx0, inpL, hparams,
  4922. model.tok_norm,
  4923. model.tok_norm_b,
  4924. LLM_NORM, cb, -1);
  4925. cb(inpL, "inp_norm", -1);
  4926. for (int il = 0; il < n_layer; ++il) {
  4927. cur = llm_build_norm(ctx0, inpL, hparams,
  4928. model.layers[il].attn_norm,
  4929. model.layers[il].attn_norm_b,
  4930. LLM_NORM, cb, il);
  4931. cb(cur, "attn_norm", il);
  4932. // self-attention
  4933. {
  4934. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4935. cb(cur, "wqkv", il);
  4936. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4937. cb(cur, "bqkv", il);
  4938. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4939. 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)));
  4940. 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)));
  4941. cb(Qcur, "Qcur", il);
  4942. cb(Kcur, "Kcur", il);
  4943. cb(Vcur, "Vcur", il);
  4944. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4945. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4946. model.layers[il].wo, model.layers[il].bo,
  4947. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, 8.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4948. cb(cur, "kqv_out", il);
  4949. }
  4950. // Add the input
  4951. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4952. cb(ffn_inp, "ffn_inp", il);
  4953. // FF
  4954. {
  4955. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4956. model.layers[il].ffn_norm,
  4957. model.layers[il].ffn_norm_b,
  4958. LLM_NORM, cb, il);
  4959. cb(cur, "ffn_norm", il);
  4960. cur = llm_build_ffn(ctx0, cur,
  4961. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4962. NULL, NULL,
  4963. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4964. NULL,
  4965. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4966. cb(cur, "ffn_out", il);
  4967. }
  4968. inpL = ggml_add(ctx0, cur, ffn_inp);
  4969. cb(inpL, "l_out", il);
  4970. }
  4971. cur = llm_build_norm(ctx0, inpL, hparams,
  4972. model.output_norm,
  4973. model.output_norm_b,
  4974. LLM_NORM, cb, -1);
  4975. cb(cur, "result_norm", -1);
  4976. cur = ggml_mul_mat(ctx0, model.output, cur);
  4977. cb(cur, "result_output", -1);
  4978. ggml_build_forward_expand(gf, cur);
  4979. return gf;
  4980. }
  4981. struct ggml_cgraph * build_mpt() {
  4982. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4983. const int64_t n_embd_head = hparams.n_embd_head_v;
  4984. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4985. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4986. struct ggml_tensor * cur;
  4987. struct ggml_tensor * inpL;
  4988. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4989. cb(inpL, "inp_embd", -1);
  4990. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4991. 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);
  4992. cb(KQ_mask, "KQ_mask", -1);
  4993. for (int il = 0; il < n_layer; ++il) {
  4994. struct ggml_tensor * attn_norm;
  4995. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  4996. model.layers[il].attn_norm,
  4997. NULL,
  4998. LLM_NORM, cb, il);
  4999. cb(attn_norm, "attn_norm", il);
  5000. // self-attention
  5001. {
  5002. cur = attn_norm;
  5003. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5004. cb(cur, "wqkv", il);
  5005. if (hparams.f_clamp_kqv > 0.0f) {
  5006. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  5007. cb(cur, "wqkv_clamped", il);
  5008. }
  5009. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5010. 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)));
  5011. 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)));
  5012. cb(Qcur, "Qcur", il);
  5013. cb(Kcur, "Kcur", il);
  5014. cb(Vcur, "Vcur", il);
  5015. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5016. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5017. model.layers[il].wo, NULL,
  5018. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, hparams.f_max_alibi_bias, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5019. cb(cur, "kqv_out", il);
  5020. }
  5021. // Add the input
  5022. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5023. cb(ffn_inp, "ffn_inp", il);
  5024. // feed forward
  5025. {
  5026. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5027. model.layers[il].ffn_norm,
  5028. NULL,
  5029. LLM_NORM, cb, il);
  5030. cb(cur, "ffn_norm", il);
  5031. cur = llm_build_ffn(ctx0, cur,
  5032. model.layers[il].ffn_up, NULL,
  5033. NULL, NULL,
  5034. model.layers[il].ffn_down, NULL,
  5035. model.layers[il].ffn_act,
  5036. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5037. cb(cur, "ffn_out", il);
  5038. }
  5039. cur = ggml_add(ctx0, cur, ffn_inp);
  5040. cb(cur, "l_out", il);
  5041. // input for next layer
  5042. inpL = cur;
  5043. }
  5044. cur = inpL;
  5045. cur = llm_build_norm(ctx0, cur, hparams,
  5046. model.output_norm,
  5047. NULL,
  5048. LLM_NORM, cb, -1);
  5049. cb(cur, "result_norm", -1);
  5050. cur = ggml_mul_mat(ctx0, model.output, cur);
  5051. cb(cur, "result_output", -1);
  5052. ggml_build_forward_expand(gf, cur);
  5053. return gf;
  5054. }
  5055. struct ggml_cgraph * build_stablelm() {
  5056. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  5057. const int64_t n_embd_head = hparams.n_embd_head_v;
  5058. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5059. struct ggml_tensor * cur;
  5060. struct ggml_tensor * inpL;
  5061. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5062. cb(inpL, "inp_embd", -1);
  5063. // inp_pos - contains the positions
  5064. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5065. cb(inp_pos, "inp_pos", -1);
  5066. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5067. 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);
  5068. cb(KQ_mask, "KQ_mask", -1);
  5069. // shift the entire K-cache if needed
  5070. if (do_rope_shift) {
  5071. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  5072. }
  5073. for (int il = 0; il < n_layer; ++il) {
  5074. struct ggml_tensor * inpSA = inpL;
  5075. // norm
  5076. cur = llm_build_norm(ctx0, inpL, hparams,
  5077. model.layers[il].attn_norm,
  5078. model.layers[il].attn_norm_b,
  5079. LLM_NORM, cb, il);
  5080. cb(cur, "attn_norm", il);
  5081. // self-attention
  5082. {
  5083. // compute Q and K and RoPE them
  5084. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5085. cb(Qcur, "Qcur", il);
  5086. if (model.layers[il].bq) {
  5087. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5088. cb(Qcur, "Qcur", il);
  5089. }
  5090. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5091. cb(Kcur, "Kcur", il);
  5092. if (model.layers[il].bk) {
  5093. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5094. cb(Kcur, "Kcur", il);
  5095. }
  5096. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5097. cb(Vcur, "Vcur", il);
  5098. if (model.layers[il].bv) {
  5099. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5100. cb(Vcur, "Vcur", il);
  5101. }
  5102. Qcur = ggml_rope_custom(
  5103. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5104. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5105. ext_factor, attn_factor, beta_fast, beta_slow
  5106. );
  5107. cb(Qcur, "Qcur", il);
  5108. Kcur = ggml_rope_custom(
  5109. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5110. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5111. ext_factor, attn_factor, beta_fast, beta_slow
  5112. );
  5113. cb(Kcur, "Kcur", il);
  5114. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5115. model.layers[il].wo, NULL,
  5116. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5117. cb(cur, "kqv_out", il);
  5118. }
  5119. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5120. cb(ffn_inp, "ffn_inp", il);
  5121. // feed-forward network
  5122. {
  5123. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5124. model.layers[il].ffn_norm,
  5125. model.layers[il].ffn_norm_b,
  5126. LLM_NORM, cb, il);
  5127. cb(cur, "ffn_norm", il);
  5128. cur = llm_build_ffn(ctx0, cur,
  5129. model.layers[il].ffn_up, NULL,
  5130. model.layers[il].ffn_gate, NULL,
  5131. model.layers[il].ffn_down, NULL,
  5132. NULL,
  5133. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5134. cb(cur, "ffn_out", il);
  5135. }
  5136. cur = ggml_add(ctx0, cur, ffn_inp);
  5137. cb(cur, "l_out", il);
  5138. // input for next layer
  5139. inpL = cur;
  5140. }
  5141. cur = inpL;
  5142. cur = llm_build_norm(ctx0, cur, hparams,
  5143. model.output_norm,
  5144. model.output_norm_b,
  5145. LLM_NORM, cb, -1);
  5146. cb(cur, "result_norm", -1);
  5147. // lm_head
  5148. cur = ggml_mul_mat(ctx0, model.output, cur);
  5149. cb(cur, "result_output", -1);
  5150. ggml_build_forward_expand(gf, cur);
  5151. return gf;
  5152. }
  5153. struct ggml_cgraph * build_qwen() {
  5154. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5155. const int64_t n_embd_head = hparams.n_embd_head_v;
  5156. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5157. struct ggml_tensor * cur;
  5158. struct ggml_tensor * inpL;
  5159. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5160. cb(inpL, "inp_embd", -1);
  5161. // inp_pos - contains the positions
  5162. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5163. cb(inp_pos, "inp_pos", -1);
  5164. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5165. 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);
  5166. cb(KQ_mask, "KQ_mask", -1);
  5167. // shift the entire K-cache if needed
  5168. if (do_rope_shift) {
  5169. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  5170. }
  5171. for (int il = 0; il < n_layer; ++il) {
  5172. struct ggml_tensor * inpSA = inpL;
  5173. cur = llm_build_norm(ctx0, inpL, hparams,
  5174. model.layers[il].attn_norm, NULL,
  5175. LLM_NORM_RMS, cb, il);
  5176. cb(cur, "attn_norm", il);
  5177. // self-attention
  5178. {
  5179. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5180. cb(cur, "wqkv", il);
  5181. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5182. cb(cur, "bqkv", il);
  5183. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5184. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5185. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  5186. cb(Qcur, "Qcur", il);
  5187. cb(Kcur, "Kcur", il);
  5188. cb(Vcur, "Vcur", il);
  5189. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5190. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5191. // using mode = 2 for neox mode
  5192. Qcur = ggml_rope_custom(
  5193. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  5194. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5195. );
  5196. cb(Qcur, "Qcur", il);
  5197. Kcur = ggml_rope_custom(
  5198. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  5199. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5200. );
  5201. cb(Kcur, "Kcur", il);
  5202. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5203. model.layers[il].wo, NULL,
  5204. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5205. cb(cur, "kqv_out", il);
  5206. }
  5207. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5208. cb(ffn_inp, "ffn_inp", il);
  5209. // feed-forward forward
  5210. {
  5211. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5212. model.layers[il].ffn_norm, NULL,
  5213. LLM_NORM_RMS, cb, il);
  5214. cb(cur, "ffn_norm", il);
  5215. cur = llm_build_ffn(ctx0, cur,
  5216. model.layers[il].ffn_up, NULL,
  5217. model.layers[il].ffn_gate, NULL,
  5218. model.layers[il].ffn_down, NULL,
  5219. NULL,
  5220. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5221. cb(cur, "ffn_out", il);
  5222. }
  5223. cur = ggml_add(ctx0, cur, ffn_inp);
  5224. cb(cur, "l_out", il);
  5225. // input for next layer
  5226. inpL = cur;
  5227. }
  5228. cur = inpL;
  5229. cur = llm_build_norm(ctx0, cur, hparams,
  5230. model.output_norm, NULL,
  5231. LLM_NORM_RMS, cb, -1);
  5232. cb(cur, "result_norm", -1);
  5233. // lm_head
  5234. cur = ggml_mul_mat(ctx0, model.output, cur);
  5235. cb(cur, "result_output", -1);
  5236. ggml_build_forward_expand(gf, cur);
  5237. return gf;
  5238. }
  5239. struct ggml_cgraph * build_qwen2() {
  5240. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5241. const int64_t n_embd_head = hparams.n_embd_head_v;
  5242. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5243. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5244. struct ggml_tensor * cur;
  5245. struct ggml_tensor * inpL;
  5246. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5247. cb(inpL, "inp_embd", -1);
  5248. // inp_pos - contains the positions
  5249. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5250. cb(inp_pos, "inp_pos", -1);
  5251. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5252. 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);
  5253. cb(KQ_mask, "KQ_mask", -1);
  5254. // shift the entire K-cache if needed
  5255. if (do_rope_shift) {
  5256. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  5257. }
  5258. for (int il = 0; il < n_layer; ++il) {
  5259. struct ggml_tensor * inpSA = inpL;
  5260. // norm
  5261. cur = llm_build_norm(ctx0, inpL, hparams,
  5262. model.layers[il].attn_norm, NULL,
  5263. LLM_NORM_RMS, cb, il);
  5264. cb(cur, "attn_norm", il);
  5265. // self-attention
  5266. {
  5267. // compute Q and K and RoPE them
  5268. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5269. cb(Qcur, "Qcur", il);
  5270. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5271. cb(Qcur, "Qcur", il);
  5272. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5273. cb(Kcur, "Kcur", il);
  5274. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5275. cb(Kcur, "Kcur", il);
  5276. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5277. cb(Vcur, "Vcur", il);
  5278. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5279. cb(Vcur, "Vcur", il);
  5280. // these nodes are added to the graph together so that they are not reordered
  5281. // by doing so, the number of splits in the graph is reduced
  5282. ggml_build_forward_expand(gf, Qcur);
  5283. ggml_build_forward_expand(gf, Kcur);
  5284. ggml_build_forward_expand(gf, Vcur);
  5285. Qcur = ggml_rope_custom(
  5286. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5287. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5288. ext_factor, attn_factor, beta_fast, beta_slow
  5289. );
  5290. cb(Qcur, "Qcur", il);
  5291. Kcur = ggml_rope_custom(
  5292. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5293. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5294. ext_factor, attn_factor, beta_fast, beta_slow
  5295. );
  5296. cb(Kcur, "Kcur", il);
  5297. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5298. model.layers[il].wo, model.layers[il].bo,
  5299. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5300. cb(cur, "kqv_out", il);
  5301. }
  5302. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5303. cb(ffn_inp, "ffn_inp", il);
  5304. // feed-forward network
  5305. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5306. model.layers[il].ffn_norm, NULL,
  5307. LLM_NORM_RMS, cb, il);
  5308. cb(cur, "ffn_norm", il);
  5309. cur = llm_build_ffn(ctx0, cur,
  5310. model.layers[il].ffn_up, NULL,
  5311. model.layers[il].ffn_gate, NULL,
  5312. model.layers[il].ffn_down, NULL,
  5313. NULL,
  5314. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5315. cb(cur, "ffn_out", il);
  5316. cur = ggml_add(ctx0, cur, ffn_inp);
  5317. cb(cur, "l_out", il);
  5318. // input for next layer
  5319. inpL = cur;
  5320. }
  5321. cur = inpL;
  5322. cur = llm_build_norm(ctx0, cur, hparams,
  5323. model.output_norm, NULL,
  5324. LLM_NORM_RMS, cb, -1);
  5325. cb(cur, "result_norm", -1);
  5326. // lm_head
  5327. cur = ggml_mul_mat(ctx0, model.output, cur);
  5328. cb(cur, "result_output", -1);
  5329. ggml_build_forward_expand(gf, cur);
  5330. return gf;
  5331. }
  5332. struct ggml_cgraph * build_phi2() {
  5333. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5334. const int64_t n_embd_head = hparams.n_embd_head_v;
  5335. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5336. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5337. struct ggml_tensor * cur;
  5338. struct ggml_tensor * attn_norm_output;
  5339. struct ggml_tensor * ffn_output;
  5340. struct ggml_tensor * inpL;
  5341. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5342. cb(inpL, "inp_embd", -1);
  5343. // inp_pos - contains the positions
  5344. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5345. cb(inp_pos, "inp_pos", -1);
  5346. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5347. 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);
  5348. cb(KQ_mask, "KQ_mask", -1);
  5349. // shift the entire K-cache if needed
  5350. if (do_rope_shift) {
  5351. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  5352. }
  5353. for (int il = 0; il < n_layer; ++il) {
  5354. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  5355. model.layers[il].attn_norm,
  5356. model.layers[il].attn_norm_b,
  5357. LLM_NORM, cb, il);
  5358. cb(attn_norm_output, "attn_norm", il);
  5359. // self-attention
  5360. {
  5361. struct ggml_tensor * Qcur = nullptr;
  5362. struct ggml_tensor * Kcur = nullptr;
  5363. struct ggml_tensor * Vcur = nullptr;
  5364. if (model.layers[il].wqkv) {
  5365. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  5366. cb(cur, "wqkv", il);
  5367. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5368. cb(cur, "bqkv", il);
  5369. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5370. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5371. 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)));
  5372. } else {
  5373. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  5374. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  5375. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  5376. }
  5377. cb(Qcur, "Qcur", il);
  5378. cb(Kcur, "Kcur", il);
  5379. cb(Vcur, "Vcur", il);
  5380. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5381. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5382. Qcur = ggml_rope_custom(
  5383. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  5384. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5385. );
  5386. cb(Qcur, "Qcur", il);
  5387. // with phi2, we scale the Q to avoid precision issues
  5388. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  5389. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  5390. cb(Qcur, "Qcur", il);
  5391. Kcur = ggml_rope_custom(
  5392. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  5393. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5394. );
  5395. cb(Kcur, "Kcur", il);
  5396. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5397. model.layers[il].wo, model.layers[il].bo,
  5398. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f, cb, il);
  5399. cb(cur, "kqv_out", il);
  5400. }
  5401. // FF
  5402. {
  5403. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  5404. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5405. NULL, NULL,
  5406. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5407. NULL,
  5408. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5409. cb(ffn_output, "ffn_out", il);
  5410. }
  5411. cur = ggml_add(ctx0, cur, ffn_output);
  5412. cb(cur, "l_out", il);
  5413. cur = ggml_add(ctx0, cur, inpL);
  5414. cb(cur, "l_out", il);
  5415. inpL = cur;
  5416. }
  5417. cur = llm_build_norm(ctx0, inpL, hparams,
  5418. model.output_norm,
  5419. model.output_norm_b,
  5420. LLM_NORM, cb, -1);
  5421. cb(cur, "result_norm", -1);
  5422. cur = ggml_mul_mat(ctx0, model.output, cur);
  5423. cb(cur, "result_output_no_bias", -1);
  5424. cur = ggml_add(ctx0, cur, model.output_b);
  5425. cb(cur, "result_output", -1);
  5426. ggml_build_forward_expand(gf, cur);
  5427. return gf;
  5428. }
  5429. struct ggml_cgraph * build_plamo() {
  5430. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  5431. const int64_t n_embd_head = hparams.n_embd_head_v;
  5432. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5433. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5434. struct ggml_tensor * cur;
  5435. struct ggml_tensor * inpL;
  5436. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5437. cb(inpL, "inp_embd", -1);
  5438. // inp_pos - contains the positions
  5439. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5440. cb(inp_pos, "inp_pos", -1);
  5441. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5442. 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);
  5443. cb(KQ_mask, "KQ_mask", -1);
  5444. // shift the entire K-cache if needed
  5445. if (do_rope_shift) {
  5446. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5447. }
  5448. for (int il = 0; il < n_layer; ++il) {
  5449. // norm
  5450. cur = llm_build_norm(ctx0, inpL, hparams,
  5451. model.layers[il].attn_norm, NULL,
  5452. LLM_NORM_RMS, cb, il);
  5453. cb(cur, "attn_norm", il);
  5454. struct ggml_tensor * attention_norm = cur;
  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. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5461. cb(Kcur, "Kcur", il);
  5462. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5463. cb(Vcur, "Vcur", il);
  5464. Qcur = ggml_rope_custom(
  5465. ctx0, ggml_reshape_3d(ctx0, Qcur, hparams.n_rot, n_head, n_tokens), inp_pos,
  5466. n_embd_head, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5467. ext_factor, attn_factor, beta_fast, beta_slow);
  5468. cb(Qcur, "Qcur", il);
  5469. Kcur = ggml_rope_custom(
  5470. ctx0, ggml_reshape_3d(ctx0, Kcur, hparams.n_rot, n_head_kv, n_tokens), inp_pos,
  5471. n_embd_head, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5472. ext_factor, attn_factor, beta_fast, beta_slow);
  5473. cb(Kcur, "Kcur", il);
  5474. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5475. model.layers[il].wo, NULL,
  5476. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5477. cb(cur, "kqv_out", il);
  5478. }
  5479. struct ggml_tensor * sa_out = cur;
  5480. cur = attention_norm;
  5481. // feed-forward network
  5482. {
  5483. cur = llm_build_ffn(ctx0, cur,
  5484. model.layers[il].ffn_up, NULL,
  5485. model.layers[il].ffn_gate, NULL,
  5486. model.layers[il].ffn_down, NULL,
  5487. NULL,
  5488. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5489. cb(cur, "ffn_out", il);
  5490. }
  5491. cur = ggml_add(ctx0, cur, sa_out);
  5492. cb(cur, "l_out", il);
  5493. cur = ggml_add(ctx0, cur, inpL);
  5494. cb(cur, "l_out", il);
  5495. // input for next layer
  5496. inpL = cur;
  5497. }
  5498. cur = inpL;
  5499. cur = llm_build_norm(ctx0, cur, hparams,
  5500. model.output_norm, NULL,
  5501. LLM_NORM_RMS, cb, -1);
  5502. cb(cur, "result_norm", -1);
  5503. // lm_head
  5504. cur = ggml_mul_mat(ctx0, model.output, cur);
  5505. cb(cur, "result_output", -1);
  5506. ggml_build_forward_expand(gf, cur);
  5507. return gf;
  5508. }
  5509. struct ggml_cgraph * build_gpt2() {
  5510. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5511. const int64_t n_embd_head = hparams.n_embd_head_v;
  5512. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5513. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5514. struct ggml_tensor * cur;
  5515. struct ggml_tensor * pos;
  5516. struct ggml_tensor * inpL;
  5517. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5518. cb(inpL, "inp_embd", -1);
  5519. // inp_pos - contains the positions
  5520. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5521. cb(inp_pos, "inp_pos", -1);
  5522. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5523. 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);
  5524. cb(KQ_mask, "KQ_mask", -1);
  5525. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  5526. cb(pos, "pos_embd", -1);
  5527. inpL = ggml_add(ctx0, inpL, pos);
  5528. cb(inpL, "inpL", -1);
  5529. for (int il = 0; il < n_layer; ++il) {
  5530. cur = llm_build_norm(ctx0, inpL, hparams,
  5531. model.layers[il].attn_norm,
  5532. model.layers[il].attn_norm_b,
  5533. LLM_NORM, cb, il);
  5534. cb(cur, "attn_norm", il);
  5535. // self-attention
  5536. {
  5537. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5538. cb(cur, "wqkv", il);
  5539. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5540. cb(cur, "bqkv", il);
  5541. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5542. 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)));
  5543. 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)));
  5544. cb(Qcur, "Qcur", il);
  5545. cb(Kcur, "Kcur", il);
  5546. cb(Vcur, "Vcur", il);
  5547. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5548. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5549. model.layers[il].wo, model.layers[il].bo,
  5550. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5551. cb(cur, "kqv_out", il);
  5552. }
  5553. // add the input
  5554. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5555. cb(ffn_inp, "ffn_inp", il);
  5556. // FF
  5557. {
  5558. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5559. model.layers[il].ffn_norm,
  5560. model.layers[il].ffn_norm_b,
  5561. LLM_NORM, cb, il);
  5562. cb(cur, "ffn_norm", il);
  5563. cur = llm_build_ffn(ctx0, cur,
  5564. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5565. NULL, NULL,
  5566. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5567. NULL,
  5568. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5569. cb(cur, "ffn_out", il);
  5570. }
  5571. inpL = ggml_add(ctx0, cur, ffn_inp);
  5572. cb(inpL, "l_out", il);
  5573. }
  5574. cur = llm_build_norm(ctx0, inpL, hparams,
  5575. model.output_norm,
  5576. model.output_norm_b,
  5577. LLM_NORM, cb, -1);
  5578. cb(cur, "result_norm", -1);
  5579. cur = ggml_mul_mat(ctx0, model.output, cur);
  5580. cb(cur, "result_output", -1);
  5581. ggml_build_forward_expand(gf, cur);
  5582. return gf;
  5583. }
  5584. struct ggml_cgraph * build_codeshell() {
  5585. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5586. const int64_t n_embd_head = hparams.n_embd_head_v;
  5587. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5588. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5589. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5590. struct ggml_tensor * cur;
  5591. struct ggml_tensor * inpL;
  5592. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5593. cb(inpL, "inp_embd", -1);
  5594. // inp_pos - contains the positions
  5595. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5596. cb(inp_pos, "inp_pos", -1);
  5597. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5598. 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);
  5599. cb(KQ_mask, "KQ_mask", -1);
  5600. // shift the entire K-cache if needed
  5601. if (do_rope_shift) {
  5602. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5603. }
  5604. for (int il = 0; il < n_layer; ++il) {
  5605. cur = llm_build_norm(ctx0, inpL, hparams,
  5606. model.layers[il].attn_norm,
  5607. model.layers[il].attn_norm_b,
  5608. LLM_NORM, cb, il);
  5609. cb(cur, "attn_norm", il);
  5610. // self-attention
  5611. {
  5612. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5613. cb(cur, "wqkv", il);
  5614. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5615. cb(cur, "bqkv", il);
  5616. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5617. 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)));
  5618. 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)));
  5619. cb(tmpq, "tmpq", il);
  5620. cb(tmpk, "tmpk", il);
  5621. cb(Vcur, "Vcur", il);
  5622. struct ggml_tensor * Qcur = ggml_rope_custom(
  5623. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  5624. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5625. ext_factor, attn_factor, beta_fast, beta_slow
  5626. );
  5627. cb(Qcur, "Qcur", il);
  5628. struct ggml_tensor * Kcur = ggml_rope_custom(
  5629. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5630. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5631. ext_factor, attn_factor, beta_fast, beta_slow
  5632. );
  5633. cb(Kcur, "Kcur", il);
  5634. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5635. model.layers[il].wo, model.layers[il].bo,
  5636. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5637. cb(cur, "kqv_out", il);
  5638. }
  5639. // add the input
  5640. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5641. cb(ffn_inp, "ffn_inp", il);
  5642. // FF
  5643. {
  5644. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5645. model.layers[il].ffn_norm,
  5646. model.layers[il].ffn_norm_b,
  5647. LLM_NORM, cb, il);
  5648. cb(cur, "ffn_norm", il);
  5649. cur = llm_build_ffn(ctx0, cur,
  5650. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5651. NULL, NULL,
  5652. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5653. NULL,
  5654. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5655. cb(cur, "ffn_out", il);
  5656. }
  5657. inpL = ggml_add(ctx0, cur, ffn_inp);
  5658. cb(inpL, "l_out", il);
  5659. }
  5660. cur = llm_build_norm(ctx0, inpL, hparams,
  5661. model.output_norm,
  5662. model.output_norm_b,
  5663. LLM_NORM, cb, -1);
  5664. cb(cur, "result_norm", -1);
  5665. cur = ggml_mul_mat(ctx0, model.output, cur);
  5666. cb(cur, "result_output", -1);
  5667. ggml_build_forward_expand(gf, cur);
  5668. return gf;
  5669. }
  5670. struct ggml_cgraph * build_orion() {
  5671. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5672. const int64_t n_embd_head = hparams.n_embd_head_v;
  5673. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5674. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5675. struct ggml_tensor * cur;
  5676. struct ggml_tensor * inpL;
  5677. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5678. cb(inpL, "inp_embd", -1);
  5679. // inp_pos - contains the positions
  5680. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5681. cb(inp_pos, "inp_pos", -1);
  5682. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5683. 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);
  5684. cb(KQ_mask, "KQ_mask", -1);
  5685. // shift the entire K-cache if needed
  5686. if (do_rope_shift) {
  5687. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5688. }
  5689. for (int il = 0; il < n_layer; ++il) {
  5690. struct ggml_tensor * inpSA = inpL;
  5691. // norm
  5692. cur = llm_build_norm(ctx0, inpL, hparams,
  5693. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  5694. LLM_NORM, cb, il);
  5695. cb(cur, "attn_norm", il);
  5696. // self-attention
  5697. {
  5698. // compute Q and K and RoPE them
  5699. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5700. cb(Qcur, "Qcur", il);
  5701. // if (model.layers[il].bq) {
  5702. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5703. // cb(Qcur, "Qcur", il);
  5704. // }
  5705. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5706. cb(Kcur, "Kcur", il);
  5707. // if (model.layers[il].bk) {
  5708. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5709. // cb(Kcur, "Kcur", il);
  5710. // }
  5711. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5712. cb(Vcur, "Vcur", il);
  5713. // if (model.layers[il].bv) {
  5714. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5715. // cb(Vcur, "Vcur", il);
  5716. // }
  5717. Qcur = ggml_rope_custom(
  5718. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5719. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5720. ext_factor, attn_factor, beta_fast, beta_slow
  5721. );
  5722. cb(Qcur, "Qcur", il);
  5723. Kcur = ggml_rope_custom(
  5724. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5725. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5726. ext_factor, attn_factor, beta_fast, beta_slow
  5727. );
  5728. cb(Kcur, "Kcur", il);
  5729. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5730. model.layers[il].wo, NULL,
  5731. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5732. cb(cur, "kqv_out", il);
  5733. }
  5734. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5735. cb(ffn_inp, "ffn_inp", il);
  5736. // feed-forward network
  5737. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5738. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  5739. LLM_NORM, cb, il);
  5740. cb(cur, "ffn_norm", il);
  5741. cur = llm_build_ffn(ctx0, cur,
  5742. model.layers[il].ffn_up, NULL,
  5743. model.layers[il].ffn_gate, NULL,
  5744. model.layers[il].ffn_down, NULL,
  5745. NULL,
  5746. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5747. cb(cur, "ffn_out", il);
  5748. cur = ggml_add(ctx0, cur, ffn_inp);
  5749. cb(cur, "l_out", il);
  5750. // input for next layer
  5751. inpL = cur;
  5752. }
  5753. cur = inpL;
  5754. cur = llm_build_norm(ctx0, cur, hparams,
  5755. model.output_norm, model.output_norm_b,
  5756. LLM_NORM, cb, -1);
  5757. cb(cur, "result_norm", -1);
  5758. // lm_head
  5759. cur = ggml_mul_mat(ctx0, model.output, cur);
  5760. cb(cur, "result_output", -1);
  5761. ggml_build_forward_expand(gf, cur);
  5762. return gf;
  5763. }
  5764. struct ggml_cgraph * build_internlm2() {
  5765. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5766. const int64_t n_embd_head = hparams.n_embd_head_v;
  5767. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5768. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5769. struct ggml_tensor * cur;
  5770. struct ggml_tensor * inpL;
  5771. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5772. cb(inpL, "inp_embd", -1);
  5773. // inp_pos - contains the positions
  5774. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5775. cb(inp_pos, "inp_pos", -1);
  5776. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5777. 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);
  5778. cb(KQ_mask, "KQ_mask", -1);
  5779. // shift the entire K-cache if needed
  5780. if (do_rope_shift) {
  5781. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5782. }
  5783. for (int il = 0; il < n_layer; ++il) {
  5784. struct ggml_tensor * inpSA = inpL;
  5785. // norm
  5786. cur = llm_build_norm(ctx0, inpL, hparams,
  5787. model.layers[il].attn_norm, NULL,
  5788. LLM_NORM_RMS, cb, il);
  5789. cb(cur, "attn_norm", il);
  5790. // self-attention
  5791. {
  5792. // compute Q and K and RoPE them
  5793. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5794. cb(Qcur, "Qcur", il);
  5795. if (model.layers[il].bq) {
  5796. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5797. cb(Qcur, "Qcur", il);
  5798. }
  5799. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5800. cb(Kcur, "Kcur", il);
  5801. if (model.layers[il].bk) {
  5802. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5803. cb(Kcur, "Kcur", il);
  5804. }
  5805. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5806. cb(Vcur, "Vcur", il);
  5807. if (model.layers[il].bv) {
  5808. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5809. cb(Vcur, "Vcur", il);
  5810. }
  5811. Qcur = ggml_rope_custom(
  5812. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5813. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  5814. ext_factor, attn_factor, beta_fast, beta_slow
  5815. );
  5816. cb(Qcur, "Qcur", il);
  5817. Kcur = ggml_rope_custom(
  5818. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5819. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  5820. ext_factor, attn_factor, beta_fast, beta_slow
  5821. );
  5822. cb(Kcur, "Kcur", il);
  5823. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5824. model.layers[il].wo, model.layers[il].bo,
  5825. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5826. cb(cur, "kqv_out", il);
  5827. }
  5828. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5829. cb(ffn_inp, "ffn_inp", il);
  5830. // feed-forward network
  5831. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5832. model.layers[il].ffn_norm, NULL,
  5833. LLM_NORM_RMS, cb, il);
  5834. cb(cur, "ffn_norm", il);
  5835. cur = llm_build_ffn(ctx0, cur,
  5836. model.layers[il].ffn_up, NULL,
  5837. model.layers[il].ffn_gate, NULL,
  5838. model.layers[il].ffn_down, NULL,
  5839. NULL,
  5840. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5841. cb(cur, "ffn_out", il);
  5842. cur = ggml_add(ctx0, cur, ffn_inp);
  5843. cb(cur, "l_out", il);
  5844. // input for next layer
  5845. inpL = cur;
  5846. }
  5847. cur = inpL;
  5848. cur = llm_build_norm(ctx0, cur, hparams,
  5849. model.output_norm, NULL,
  5850. LLM_NORM_RMS, cb, -1);
  5851. cb(cur, "result_norm", -1);
  5852. // lm_head
  5853. cur = ggml_mul_mat(ctx0, model.output, cur);
  5854. cb(cur, "result_output", -1);
  5855. ggml_build_forward_expand(gf, cur);
  5856. return gf;
  5857. }
  5858. // ref: https://arxiv.org/abs/2203.03466
  5859. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  5860. // based on the original build_llama() function
  5861. struct ggml_cgraph * build_minicpm() {
  5862. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5863. const int64_t n_embd_head = hparams.n_embd_head_v;
  5864. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5865. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5866. const int64_t n_embd = hparams.n_embd;
  5867. //TODO: if the model varies, these parameters need to be read from the model
  5868. const int64_t n_embd_base = 256;
  5869. const float scale_embd = 12.0f;
  5870. const float scale_depth = 1.4f;
  5871. struct ggml_tensor * cur;
  5872. struct ggml_tensor * inpL;
  5873. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5874. cb(inpL, "inp_embd", -1);
  5875. // scale the input embeddings
  5876. inpL = ggml_scale(ctx0, inpL, scale_embd);
  5877. cb(inpL, "inp_scaled", -1);
  5878. // inp_pos - contains the positions
  5879. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5880. cb(inp_pos, "inp_pos", -1);
  5881. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5882. 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);
  5883. cb(KQ_mask, "KQ_mask", -1);
  5884. // shift the entire K-cache if needed
  5885. if (do_rope_shift) {
  5886. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5887. }
  5888. for (int il = 0; il < n_layer; ++il) {
  5889. struct ggml_tensor * inpSA = inpL;
  5890. // norm
  5891. cur = llm_build_norm(ctx0, inpL, hparams,
  5892. model.layers[il].attn_norm, NULL,
  5893. LLM_NORM_RMS, cb, il);
  5894. cb(cur, "attn_norm", il);
  5895. // self-attention
  5896. {
  5897. // compute Q and K and RoPE them
  5898. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5899. cb(Qcur, "Qcur", il);
  5900. if (model.layers[il].bq) {
  5901. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5902. cb(Qcur, "Qcur", il);
  5903. }
  5904. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5905. cb(Kcur, "Kcur", il);
  5906. if (model.layers[il].bk) {
  5907. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5908. cb(Kcur, "Kcur", il);
  5909. }
  5910. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5911. cb(Vcur, "Vcur", il);
  5912. if (model.layers[il].bv) {
  5913. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5914. cb(Vcur, "Vcur", il);
  5915. }
  5916. Qcur = ggml_rope_custom(
  5917. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5918. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  5919. ext_factor, attn_factor, beta_fast, beta_slow
  5920. );
  5921. cb(Qcur, "Qcur", il);
  5922. Kcur = ggml_rope_custom(
  5923. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5924. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  5925. ext_factor, attn_factor, beta_fast, beta_slow
  5926. );
  5927. cb(Kcur, "Kcur", il);
  5928. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5929. model.layers[il].wo, model.layers[il].bo,
  5930. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5931. cb(cur, "kqv_out", il);
  5932. }
  5933. // scale_res - scale the hidden states for residual connection
  5934. const float scale_res = scale_depth/sqrtf(float(n_layer));
  5935. cur = ggml_scale(ctx0, cur, scale_res);
  5936. cb(cur, "hidden_scaled", -1);
  5937. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5938. cb(ffn_inp, "ffn_inp", il);
  5939. // feed-forward network
  5940. {
  5941. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5942. model.layers[il].ffn_norm, NULL,
  5943. LLM_NORM_RMS, cb, il);
  5944. cb(cur, "ffn_norm", il);
  5945. cur = llm_build_ffn(ctx0, cur,
  5946. model.layers[il].ffn_up, NULL,
  5947. model.layers[il].ffn_gate, NULL,
  5948. model.layers[il].ffn_down, NULL,
  5949. NULL,
  5950. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5951. cb(cur, "ffn_out", il);
  5952. }
  5953. // scale the hidden states for residual connection
  5954. cur = ggml_scale(ctx0, cur, scale_res);
  5955. cb(cur, "hidden_scaled_ffn", -1);
  5956. cur = ggml_add(ctx0, cur, ffn_inp);
  5957. cb(cur, "l_out", il);
  5958. // input for next layer
  5959. inpL = cur;
  5960. }
  5961. cur = inpL;
  5962. cur = llm_build_norm(ctx0, cur, hparams,
  5963. model.output_norm, NULL,
  5964. LLM_NORM_RMS, cb, -1);
  5965. cb(cur, "result_norm", -1);
  5966. // lm_head scaling
  5967. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  5968. cur = ggml_scale(ctx0, cur, scale_lmhead);
  5969. cb(cur, "lmhead_scaling", -1);
  5970. // lm_head
  5971. cur = ggml_mul_mat(ctx0, model.tok_embd, cur);
  5972. cb(cur, "result_output", -1);
  5973. ggml_build_forward_expand(gf, cur);
  5974. return gf;
  5975. }
  5976. };
  5977. static struct ggml_cgraph * llama_build_graph(
  5978. llama_context & lctx,
  5979. const llama_batch & batch,
  5980. bool worst_case) {
  5981. const auto & model = lctx.model;
  5982. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  5983. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  5984. if (il >= 0) {
  5985. ggml_format_name(cur, "%s-%d", name, il);
  5986. } else {
  5987. ggml_set_name(cur, name);
  5988. }
  5989. if (!lctx.cparams.offload_kqv) {
  5990. if (strcmp(name, "kqv_merged_cont") == 0) {
  5991. // all nodes between the KV store and the attention output are run on the CPU
  5992. ggml_backend_sched_set_node_backend(lctx.sched, cur, lctx.backend_cpu);
  5993. }
  5994. }
  5995. };
  5996. struct ggml_cgraph * result = NULL;
  5997. struct llm_build_context llm(lctx, batch, cb, worst_case);
  5998. llm.init();
  5999. switch (model.arch) {
  6000. case LLM_ARCH_LLAMA:
  6001. {
  6002. result = llm.build_llama();
  6003. } break;
  6004. case LLM_ARCH_BAICHUAN:
  6005. {
  6006. result = llm.build_baichuan();
  6007. } break;
  6008. case LLM_ARCH_FALCON:
  6009. {
  6010. result = llm.build_falcon();
  6011. } break;
  6012. case LLM_ARCH_STARCODER:
  6013. {
  6014. result = llm.build_starcoder();
  6015. } break;
  6016. case LLM_ARCH_PERSIMMON:
  6017. {
  6018. result = llm.build_persimmon();
  6019. } break;
  6020. case LLM_ARCH_REFACT:
  6021. {
  6022. result = llm.build_refact();
  6023. } break;
  6024. case LLM_ARCH_BERT:
  6025. {
  6026. result = llm.build_bert();
  6027. } break;
  6028. case LLM_ARCH_BLOOM:
  6029. {
  6030. result = llm.build_bloom();
  6031. } break;
  6032. case LLM_ARCH_MPT:
  6033. {
  6034. result = llm.build_mpt();
  6035. } break;
  6036. case LLM_ARCH_STABLELM:
  6037. {
  6038. result = llm.build_stablelm();
  6039. } break;
  6040. case LLM_ARCH_QWEN:
  6041. {
  6042. result = llm.build_qwen();
  6043. } break;
  6044. case LLM_ARCH_QWEN2:
  6045. {
  6046. result = llm.build_qwen2();
  6047. } break;
  6048. case LLM_ARCH_PHI2:
  6049. {
  6050. result = llm.build_phi2();
  6051. } break;
  6052. case LLM_ARCH_PLAMO:
  6053. {
  6054. result = llm.build_plamo();
  6055. } break;
  6056. case LLM_ARCH_GPT2:
  6057. {
  6058. result = llm.build_gpt2();
  6059. } break;
  6060. case LLM_ARCH_CODESHELL:
  6061. {
  6062. result = llm.build_codeshell();
  6063. } break;
  6064. case LLM_ARCH_ORION:
  6065. {
  6066. result = llm.build_orion();
  6067. } break;
  6068. case LLM_ARCH_INTERNLM2:
  6069. {
  6070. result = llm.build_internlm2();
  6071. } break;
  6072. case LLM_ARCH_MINICPM:
  6073. {
  6074. result = llm.build_minicpm();
  6075. } break;
  6076. default:
  6077. GGML_ASSERT(false);
  6078. }
  6079. llm.free();
  6080. return result;
  6081. }
  6082. static void llama_set_inputs(llama_context & lctx, const llama_batch & batch) {
  6083. //
  6084. // set input data
  6085. //
  6086. const auto & hparams = lctx.model.hparams;
  6087. const auto & cparams = lctx.cparams;
  6088. const auto & kv_self = lctx.kv_self;
  6089. if (batch.token) {
  6090. const int64_t n_tokens = batch.n_tokens;
  6091. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  6092. }
  6093. if (batch.embd) {
  6094. const int64_t n_embd = hparams.n_embd;
  6095. const int64_t n_tokens = batch.n_tokens;
  6096. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  6097. }
  6098. if (batch.pos) {
  6099. const int64_t n_tokens = batch.n_tokens;
  6100. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  6101. }
  6102. {
  6103. const int64_t n_kv = kv_self.n;
  6104. const int64_t n_tokens = batch.n_tokens;
  6105. assert(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  6106. float * data = (float *) lctx.inp_KQ_mask->data;
  6107. for (int h = 0; h < 1; ++h) {
  6108. for (int j = 0; j < n_tokens; ++j) {
  6109. const llama_pos pos = batch.pos[j];
  6110. const llama_seq_id seq_id = batch.seq_id[j][0];
  6111. for (int i = 0; i < n_kv; ++i) {
  6112. float f;
  6113. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  6114. f = -INFINITY;
  6115. } else {
  6116. f = 0;
  6117. }
  6118. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  6119. }
  6120. }
  6121. }
  6122. }
  6123. {
  6124. assert(ggml_backend_buffer_is_host(lctx.inp_sum->buffer));
  6125. float * data = (float *) lctx.inp_sum->data;
  6126. for (int i = 0; i < batch.n_tokens; ++i) {
  6127. data[i] = 1.0f/float(batch.n_tokens);
  6128. }
  6129. }
  6130. if (kv_self.has_shift) {
  6131. const int64_t n_ctx = cparams.n_ctx;
  6132. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  6133. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  6134. for (int i = 0; i < n_ctx; ++i) {
  6135. data[i] = lctx.kv_self.cells[i].delta;
  6136. }
  6137. }
  6138. }
  6139. // decode a batch of tokens by evaluating the transformer
  6140. //
  6141. // - lctx: llama context
  6142. // - batch: batch to evaluate
  6143. //
  6144. // return 0 on success
  6145. // return positive int on warning
  6146. // return negative int on error
  6147. //
  6148. static int llama_decode_internal(
  6149. llama_context & lctx,
  6150. llama_batch batch) {
  6151. const uint32_t n_tokens = batch.n_tokens;
  6152. if (n_tokens == 0) {
  6153. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  6154. return -1;
  6155. }
  6156. const auto & model = lctx.model;
  6157. const auto & hparams = model.hparams;
  6158. const auto & cparams = lctx.cparams;
  6159. const auto n_batch = cparams.n_batch;
  6160. GGML_ASSERT(n_tokens <= n_batch);
  6161. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  6162. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  6163. const int64_t t_start_us = ggml_time_us();
  6164. #ifdef GGML_USE_MPI
  6165. // TODO: needs fix after #3228
  6166. GGML_ASSERT(false && "not implemented");
  6167. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  6168. #endif
  6169. GGML_ASSERT(n_threads > 0);
  6170. auto & kv_self = lctx.kv_self;
  6171. const int64_t n_embd = hparams.n_embd;
  6172. const int64_t n_vocab = hparams.n_vocab;
  6173. // helpers for smoother batch API transition
  6174. // after deprecating the llama_eval calls, these will be removed
  6175. std::vector<llama_pos> pos;
  6176. std::vector<int32_t> n_seq_id;
  6177. std::vector<llama_seq_id *> seq_id_arr;
  6178. std::vector<std::vector<llama_seq_id>> seq_id;
  6179. if (batch.pos == nullptr) {
  6180. pos.resize(n_tokens);
  6181. for (uint32_t i = 0; i < n_tokens; i++) {
  6182. pos[i] = batch.all_pos_0 + i*batch.all_pos_1;
  6183. }
  6184. batch.pos = pos.data();
  6185. }
  6186. if (batch.seq_id == nullptr) {
  6187. n_seq_id.resize(n_tokens);
  6188. seq_id.resize(n_tokens);
  6189. seq_id_arr.resize(n_tokens);
  6190. for (uint32_t i = 0; i < n_tokens; i++) {
  6191. n_seq_id[i] = 1;
  6192. seq_id[i].resize(1);
  6193. seq_id[i][0] = batch.all_seq_id;
  6194. seq_id_arr[i] = seq_id[i].data();
  6195. }
  6196. batch.n_seq_id = n_seq_id.data();
  6197. batch.seq_id = seq_id_arr.data();
  6198. }
  6199. // if we have enough unused cells before the current head ->
  6200. // better to start searching from the beginning of the cache, hoping to fill it
  6201. if (kv_self.head > kv_self.used + 2*n_tokens) {
  6202. kv_self.head = 0;
  6203. }
  6204. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  6205. return 1;
  6206. }
  6207. // a heuristic, to avoid attending the full cache if it is not yet utilized
  6208. // after enough generations, the benefit from this heuristic disappears
  6209. // if we start defragmenting the cache, the benefit from this will be more important
  6210. kv_self.n = std::min((int32_t) cparams.n_ctx, std::max(32, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  6211. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  6212. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  6213. ggml_backend_sched_reset(lctx.sched);
  6214. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  6215. ggml_cgraph * gf = llama_build_graph(lctx, batch, false);
  6216. // the output is always the last tensor in the graph
  6217. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  6218. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 2];
  6219. if (strcmp(res->name, "result_output") == 0) {
  6220. // the embeddings could be the second to last tensor, or the third to last tensor
  6221. if (strcmp(embeddings->name, "result_norm") != 0) {
  6222. embeddings = gf->nodes[gf->n_nodes - 3];
  6223. GGML_ASSERT(strcmp(embeddings->name, "result_norm") == 0);
  6224. }
  6225. } else if (strcmp(res->name, "result_embed") == 0) {
  6226. embeddings = res;
  6227. res = nullptr;
  6228. } else {
  6229. GGML_ASSERT(false);
  6230. }
  6231. // 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);
  6232. // for big prompts, if BLAS is enabled, it is better to use only one thread
  6233. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  6234. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  6235. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  6236. // with the BLAS calls. need a better solution
  6237. // MoE Special Case: This logic applies when hparams.n_expert == 0, i.e. the model is NOT an MoE model. When an MoE is
  6238. // being processed then Accelerate/BLAS will not be involved, so capping would limit performance.
  6239. if (n_tokens >= 32 && hparams.n_expert == 0 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  6240. n_threads = std::min(4, n_threads);
  6241. }
  6242. #ifdef GGML_USE_MPI
  6243. const int64_t n_layer = hparams.n_layer;
  6244. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  6245. #endif
  6246. #ifdef GGML_USE_METAL
  6247. if (ggml_backend_is_metal(lctx.backend_metal)) {
  6248. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  6249. }
  6250. #endif
  6251. if (lctx.backend_cpu != nullptr) {
  6252. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  6253. }
  6254. llama_set_inputs(lctx, batch);
  6255. ggml_backend_sched_graph_compute(lctx.sched, gf);
  6256. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  6257. #ifdef GGML_USE_MPI
  6258. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  6259. #endif
  6260. // update the kv ring buffer
  6261. {
  6262. if (kv_self.has_shift) {
  6263. kv_self.has_shift = false;
  6264. for (uint32_t i = 0; i < kv_self.size; ++i) {
  6265. kv_self.cells[i].delta = 0;
  6266. }
  6267. }
  6268. kv_self.head += n_tokens;
  6269. // Ensure kv cache head points to a valid index.
  6270. if (kv_self.head >= kv_self.size) {
  6271. kv_self.head = 0;
  6272. }
  6273. }
  6274. #ifdef GGML_PERF
  6275. // print timing information per ggml operation (for debugging purposes)
  6276. // requires GGML_PERF to be defined
  6277. ggml_graph_print(gf);
  6278. #endif
  6279. // plot the computation graph in dot format (for debugging purposes)
  6280. //if (n_past%100 == 0) {
  6281. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  6282. //}
  6283. // extract logits
  6284. // TODO: do not compute and extract logits if only embeddings are needed
  6285. // need to update the graphs to skip "result_output"
  6286. if (res) {
  6287. auto & logits_out = lctx.logits;
  6288. #ifndef NDEBUG
  6289. auto & logits_valid = lctx.logits_valid;
  6290. logits_valid.clear();
  6291. logits_valid.resize(n_tokens);
  6292. logits_out.clear();
  6293. #endif
  6294. ggml_backend_t res_backend = ggml_backend_sched_get_node_backend(lctx.sched, res);
  6295. GGML_ASSERT(res_backend != nullptr);
  6296. if (batch.logits) {
  6297. logits_out.resize(n_vocab * n_tokens);
  6298. for (uint32_t i = 0; i < n_tokens; i++) {
  6299. if (batch.logits[i] == 0) {
  6300. continue;
  6301. }
  6302. ggml_backend_tensor_get_async(res_backend, res, logits_out.data() + (n_vocab*i), (n_vocab*i)*sizeof(float), n_vocab*sizeof(float));
  6303. #ifndef NDEBUG
  6304. logits_valid[i] = true;
  6305. #endif
  6306. }
  6307. } else if (lctx.logits_all) {
  6308. logits_out.resize(n_vocab * n_tokens);
  6309. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), 0, n_vocab*n_tokens*sizeof(float));
  6310. #ifndef NDEBUG
  6311. std::fill(logits_valid.begin(), logits_valid.end(), true);
  6312. #endif
  6313. } else {
  6314. logits_out.resize(n_vocab);
  6315. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), (n_vocab*(n_tokens - 1))*sizeof(float), n_vocab*sizeof(float));
  6316. #ifndef NDEBUG
  6317. logits_valid[0] = true;
  6318. #endif
  6319. }
  6320. ggml_backend_synchronize(res_backend);
  6321. }
  6322. // extract embeddings
  6323. if (!lctx.embedding.empty()) {
  6324. auto & embedding_out = lctx.embedding;
  6325. const int64_t embed_pos = res ? n_embd * (n_tokens-1) : 0;
  6326. embedding_out.resize(n_embd);
  6327. ggml_backend_t embeddings_backend = ggml_backend_sched_get_node_backend(lctx.sched, embeddings);
  6328. ggml_backend_tensor_get_async(embeddings_backend, embeddings, embedding_out.data(), embed_pos*sizeof(float), n_embd*sizeof(float));
  6329. ggml_backend_synchronize(embeddings_backend);
  6330. }
  6331. // measure the performance only for the single-token evals
  6332. if (n_tokens == 1) {
  6333. lctx.t_eval_us += ggml_time_us() - t_start_us;
  6334. lctx.n_eval++;
  6335. }
  6336. else if (n_tokens > 1) {
  6337. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  6338. lctx.n_p_eval += n_tokens;
  6339. }
  6340. // get a more accurate load time, upon first eval
  6341. // TODO: fix this
  6342. if (!lctx.has_evaluated_once) {
  6343. lctx.t_load_us = ggml_time_us() - lctx.t_start_us;
  6344. lctx.has_evaluated_once = true;
  6345. }
  6346. return 0;
  6347. }
  6348. //
  6349. // tokenizer
  6350. //
  6351. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  6352. return vocab.type;
  6353. }
  6354. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  6355. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  6356. }
  6357. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  6358. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  6359. }
  6360. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  6361. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  6362. }
  6363. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  6364. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  6365. }
  6366. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  6367. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  6368. }
  6369. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  6370. GGML_ASSERT(llama_is_byte_token(vocab, id));
  6371. const auto& token_data = vocab.id_to_token.at(id);
  6372. switch (llama_vocab_get_type(vocab)) {
  6373. case LLAMA_VOCAB_TYPE_SPM: {
  6374. auto buf = token_data.text.substr(3, 2);
  6375. return strtol(buf.c_str(), NULL, 16);
  6376. }
  6377. case LLAMA_VOCAB_TYPE_BPE: {
  6378. GGML_ASSERT(false);
  6379. return unicode_to_bytes_bpe(token_data.text);
  6380. }
  6381. case LLAMA_VOCAB_TYPE_WPM: {
  6382. GGML_ASSERT(false);
  6383. }
  6384. default:
  6385. GGML_ASSERT(false);
  6386. }
  6387. }
  6388. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  6389. static const char * hex = "0123456789ABCDEF";
  6390. switch (llama_vocab_get_type(vocab)) {
  6391. case LLAMA_VOCAB_TYPE_SPM: {
  6392. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  6393. return vocab.token_to_id.at(buf);
  6394. }
  6395. case LLAMA_VOCAB_TYPE_WPM:
  6396. case LLAMA_VOCAB_TYPE_BPE: {
  6397. return vocab.token_to_id.at(bytes_to_unicode_bpe(ch));
  6398. }
  6399. default:
  6400. GGML_ASSERT(false);
  6401. }
  6402. }
  6403. static void llama_escape_whitespace(std::string & text) {
  6404. replace_all(text, " ", "\xe2\x96\x81");
  6405. }
  6406. static void llama_unescape_whitespace(std::string & word) {
  6407. replace_all(word, "\xe2\x96\x81", " ");
  6408. }
  6409. struct llm_symbol {
  6410. using index = int;
  6411. index prev;
  6412. index next;
  6413. const char * text;
  6414. size_t n;
  6415. };
  6416. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  6417. // SPM tokenizer
  6418. // original implementation:
  6419. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  6420. struct llm_bigram_spm {
  6421. struct comparator {
  6422. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  6423. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  6424. }
  6425. };
  6426. using queue_storage = std::vector<llm_bigram_spm>;
  6427. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  6428. llm_symbol::index left;
  6429. llm_symbol::index right;
  6430. float score;
  6431. size_t size;
  6432. };
  6433. struct llm_tokenizer_spm {
  6434. llm_tokenizer_spm(const llama_vocab & vocab): vocab(vocab) {}
  6435. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  6436. // split string into utf8 chars
  6437. int index = 0;
  6438. size_t offs = 0;
  6439. while (offs < text.size()) {
  6440. llm_symbol sym;
  6441. size_t len = utf8_len(text[offs]);
  6442. sym.text = text.c_str() + offs;
  6443. sym.n = std::min(len, text.size() - offs);
  6444. offs += sym.n;
  6445. sym.prev = index - 1;
  6446. sym.next = offs == text.size() ? -1 : index + 1;
  6447. index++;
  6448. symbols.emplace_back(sym);
  6449. }
  6450. // seed the work queue with all possible 2-character tokens.
  6451. for (size_t i = 1; i < symbols.size(); ++i) {
  6452. try_add_bigram(i - 1, i);
  6453. }
  6454. // keep substituting the highest frequency pairs for as long as we can.
  6455. while (!work_queue.empty()) {
  6456. auto bigram = work_queue.top();
  6457. work_queue.pop();
  6458. auto & left_sym = symbols[bigram.left];
  6459. auto & right_sym = symbols[bigram.right];
  6460. // if one of the symbols already got merged, skip it.
  6461. if (left_sym.n == 0 || right_sym.n == 0 ||
  6462. left_sym.n + right_sym.n != bigram.size) {
  6463. continue;
  6464. }
  6465. // merge the right sym into the left one
  6466. left_sym.n += right_sym.n;
  6467. right_sym.n = 0;
  6468. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  6469. // remove the right sym from the chain
  6470. left_sym.next = right_sym.next;
  6471. if (right_sym.next >= 0) {
  6472. symbols[right_sym.next].prev = bigram.left;
  6473. }
  6474. // find more substitutions
  6475. try_add_bigram(left_sym.prev, bigram.left);
  6476. try_add_bigram(bigram.left, left_sym.next);
  6477. }
  6478. for (int i = 0; i != -1; i = symbols[i].next) {
  6479. auto & symbol = symbols[i];
  6480. resegment(symbol, output);
  6481. }
  6482. }
  6483. private:
  6484. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  6485. auto text = std::string(symbol.text, symbol.n);
  6486. auto token = vocab.token_to_id.find(text);
  6487. // Do we need to support is_unused?
  6488. if (token != vocab.token_to_id.end()) {
  6489. output.push_back((*token).second);
  6490. return;
  6491. }
  6492. const auto p = rev_merge.find(text);
  6493. if (p == rev_merge.end()) {
  6494. // output any symbols that did not form tokens as bytes.
  6495. for (int j = 0; j < (int)symbol.n; ++j) {
  6496. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  6497. output.push_back(token_id);
  6498. }
  6499. return;
  6500. }
  6501. resegment(symbols[p->second.first], output);
  6502. resegment(symbols[p->second.second], output);
  6503. }
  6504. void try_add_bigram(int left, int right) {
  6505. if (left == -1 || right == -1) {
  6506. return;
  6507. }
  6508. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  6509. auto token = vocab.token_to_id.find(text);
  6510. if (token == vocab.token_to_id.end()) {
  6511. return;
  6512. }
  6513. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  6514. return;
  6515. }
  6516. const auto & tok_data = vocab.id_to_token[(*token).second];
  6517. llm_bigram_spm bigram;
  6518. bigram.left = left;
  6519. bigram.right = right;
  6520. bigram.score = tok_data.score;
  6521. bigram.size = text.size();
  6522. work_queue.push(bigram);
  6523. // Do we need to support is_unused?
  6524. rev_merge[text] = std::make_pair(left, right);
  6525. }
  6526. const llama_vocab & vocab;
  6527. std::vector<llm_symbol> symbols;
  6528. llm_bigram_spm::queue work_queue;
  6529. std::map<std::string, std::pair<int, int>> rev_merge;
  6530. };
  6531. // BPE tokenizer
  6532. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  6533. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  6534. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  6535. struct llm_bigram_bpe {
  6536. struct comparator {
  6537. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  6538. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  6539. }
  6540. };
  6541. using queue_storage = std::vector<llm_bigram_bpe>;
  6542. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  6543. llm_symbol::index left;
  6544. llm_symbol::index right;
  6545. std::string text;
  6546. int rank;
  6547. size_t size;
  6548. };
  6549. struct llm_tokenizer_bpe {
  6550. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  6551. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  6552. int final_prev_index = -1;
  6553. auto word_collection = bpe_gpt2_preprocess(text);
  6554. symbols_final.clear();
  6555. for (auto & word : word_collection) {
  6556. work_queue = llm_bigram_bpe::queue();
  6557. symbols.clear();
  6558. int index = 0;
  6559. size_t offset = 0;
  6560. while (offset < word.size()) {
  6561. llm_symbol sym;
  6562. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  6563. sym.text = word.c_str() + offset;
  6564. sym.n = char_len;
  6565. offset += sym.n;
  6566. sym.prev = index - 1;
  6567. sym.next = offset == word.size() ? -1 : index + 1;
  6568. index++;
  6569. symbols.emplace_back(sym);
  6570. }
  6571. for (size_t i = 1; i < symbols.size(); ++i) {
  6572. add_new_bigram(i - 1, i);
  6573. }
  6574. // build token(s)
  6575. while (!work_queue.empty()) {
  6576. auto bigram = work_queue.top();
  6577. work_queue.pop();
  6578. auto & left_symbol = symbols[bigram.left];
  6579. auto & right_symbol = symbols[bigram.right];
  6580. if (left_symbol.n == 0 || right_symbol.n == 0) {
  6581. continue;
  6582. }
  6583. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  6584. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  6585. if (left_token + right_token != bigram.text) {
  6586. continue; // Skip this bigram if it's outdated
  6587. }
  6588. // merge the right sym into the left one
  6589. left_symbol.n += right_symbol.n;
  6590. right_symbol.n = 0;
  6591. // remove the right sym from the chain
  6592. left_symbol.next = right_symbol.next;
  6593. if (right_symbol.next >= 0) {
  6594. symbols[right_symbol.next].prev = bigram.left;
  6595. }
  6596. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  6597. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  6598. }
  6599. // add the fnished tokens to the final list keeping correct order for next and prev
  6600. for (auto & sym : symbols) {
  6601. if (sym.n > 0) {
  6602. sym.prev = final_prev_index;
  6603. sym.next = -1;
  6604. if (final_prev_index != -1) {
  6605. symbols_final[final_prev_index].next = symbols_final.size();
  6606. }
  6607. symbols_final.emplace_back(sym);
  6608. final_prev_index = symbols_final.size() - 1;
  6609. }
  6610. }
  6611. }
  6612. symbols = symbols_final;
  6613. if (!symbols.empty()) {
  6614. for (int i = 0; i != -1; i = symbols[i].next) {
  6615. auto & symbol = symbols[i];
  6616. if (symbol.n == 0) {
  6617. continue;
  6618. }
  6619. const std::string str = std::string(symbol.text, symbol.n);
  6620. const auto token = vocab.token_to_id.find(str);
  6621. if (token == vocab.token_to_id.end()) {
  6622. for (auto j = str.begin(); j != str.end(); ++j) {
  6623. std::string byte_str(1, *j);
  6624. auto token_multibyte = vocab.token_to_id.find(byte_str);
  6625. if (token_multibyte == vocab.token_to_id.end()) {
  6626. throw std::runtime_error("ERROR: byte not found in vocab");
  6627. }
  6628. output.push_back((*token_multibyte).second);
  6629. }
  6630. } else {
  6631. output.push_back((*token).second);
  6632. }
  6633. }
  6634. }
  6635. }
  6636. private:
  6637. void add_new_bigram(int left, int right) {
  6638. if (left == -1 || right == -1) {
  6639. return;
  6640. }
  6641. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  6642. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  6643. int rank_found = -1;
  6644. rank_found = vocab.find_bpe_rank(left_token, right_token);
  6645. if (rank_found < 0) {
  6646. return;
  6647. }
  6648. llm_bigram_bpe bigram;
  6649. bigram.left = left;
  6650. bigram.right = right;
  6651. bigram.text = left_token + right_token;
  6652. bigram.size = left_token.size() + right_token.size();
  6653. bigram.rank = rank_found;
  6654. work_queue.push(bigram);
  6655. }
  6656. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  6657. std::vector<std::string> bpe_words;
  6658. std::vector<std::string> bpe_encoded_words;
  6659. std::string token = "";
  6660. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  6661. bool collecting_numeric = false;
  6662. bool collecting_letter = false;
  6663. bool collecting_special = false;
  6664. bool collecting_whitespace_lookahead = false;
  6665. bool collecting = false;
  6666. std::vector<std::string> text_utf;
  6667. text_utf.reserve(text.size());
  6668. bpe_words.reserve(text.size());
  6669. bpe_encoded_words.reserve(text.size());
  6670. auto cps = codepoints_from_utf8(text);
  6671. for (size_t i = 0; i < cps.size(); ++i)
  6672. text_utf.emplace_back(codepoint_to_utf8(cps[i]));
  6673. for (int i = 0; i < (int)text_utf.size(); i++) {
  6674. const std::string & utf_char = text_utf[i];
  6675. bool split_condition = false;
  6676. int bytes_remain = text_utf.size() - i;
  6677. // forward backward lookups
  6678. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  6679. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  6680. // handling contractions
  6681. if (!split_condition && bytes_remain >= 2) {
  6682. // 's|'t|'m|'d
  6683. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  6684. split_condition = true;
  6685. }
  6686. if (split_condition) {
  6687. if (token.size()) {
  6688. bpe_words.emplace_back(token); // push previous content as token
  6689. }
  6690. token = utf_char + utf_char_next;
  6691. bpe_words.emplace_back(token);
  6692. token = "";
  6693. i++;
  6694. continue;
  6695. }
  6696. }
  6697. if (!split_condition && bytes_remain >= 3) {
  6698. // 're|'ve|'ll
  6699. if (utf_char == "\'" && (
  6700. (utf_char_next == "r" && utf_char_next_next == "e") ||
  6701. (utf_char_next == "v" && utf_char_next_next == "e") ||
  6702. (utf_char_next == "l" && utf_char_next_next == "l"))
  6703. ) {
  6704. split_condition = true;
  6705. }
  6706. if (split_condition) {
  6707. // current token + next token can be defined
  6708. if (token.size()) {
  6709. bpe_words.emplace_back(token); // push previous content as token
  6710. }
  6711. token = utf_char + utf_char_next + utf_char_next_next;
  6712. bpe_words.emplace_back(token); // the contraction
  6713. token = "";
  6714. i += 2;
  6715. continue;
  6716. }
  6717. }
  6718. if (!split_condition && !collecting) {
  6719. if (codepoint_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  6720. collecting_letter = true;
  6721. collecting = true;
  6722. }
  6723. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  6724. collecting_numeric = true;
  6725. collecting = true;
  6726. }
  6727. else if (
  6728. ((codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (codepoint_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  6729. (!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)
  6730. ) {
  6731. collecting_special = true;
  6732. collecting = true;
  6733. }
  6734. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && codepoint_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  6735. collecting_whitespace_lookahead = true;
  6736. collecting = true;
  6737. }
  6738. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  6739. split_condition = true;
  6740. }
  6741. }
  6742. else if (!split_condition && collecting) {
  6743. if (collecting_letter && codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  6744. split_condition = true;
  6745. }
  6746. else if (collecting_numeric && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  6747. split_condition = true;
  6748. }
  6749. 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)) {
  6750. split_condition = true;
  6751. }
  6752. else if (collecting_whitespace_lookahead && (codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER || codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  6753. split_condition = true;
  6754. }
  6755. }
  6756. if (utf_char_next == "") {
  6757. split_condition = true; // final
  6758. token += utf_char;
  6759. }
  6760. if (split_condition) {
  6761. if (token.size()) {
  6762. bpe_words.emplace_back(token);
  6763. }
  6764. token = utf_char;
  6765. collecting = false;
  6766. collecting_letter = false;
  6767. collecting_numeric = false;
  6768. collecting_special = false;
  6769. collecting_whitespace_lookahead = false;
  6770. }
  6771. else {
  6772. token += utf_char;
  6773. }
  6774. }
  6775. for (std::string & word : bpe_words) {
  6776. std::string encoded_token = "";
  6777. for (char & c : word) {
  6778. encoded_token += bytes_to_unicode_bpe(c);
  6779. }
  6780. bpe_encoded_words.emplace_back(encoded_token);
  6781. }
  6782. return bpe_encoded_words;
  6783. }
  6784. const llama_vocab & vocab;
  6785. std::vector<llm_symbol> symbols;
  6786. std::vector<llm_symbol> symbols_final;
  6787. llm_bigram_bpe::queue work_queue;
  6788. };
  6789. struct llm_tokenizer_wpm {
  6790. llm_tokenizer_wpm(const llama_vocab & vocab): vocab(vocab) {}
  6791. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  6792. auto * token_map = &vocab.token_to_id;
  6793. // normalize and split by whitespace
  6794. std::vector<std::string> words = preprocess(text);
  6795. // bos token prepended already
  6796. // find the longest tokens that form the words
  6797. for (const std::string &word : words) {
  6798. // skip empty words
  6799. if (word.size() == 0) {
  6800. continue;
  6801. }
  6802. // prepend phantom space
  6803. std::string word1 = "\xe2\x96\x81" + word;
  6804. int n = word1.size();
  6805. // we're at the start of a new word
  6806. int i = 0;
  6807. bool match_any = false;
  6808. // move through character position in word
  6809. while (i < n) {
  6810. // loop through possible match length
  6811. bool match = false;
  6812. for (int j = n; j > i; j--) {
  6813. auto it = token_map->find(word1.substr(i, j - i));
  6814. if (it != token_map->end()) {
  6815. output.push_back(it->second);
  6816. match = true;
  6817. match_any = true;
  6818. i = j;
  6819. break;
  6820. }
  6821. }
  6822. // must be an unknown character
  6823. if (!match) {
  6824. i++;
  6825. }
  6826. }
  6827. // we didn't find any matches for this word
  6828. if (!match_any) {
  6829. output.push_back(vocab.special_unk_id);
  6830. }
  6831. }
  6832. // append eos token
  6833. output.push_back(vocab.special_eos_id);
  6834. }
  6835. std::vector<std::string> preprocess(const std::string & text) {
  6836. std::string ori_str = normalize(text);
  6837. uint64_t ori_size = ori_str.size();
  6838. // single punct / single symbol / single digit
  6839. // baseline: add whitespace on the left and right of punct and chinese characters
  6840. std::vector<std::string> words;
  6841. std::string new_str = "";
  6842. uint64_t i = 0;
  6843. while (i < ori_size) {
  6844. int utf_char_len = utf8_len(ori_str[i]);
  6845. if ((utf_char_len == 1) && ispunct(ori_str[i])) {
  6846. new_str += " ";
  6847. new_str += ori_str[i];
  6848. new_str += " ";
  6849. i += 1;
  6850. }
  6851. else if ((utf_char_len == 3) && is_chinese_char(ori_str.substr(i, 3))) {
  6852. new_str += " ";
  6853. new_str += ori_str.substr(i, 3);
  6854. new_str += " ";
  6855. i += 3;
  6856. }
  6857. else {
  6858. new_str += ori_str[i];
  6859. i += 1;
  6860. }
  6861. }
  6862. // split by whitespace
  6863. uint64_t l = 0;
  6864. uint64_t r = 0;
  6865. while (r < new_str.size()) {
  6866. // if is whitespace
  6867. if (isspace(new_str[r])) {
  6868. if (r > l) words.push_back(new_str.substr(l, (r - l)));
  6869. l = r + 1;
  6870. r = l;
  6871. }
  6872. else {
  6873. r += 1;
  6874. }
  6875. }
  6876. if (r > l) {
  6877. words.push_back(new_str.substr(l, (r - l)));
  6878. }
  6879. return words;
  6880. }
  6881. std::string normalize(const std::string & text) {
  6882. // TODO: handle chinese characters? https://github.com/huggingface/tokenizers/blob/ef5f50605ddf9f8caef1598c0e4853862b9707a7/tokenizers/src/normalizers/bert.rs#L98
  6883. std::string text2 = strip_accents(text);
  6884. for (size_t i = 0; i < text2.size(); i += utf8_len(text2[i])) {
  6885. char c = text2[i];
  6886. if (c >= 'A' && c <= 'Z') {
  6887. text2[i] = c - 'A' + 'a';
  6888. }
  6889. }
  6890. return text2;
  6891. }
  6892. bool is_chinese_char(const std::string & str) {
  6893. int len = str.length();
  6894. unsigned int codepoint = 0;
  6895. int num_bytes = 0;
  6896. int i = 0;
  6897. unsigned char ch = static_cast<unsigned char>(str[i]);
  6898. if (ch <= 0x7f) {
  6899. codepoint = ch;
  6900. num_bytes = 1;
  6901. } else if ((ch >> 5) == 0x06) {
  6902. codepoint = ch & 0x1f;
  6903. num_bytes = 2;
  6904. } else if ((ch >> 4) == 0x0e) {
  6905. codepoint = ch & 0x0f;
  6906. num_bytes = 3;
  6907. } else if ((ch >> 3) == 0x1e) {
  6908. codepoint = ch & 0x07;
  6909. num_bytes = 4;
  6910. }
  6911. for (int j = 1; j < num_bytes; ++j) {
  6912. if (i + j >= len) {
  6913. return false; // incomplete UTF-8 character
  6914. }
  6915. unsigned char next_ch = static_cast<unsigned char>(str[i + j]);
  6916. if ((next_ch >> 6) != 0x02) {
  6917. return false; // invalid trailing byte
  6918. }
  6919. codepoint = (codepoint << 6) | (next_ch & 0x3f);
  6920. }
  6921. if ((codepoint >= 0x4E00 && codepoint <= 0x9FFF) ||
  6922. (codepoint >= 0x3400 && codepoint <= 0x4DBF) ||
  6923. (codepoint >= 0x20000 && codepoint <= 0x2A6DF) ||
  6924. (codepoint >= 0x2A700 && codepoint <= 0x2B73F) ||
  6925. (codepoint >= 0x2B740 && codepoint <= 0x2B81F) ||
  6926. (codepoint >= 0x2B920 && codepoint <= 0x2CEAF) || // this should be 0x2B820 but in hf rust code it is 0x2B920
  6927. (codepoint >= 0xF900 && codepoint <= 0xFAFF) ||
  6928. (codepoint >= 0x2F800 && codepoint <= 0x2FA1F) ||
  6929. (codepoint >= 0x3000 && codepoint <= 0x303F) ||
  6930. (codepoint >= 0xFF00 && codepoint <= 0xFFEF)) {
  6931. return true; // NOLINT
  6932. }
  6933. return false;
  6934. }
  6935. std::string strip_accents(const std::string & input_string) {
  6936. std::string resultString;
  6937. std::map<std::string, char> accent_map = {
  6938. {"À", 'A'}, {"Á", 'A'}, {"Â", 'A'}, {"Ã", 'A'}, {"Ä", 'A'}, {"Å", 'A'},
  6939. {"à", 'a'}, {"á", 'a'}, {"â", 'a'}, {"ã", 'a'}, {"ä", 'a'}, {"å", 'a'},
  6940. {"È", 'E'}, {"É", 'E'}, {"Ê", 'E'}, {"Ë", 'E'}, {"è", 'e'}, {"é", 'e'},
  6941. {"ê", 'e'}, {"ë", 'e'}, {"Ì", 'I'}, {"Í", 'I'}, {"Î", 'I'}, {"Ï", 'I'},
  6942. {"ì", 'i'}, {"í", 'i'}, {"î", 'i'}, {"ï", 'i'}, {"Ò", 'O'}, {"Ó", 'O'},
  6943. {"Ô", 'O'}, {"Õ", 'O'}, {"Ö", 'O'}, {"ò", 'o'}, {"ó", 'o'}, {"ô", 'o'},
  6944. {"õ", 'o'}, {"ö", 'o'}, {"Ù", 'U'}, {"Ú", 'U'}, {"Û", 'U'}, {"Ü", 'U'},
  6945. {"ù", 'u'}, {"ú", 'u'}, {"û", 'u'}, {"ü", 'u'}, {"Ý", 'Y'}, {"ý", 'y'},
  6946. {"Ç", 'C'}, {"ç", 'c'}, {"Ñ", 'N'}, {"ñ", 'n'},
  6947. };
  6948. for (size_t i = 0; i < input_string.length();) {
  6949. int len = utf8_len(input_string[i]);
  6950. std::string curChar = input_string.substr(i, len);
  6951. auto iter = accent_map.find(curChar);
  6952. if (iter != accent_map.end()) {
  6953. resultString += iter->second;
  6954. } else {
  6955. resultString += curChar;
  6956. }
  6957. i += len;
  6958. }
  6959. return resultString;
  6960. }
  6961. static size_t utf8_len(char src) {
  6962. const size_t lookup[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4};
  6963. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  6964. return lookup[highbits];
  6965. }
  6966. const llama_vocab & vocab;
  6967. };
  6968. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE {
  6969. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  6970. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  6971. } FRAGMENT_BUFFER_VARIANT_TYPE;
  6972. struct fragment_buffer_variant {
  6973. fragment_buffer_variant(llama_vocab::id _token)
  6974. :
  6975. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  6976. token(_token),
  6977. raw_text(_dummy),
  6978. offset(0),
  6979. length(0){}
  6980. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  6981. :
  6982. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  6983. token((llama_vocab::id)-1),
  6984. raw_text(_raw_text),
  6985. offset(_offset),
  6986. length(_length){
  6987. GGML_ASSERT( _offset >= 0 );
  6988. GGML_ASSERT( _length >= 1 );
  6989. GGML_ASSERT( offset + length <= raw_text.length() );
  6990. }
  6991. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  6992. const llama_vocab::id token;
  6993. const std::string _dummy;
  6994. const std::string & raw_text;
  6995. const uint64_t offset;
  6996. const uint64_t length;
  6997. };
  6998. // #define PRETOKENIZERDEBUG
  6999. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer) {
  7000. // for each special token
  7001. for (const auto & st: vocab.special_tokens_cache) {
  7002. const auto & special_token = st.first;
  7003. const auto & special_id = st.second;
  7004. // for each text fragment
  7005. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  7006. while (it != buffer.end()) {
  7007. auto & fragment = (*it);
  7008. // if a fragment is text ( not yet processed )
  7009. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7010. auto * raw_text = &(fragment.raw_text);
  7011. auto raw_text_base_offset = fragment.offset;
  7012. auto raw_text_base_length = fragment.length;
  7013. // loop over the text
  7014. while (true) {
  7015. // find the first occurrence of a given special token in this fragment
  7016. // passing offset argument only limit the "search area" but match coordinates
  7017. // are still relative to the source full raw_text
  7018. auto match = raw_text->find(special_token, raw_text_base_offset);
  7019. // no occurrences found, stop processing this fragment for a given special token
  7020. if (match == std::string::npos) break;
  7021. // check if match is within bounds of offset <-> length
  7022. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  7023. #ifdef PRETOKENIZERDEBUG
  7024. 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());
  7025. #endif
  7026. auto source = std::distance(buffer.begin(), it);
  7027. // if match is further than base offset
  7028. // then we have some text to the left of it
  7029. if (match > raw_text_base_offset) {
  7030. // left
  7031. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  7032. const int64_t left_reminder_length = match - raw_text_base_offset;
  7033. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  7034. #ifdef PRETOKENIZERDEBUG
  7035. 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());
  7036. #endif
  7037. it++;
  7038. }
  7039. // special token
  7040. buffer.emplace_after(it, special_id);
  7041. it++;
  7042. // right
  7043. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  7044. const int64_t right_reminder_offset = match + special_token.length();
  7045. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  7046. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  7047. #ifdef PRETOKENIZERDEBUG
  7048. 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());
  7049. #endif
  7050. it++;
  7051. if (source == 0) {
  7052. buffer.erase_after(buffer.before_begin());
  7053. } else {
  7054. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  7055. }
  7056. // repeat for the right side
  7057. raw_text_base_offset = right_reminder_offset;
  7058. raw_text_base_length = right_reminder_length;
  7059. #ifdef PRETOKENIZERDEBUG
  7060. 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());
  7061. #endif
  7062. } else {
  7063. if (source == 0) {
  7064. buffer.erase_after(buffer.before_begin());
  7065. } else {
  7066. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  7067. }
  7068. break;
  7069. }
  7070. }
  7071. }
  7072. it++;
  7073. }
  7074. }
  7075. }
  7076. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  7077. std::vector<llama_vocab::id> output;
  7078. // OG tokenizer behavior:
  7079. //
  7080. // tokenizer.encode('', add_bos=True) returns [1]
  7081. // tokenizer.encode('', add_bos=False) returns []
  7082. if (bos && vocab.special_bos_id != -1) {
  7083. output.push_back(vocab.special_bos_id);
  7084. }
  7085. if (raw_text.empty()) {
  7086. return output;
  7087. }
  7088. std::forward_list<fragment_buffer_variant> fragment_buffer;
  7089. fragment_buffer.emplace_front( raw_text, 0, raw_text.length() );
  7090. if (special) tokenizer_st_partition( vocab, fragment_buffer );
  7091. switch (vocab.type) {
  7092. case LLAMA_VOCAB_TYPE_SPM:
  7093. {
  7094. for (const auto & fragment: fragment_buffer) {
  7095. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7096. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  7097. // TODO: It's likely possible to get rid of this string copy entirely
  7098. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  7099. // and passing 'add space prefix' as bool argument
  7100. //
  7101. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7102. if (&fragment == &fragment_buffer.front()) {
  7103. if (vocab.add_space_prefix) {
  7104. raw_text = " " + raw_text; // prefix with space if the first token is not special
  7105. }
  7106. }
  7107. #ifdef PRETOKENIZERDEBUG
  7108. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7109. #endif
  7110. llm_tokenizer_spm tokenizer(vocab);
  7111. llama_escape_whitespace(raw_text);
  7112. tokenizer.tokenize(raw_text, output);
  7113. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7114. output.push_back(fragment.token);
  7115. }
  7116. }
  7117. } break;
  7118. case LLAMA_VOCAB_TYPE_BPE:
  7119. {
  7120. for (const auto & fragment: fragment_buffer) {
  7121. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7122. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7123. #ifdef PRETOKENIZERDEBUG
  7124. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7125. #endif
  7126. llm_tokenizer_bpe tokenizer(vocab);
  7127. tokenizer.tokenize(raw_text, output);
  7128. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7129. output.push_back(fragment.token);
  7130. }
  7131. }
  7132. } break;
  7133. case LLAMA_VOCAB_TYPE_WPM:
  7134. {
  7135. for (const auto & fragment: fragment_buffer) {
  7136. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7137. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7138. #ifdef PRETOKENIZERDEBUG
  7139. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7140. #endif
  7141. llm_tokenizer_wpm tokenizer(vocab);
  7142. tokenizer.tokenize(raw_text, output);
  7143. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7144. output.push_back(fragment.token);
  7145. }
  7146. }
  7147. } break;
  7148. }
  7149. return output;
  7150. }
  7151. //
  7152. // grammar - internal
  7153. //
  7154. struct llama_partial_utf8 {
  7155. uint32_t value; // bit value so far (unshifted)
  7156. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  7157. };
  7158. struct llama_grammar {
  7159. const std::vector<std::vector<llama_grammar_element>> rules;
  7160. std::vector<std::vector<const llama_grammar_element *>> stacks;
  7161. // buffer for partially generated UTF-8 sequence from accepted tokens
  7162. llama_partial_utf8 partial_utf8;
  7163. };
  7164. struct llama_grammar_candidate {
  7165. size_t index;
  7166. const uint32_t * code_points;
  7167. llama_partial_utf8 partial_utf8;
  7168. };
  7169. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  7170. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  7171. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  7172. const std::string & src,
  7173. llama_partial_utf8 partial_start) {
  7174. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  7175. const char * pos = src.c_str();
  7176. std::vector<uint32_t> code_points;
  7177. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  7178. code_points.reserve(src.size() + 1);
  7179. uint32_t value = partial_start.value;
  7180. int n_remain = partial_start.n_remain;
  7181. // continue previous decode, if applicable
  7182. while (*pos != 0 && n_remain > 0) {
  7183. uint8_t next_byte = static_cast<uint8_t>(*pos);
  7184. if ((next_byte >> 6) != 2) {
  7185. // invalid sequence, abort
  7186. code_points.push_back(0);
  7187. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  7188. }
  7189. value = (value << 6) + (next_byte & 0x3F);
  7190. ++pos;
  7191. --n_remain;
  7192. }
  7193. if (partial_start.n_remain > 0 && n_remain == 0) {
  7194. code_points.push_back(value);
  7195. }
  7196. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  7197. while (*pos != 0) {
  7198. uint8_t first_byte = static_cast<uint8_t>(*pos);
  7199. uint8_t highbits = first_byte >> 4;
  7200. n_remain = lookup[highbits] - 1;
  7201. if (n_remain < 0) {
  7202. // invalid sequence, abort
  7203. code_points.clear();
  7204. code_points.push_back(0);
  7205. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  7206. }
  7207. uint8_t mask = (1 << (7 - n_remain)) - 1;
  7208. value = first_byte & mask;
  7209. ++pos;
  7210. while (*pos != 0 && n_remain > 0) {
  7211. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  7212. ++pos;
  7213. --n_remain;
  7214. }
  7215. if (n_remain == 0) {
  7216. code_points.push_back(value);
  7217. }
  7218. }
  7219. code_points.push_back(0);
  7220. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  7221. }
  7222. // returns true iff pos points to the end of one of the definitions of a rule
  7223. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  7224. switch (pos->type) {
  7225. case LLAMA_GRETYPE_END: return true; // NOLINT
  7226. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  7227. default: return false;
  7228. }
  7229. }
  7230. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  7231. // asserts that pos is pointing to a char range element
  7232. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  7233. const llama_grammar_element * pos,
  7234. const uint32_t chr) {
  7235. bool found = false;
  7236. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  7237. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  7238. do {
  7239. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  7240. // inclusive range, e.g. [a-z]
  7241. found = found || (pos->value <= chr && chr <= pos[1].value);
  7242. pos += 2;
  7243. } else {
  7244. // exact char match, e.g. [a] or "a"
  7245. found = found || pos->value == chr;
  7246. pos += 1;
  7247. }
  7248. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  7249. return std::make_pair(found == is_positive_char, pos);
  7250. }
  7251. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  7252. // range at pos (regular or inverse range)
  7253. // asserts that pos is pointing to a char range element
  7254. static bool llama_grammar_match_partial_char(
  7255. const llama_grammar_element * pos,
  7256. const llama_partial_utf8 partial_utf8) {
  7257. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  7258. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  7259. uint32_t partial_value = partial_utf8.value;
  7260. int n_remain = partial_utf8.n_remain;
  7261. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  7262. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  7263. return false;
  7264. }
  7265. // range of possible code points this partial UTF-8 sequence could complete to
  7266. uint32_t low = partial_value << (n_remain * 6);
  7267. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  7268. if (low == 0) {
  7269. if (n_remain == 2) {
  7270. low = 1 << 11;
  7271. } else if (n_remain == 3) {
  7272. low = 1 << 16;
  7273. }
  7274. }
  7275. do {
  7276. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  7277. // inclusive range, e.g. [a-z]
  7278. if (pos->value <= high && low <= pos[1].value) {
  7279. return is_positive_char;
  7280. }
  7281. pos += 2;
  7282. } else {
  7283. // exact char match, e.g. [a] or "a"
  7284. if (low <= pos->value && pos->value <= high) {
  7285. return is_positive_char;
  7286. }
  7287. pos += 1;
  7288. }
  7289. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  7290. return !is_positive_char;
  7291. }
  7292. // transforms a grammar pushdown stack into N possible stacks, all ending
  7293. // at a character range (terminal element)
  7294. static void llama_grammar_advance_stack(
  7295. const std::vector<std::vector<llama_grammar_element>> & rules,
  7296. const std::vector<const llama_grammar_element *> & stack,
  7297. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  7298. if (stack.empty()) {
  7299. new_stacks.emplace_back(stack);
  7300. return;
  7301. }
  7302. const llama_grammar_element * pos = stack.back();
  7303. switch (pos->type) {
  7304. case LLAMA_GRETYPE_RULE_REF: {
  7305. const size_t rule_id = static_cast<size_t>(pos->value);
  7306. const llama_grammar_element * subpos = rules[rule_id].data();
  7307. do {
  7308. // init new stack without the top (pos)
  7309. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  7310. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  7311. // if this rule ref is followed by another element, add that to stack
  7312. new_stack.push_back(pos + 1);
  7313. }
  7314. if (!llama_grammar_is_end_of_sequence(subpos)) {
  7315. // if alternate is nonempty, add to stack
  7316. new_stack.push_back(subpos);
  7317. }
  7318. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  7319. while (!llama_grammar_is_end_of_sequence(subpos)) {
  7320. // scan to end of alternate def
  7321. subpos++;
  7322. }
  7323. if (subpos->type == LLAMA_GRETYPE_ALT) {
  7324. // there's another alternate def of this rule to process
  7325. subpos++;
  7326. } else {
  7327. break;
  7328. }
  7329. } while (true);
  7330. break;
  7331. }
  7332. case LLAMA_GRETYPE_CHAR:
  7333. case LLAMA_GRETYPE_CHAR_NOT:
  7334. new_stacks.emplace_back(stack);
  7335. break;
  7336. default:
  7337. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  7338. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  7339. // those
  7340. GGML_ASSERT(false);
  7341. }
  7342. }
  7343. // takes a set of possible pushdown stacks on a grammar, which are required to
  7344. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  7345. // produces the N possible stacks if the given char is accepted at those
  7346. // positions
  7347. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  7348. const std::vector<std::vector<llama_grammar_element>> & rules,
  7349. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  7350. const uint32_t chr) {
  7351. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  7352. for (const auto & stack : stacks) {
  7353. if (stack.empty()) {
  7354. continue;
  7355. }
  7356. auto match = llama_grammar_match_char(stack.back(), chr);
  7357. if (match.first) {
  7358. const llama_grammar_element * pos = match.second;
  7359. // update top of stack to next element, if any
  7360. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  7361. if (!llama_grammar_is_end_of_sequence(pos)) {
  7362. new_stack.push_back(pos);
  7363. }
  7364. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  7365. }
  7366. }
  7367. return new_stacks;
  7368. }
  7369. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  7370. const std::vector<std::vector<llama_grammar_element>> & rules,
  7371. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  7372. const std::vector<llama_grammar_candidate> & candidates);
  7373. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  7374. const std::vector<std::vector<llama_grammar_element>> & rules,
  7375. const std::vector<const llama_grammar_element *> & stack,
  7376. const std::vector<llama_grammar_candidate> & candidates) {
  7377. std::vector<llama_grammar_candidate> rejects;
  7378. if (stack.empty()) {
  7379. for (const auto & tok : candidates) {
  7380. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  7381. rejects.push_back(tok);
  7382. }
  7383. }
  7384. return rejects;
  7385. }
  7386. const llama_grammar_element * stack_pos = stack.back();
  7387. std::vector<llama_grammar_candidate> next_candidates;
  7388. for (const auto & tok : candidates) {
  7389. if (*tok.code_points == 0) {
  7390. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  7391. // that cannot satisfy this position in grammar
  7392. if (tok.partial_utf8.n_remain != 0 &&
  7393. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  7394. rejects.push_back(tok);
  7395. }
  7396. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  7397. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  7398. } else {
  7399. rejects.push_back(tok);
  7400. }
  7401. }
  7402. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  7403. // update top of stack to next element, if any
  7404. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  7405. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  7406. stack_after.push_back(stack_pos_after);
  7407. }
  7408. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  7409. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  7410. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  7411. for (const auto & tok : next_rejects) {
  7412. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  7413. }
  7414. return rejects;
  7415. }
  7416. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  7417. const std::vector<std::vector<llama_grammar_element>> & rules,
  7418. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  7419. const std::vector<llama_grammar_candidate> & candidates) {
  7420. GGML_ASSERT(!stacks.empty()); // REVIEW
  7421. if (candidates.empty()) {
  7422. return std::vector<llama_grammar_candidate>();
  7423. }
  7424. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  7425. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  7426. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  7427. }
  7428. return rejects;
  7429. }
  7430. //
  7431. // grammar - external
  7432. //
  7433. struct llama_grammar * llama_grammar_init(
  7434. const llama_grammar_element ** rules,
  7435. size_t n_rules,
  7436. size_t start_rule_index) {
  7437. const llama_grammar_element * pos;
  7438. // copy rule definitions into vectors
  7439. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  7440. for (size_t i = 0; i < n_rules; i++) {
  7441. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  7442. vec_rules[i].push_back(*pos);
  7443. }
  7444. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  7445. }
  7446. // loop over alternates of start rule to build initial stacks
  7447. std::vector<std::vector<const llama_grammar_element *>> stacks;
  7448. pos = rules[start_rule_index];
  7449. do {
  7450. std::vector<const llama_grammar_element *> stack;
  7451. if (!llama_grammar_is_end_of_sequence(pos)) {
  7452. // if alternate is nonempty, add to stack
  7453. stack.push_back(pos);
  7454. }
  7455. llama_grammar_advance_stack(vec_rules, stack, stacks);
  7456. while (!llama_grammar_is_end_of_sequence(pos)) {
  7457. // scan to end of alternate def
  7458. pos++;
  7459. }
  7460. if (pos->type == LLAMA_GRETYPE_ALT) {
  7461. // there's another alternate def of this rule to process
  7462. pos++;
  7463. } else {
  7464. break;
  7465. }
  7466. } while (true);
  7467. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  7468. }
  7469. void llama_grammar_free(struct llama_grammar * grammar) {
  7470. delete grammar;
  7471. }
  7472. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  7473. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  7474. // redirect elements in stacks to point to new rules
  7475. for (size_t is = 0; is < result->stacks.size(); is++) {
  7476. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  7477. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  7478. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  7479. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  7480. result->stacks[is][ie] = &result->rules[ir0][ir1];
  7481. }
  7482. }
  7483. }
  7484. }
  7485. }
  7486. return result;
  7487. }
  7488. //
  7489. // sampling
  7490. //
  7491. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  7492. if (seed == LLAMA_DEFAULT_SEED) {
  7493. seed = time(NULL);
  7494. }
  7495. ctx->rng.seed(seed);
  7496. }
  7497. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  7498. GGML_ASSERT(candidates->size > 0);
  7499. const int64_t t_start_sample_us = ggml_time_us();
  7500. // Sort the logits in descending order
  7501. if (!candidates->sorted) {
  7502. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  7503. return a.logit > b.logit;
  7504. });
  7505. candidates->sorted = true;
  7506. }
  7507. float max_l = candidates->data[0].logit;
  7508. float cum_sum = 0.0f;
  7509. for (size_t i = 0; i < candidates->size; ++i) {
  7510. float p = expf(candidates->data[i].logit - max_l);
  7511. candidates->data[i].p = p;
  7512. cum_sum += p;
  7513. }
  7514. for (size_t i = 0; i < candidates->size; ++i) {
  7515. candidates->data[i].p /= cum_sum;
  7516. }
  7517. if (ctx) {
  7518. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7519. }
  7520. }
  7521. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  7522. // TODO: move bucket sort to separate function so that top_p/tail_free/typical/softmax first is equally fast
  7523. // if (k >= (int32_t)candidates->size) {
  7524. // return;
  7525. // }
  7526. const int64_t t_start_sample_us = ggml_time_us();
  7527. if (k <= 0) {
  7528. k = candidates->size;
  7529. }
  7530. k = std::max(k, (int) min_keep);
  7531. k = std::min(k, (int) candidates->size);
  7532. // Sort scores in descending order
  7533. if (!candidates->sorted) {
  7534. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  7535. return a.logit > b.logit;
  7536. };
  7537. if (k <= 128) {
  7538. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  7539. } else {
  7540. constexpr int nbuckets = 128;
  7541. constexpr float bucket_low = -10.0f;
  7542. constexpr float bucket_high = 10.0f;
  7543. constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
  7544. constexpr float bucker_inter = -bucket_low * bucket_scale;
  7545. std::vector<int> bucket_idx(candidates->size);
  7546. std::vector<int> histo(nbuckets, 0);
  7547. for (int i = 0; i < (int)candidates->size; ++i) {
  7548. const float val = candidates->data[i].logit;
  7549. int ib = int(bucket_scale * val + bucker_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
  7550. ib = std::max(0, std::min(nbuckets-1, ib));
  7551. bucket_idx[i] = ib;
  7552. ++histo[ib];
  7553. }
  7554. int nhave = 0;
  7555. int ib = nbuckets - 1;
  7556. for ( ; ib >= 0; --ib) {
  7557. nhave += histo[ib];
  7558. if (nhave >= k) break;
  7559. }
  7560. std::vector<llama_token_data> tmp_tokens(nhave);
  7561. auto ptr = tmp_tokens.data();
  7562. std::vector<llama_token_data*> bucket_ptrs;
  7563. bucket_ptrs.reserve(nbuckets - ib);
  7564. for (int j = nbuckets - 1; j >= ib; --j) {
  7565. bucket_ptrs.push_back(ptr);
  7566. ptr += histo[j];
  7567. }
  7568. for (int i = 0; i < (int)candidates->size; ++i) {
  7569. int j = bucket_idx[i];
  7570. if (j >= ib) {
  7571. *bucket_ptrs[nbuckets-1-j]++ = candidates->data[i];
  7572. }
  7573. }
  7574. ptr = tmp_tokens.data();
  7575. int ndone = 0;
  7576. for (int j = nbuckets-1; j > ib; --j) {
  7577. std::sort(ptr, ptr + histo[j], comp);
  7578. ptr += histo[j];
  7579. ndone += histo[j];
  7580. }
  7581. std::partial_sort(ptr, ptr + k - ndone, ptr + histo[ib], comp);
  7582. std::memcpy(candidates->data, tmp_tokens.data(), k*sizeof(llama_token_data));
  7583. }
  7584. candidates->sorted = true;
  7585. }
  7586. candidates->size = k;
  7587. if (ctx) {
  7588. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7589. }
  7590. }
  7591. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  7592. if (p >= 1.0f) {
  7593. return;
  7594. }
  7595. llama_sample_softmax(ctx, candidates);
  7596. const int64_t t_start_sample_us = ggml_time_us();
  7597. // Compute the cumulative probabilities
  7598. float cum_sum = 0.0f;
  7599. size_t last_idx = candidates->size;
  7600. for (size_t i = 0; i < candidates->size; ++i) {
  7601. cum_sum += candidates->data[i].p;
  7602. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  7603. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  7604. if (cum_sum >= p && i + 1 >= min_keep) {
  7605. last_idx = i + 1;
  7606. break;
  7607. }
  7608. }
  7609. // Resize the output vector to keep only the top-p tokens
  7610. candidates->size = last_idx;
  7611. if (ctx) {
  7612. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7613. }
  7614. }
  7615. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  7616. if (p <= 0.0f || !candidates->size) {
  7617. return;
  7618. }
  7619. const int64_t t_start_sample_us = ggml_time_us();
  7620. bool min_p_applied = false;
  7621. // if the candidates aren't sorted, try the unsorted implementation first
  7622. if (!candidates->sorted) {
  7623. std::vector<llama_token_data> filtered_tokens;
  7624. float max_logit = -FLT_MAX;
  7625. for (size_t i = 0; i < candidates->size; ++i) {
  7626. max_logit = std::max(max_logit, candidates->data[i].logit);
  7627. }
  7628. const float min_logit = max_logit + logf(p); // min logit for p_i >= p * p_max
  7629. for (size_t i = 0; i < candidates->size; ++i) {
  7630. if (candidates->data[i].logit >= min_logit) {
  7631. filtered_tokens.push_back(candidates->data[i]);
  7632. }
  7633. }
  7634. // if we have enough values the operation was a success
  7635. if (filtered_tokens.size() >= min_keep) {
  7636. memcpy(candidates->data, filtered_tokens.data(), filtered_tokens.size()*sizeof(llama_token_data));
  7637. candidates->size = filtered_tokens.size();
  7638. min_p_applied = true;
  7639. }
  7640. }
  7641. // if the candidates are sorted or the unsorted implementation failed, use this implementation
  7642. if (!min_p_applied) {
  7643. // Sort the logits in descending order
  7644. if (!candidates->sorted) {
  7645. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  7646. return a.logit > b.logit;
  7647. });
  7648. candidates->sorted = true;
  7649. }
  7650. const float min_logit = candidates->data[0].logit + logf(p); // min logit for p_i >= p * p_max
  7651. size_t i = 1; // first token always matches
  7652. for (; i < candidates->size; ++i) {
  7653. if (candidates->data[i].logit < min_logit && i >= min_keep) {
  7654. break; // prob too small
  7655. }
  7656. }
  7657. // Resize the output vector to keep only the matching tokens
  7658. candidates->size = i;
  7659. }
  7660. if (ctx) {
  7661. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7662. }
  7663. }
  7664. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  7665. if (z >= 1.0f || candidates->size <= 2) {
  7666. return;
  7667. }
  7668. llama_sample_softmax(nullptr, candidates);
  7669. const int64_t t_start_sample_us = ggml_time_us();
  7670. // Compute the first and second derivatives
  7671. std::vector<float> first_derivatives(candidates->size - 1);
  7672. std::vector<float> second_derivatives(candidates->size - 2);
  7673. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  7674. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  7675. }
  7676. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  7677. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  7678. }
  7679. // Calculate absolute value of second derivatives
  7680. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  7681. second_derivatives[i] = std::abs(second_derivatives[i]);
  7682. }
  7683. // Normalize the second derivatives
  7684. {
  7685. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  7686. if (second_derivatives_sum > 1e-6f) {
  7687. for (float & value : second_derivatives) {
  7688. value /= second_derivatives_sum;
  7689. }
  7690. } else {
  7691. for (float & value : second_derivatives) {
  7692. value = 1.0f / second_derivatives.size();
  7693. }
  7694. }
  7695. }
  7696. float cum_sum = 0.0f;
  7697. size_t last_idx = candidates->size;
  7698. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  7699. cum_sum += second_derivatives[i];
  7700. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  7701. if (cum_sum > z && i >= min_keep) {
  7702. last_idx = i;
  7703. break;
  7704. }
  7705. }
  7706. // Resize the output vector to keep only the tokens above the tail location
  7707. candidates->size = last_idx;
  7708. if (ctx) {
  7709. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7710. }
  7711. }
  7712. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  7713. // Reference implementation:
  7714. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  7715. if (p >= 1.0f) {
  7716. return;
  7717. }
  7718. // Compute the softmax of logits and calculate entropy
  7719. llama_sample_softmax(nullptr, candidates);
  7720. const int64_t t_start_sample_us = ggml_time_us();
  7721. float entropy = 0.0f;
  7722. for (size_t i = 0; i < candidates->size; ++i) {
  7723. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  7724. }
  7725. // Compute the absolute difference between negative log probability and entropy for each candidate
  7726. std::vector<float> shifted_scores;
  7727. for (size_t i = 0; i < candidates->size; ++i) {
  7728. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  7729. shifted_scores.push_back(shifted_score);
  7730. }
  7731. // Sort tokens based on the shifted_scores and their corresponding indices
  7732. std::vector<size_t> indices(candidates->size);
  7733. std::iota(indices.begin(), indices.end(), 0);
  7734. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  7735. return shifted_scores[a] < shifted_scores[b];
  7736. });
  7737. // Compute the cumulative probabilities
  7738. float cum_sum = 0.0f;
  7739. size_t last_idx = indices.size();
  7740. for (size_t i = 0; i < indices.size(); ++i) {
  7741. size_t idx = indices[i];
  7742. cum_sum += candidates->data[idx].p;
  7743. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  7744. if (cum_sum > p && i >= min_keep - 1) {
  7745. last_idx = i + 1;
  7746. break;
  7747. }
  7748. }
  7749. // Resize the output vector to keep only the locally typical tokens
  7750. std::vector<llama_token_data> new_candidates;
  7751. for (size_t i = 0; i < last_idx; ++i) {
  7752. size_t idx = indices[i];
  7753. new_candidates.push_back(candidates->data[idx]);
  7754. }
  7755. // Replace the data in candidates with the new_candidates data
  7756. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  7757. candidates->size = new_candidates.size();
  7758. candidates->sorted = false;
  7759. if (ctx) {
  7760. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7761. }
  7762. }
  7763. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  7764. const int64_t t_start_sample_us = ggml_time_us();
  7765. // no need to do anything if there is only one (or zero) candidates
  7766. if(candidates_p->size <= 1) {
  7767. return;
  7768. }
  7769. // Calculate maximum possible entropy
  7770. float max_entropy = -logf(1.0f / candidates_p->size);
  7771. llama_sample_softmax(nullptr, candidates_p);
  7772. // Calculate entropy of the softmax probabilities
  7773. float entropy = 0.0f;
  7774. for (size_t i = 0; i < candidates_p->size; ++i) {
  7775. float prob = candidates_p->data[i].p;
  7776. if (prob > 0.0f) { // Ensure no log(0)
  7777. entropy -= prob * logf(prob);
  7778. }
  7779. }
  7780. // Normalize the entropy (max_entropy cannot be 0 here because we checked candidates_p->size != 1 above)
  7781. float normalized_entropy = entropy / max_entropy;
  7782. // Map the normalized entropy to the desired temperature range using the power function
  7783. float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);
  7784. #ifdef DEBUG
  7785. LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
  7786. LLAMA_LOG_INFO("Entropy: %f\n", entropy);
  7787. LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
  7788. LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
  7789. LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
  7790. LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
  7791. #endif
  7792. // Apply the dynamically calculated temperature scaling
  7793. for (size_t i = 0; i < candidates_p->size; ++i) {
  7794. candidates_p->data[i].logit /= dyn_temp;
  7795. }
  7796. // Re-compute softmax probabilities after scaling logits with dynamic temperature
  7797. double max_l_double = candidates_p->data[0].logit;
  7798. double cum_sum_double = 0.0;
  7799. for (size_t i = 0; i < candidates_p->size; ++i) {
  7800. double p = exp(candidates_p->data[i].logit - max_l_double);
  7801. candidates_p->data[i].p = p; // Store the scaled probability
  7802. cum_sum_double += p;
  7803. }
  7804. for (size_t i = 0; i < candidates_p->size; ++i) {
  7805. candidates_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
  7806. }
  7807. #ifdef DEBUG
  7808. // Print the updated top 25 probabilities after temperature scaling
  7809. LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
  7810. for (size_t i = 0; i < 25 && i < candidates_p->size; ++i) {
  7811. LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, candidates_p->data[i].p * 100.0f);
  7812. }
  7813. #endif
  7814. if (ctx) {
  7815. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7816. }
  7817. }
  7818. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  7819. const int64_t t_start_sample_us = ggml_time_us();
  7820. for (size_t i = 0; i < candidates_p->size; ++i) {
  7821. candidates_p->data[i].logit /= temp;
  7822. }
  7823. if (ctx) {
  7824. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7825. }
  7826. }
  7827. void llama_sample_temperature(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  7828. llama_sample_temp(ctx, candidates_p, temp);
  7829. }
  7830. void llama_sample_repetition_penalties(
  7831. struct llama_context * ctx,
  7832. llama_token_data_array * candidates,
  7833. const llama_token * last_tokens,
  7834. size_t penalty_last_n,
  7835. float penalty_repeat,
  7836. float penalty_freq,
  7837. float penalty_present) {
  7838. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  7839. return;
  7840. }
  7841. const int64_t t_start_sample_us = ggml_time_us();
  7842. // Create a frequency map to count occurrences of each token in last_tokens
  7843. std::unordered_map<llama_token, int> token_count;
  7844. for (size_t i = 0; i < penalty_last_n; ++i) {
  7845. token_count[last_tokens[i]]++;
  7846. }
  7847. // Apply frequency and presence penalties to the candidates
  7848. for (size_t i = 0; i < candidates->size; ++i) {
  7849. const auto token_iter = token_count.find(candidates->data[i].id);
  7850. if (token_iter == token_count.end()) {
  7851. continue;
  7852. }
  7853. const int count = token_iter->second;
  7854. // 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.
  7855. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  7856. if (candidates->data[i].logit <= 0) {
  7857. candidates->data[i].logit *= penalty_repeat;
  7858. } else {
  7859. candidates->data[i].logit /= penalty_repeat;
  7860. }
  7861. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  7862. }
  7863. candidates->sorted = false;
  7864. if (ctx) {
  7865. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7866. }
  7867. }
  7868. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  7869. GGML_ASSERT(ctx);
  7870. const int64_t t_start_sample_us = ggml_time_us();
  7871. bool allow_eos = false;
  7872. for (const auto & stack : grammar->stacks) {
  7873. if (stack.empty()) {
  7874. allow_eos = true;
  7875. break;
  7876. }
  7877. }
  7878. const llama_token eos = llama_token_eos(&ctx->model);
  7879. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  7880. candidates_decoded.reserve(candidates->size);
  7881. std::vector<llama_grammar_candidate> candidates_grammar;
  7882. candidates_grammar.reserve(candidates->size);
  7883. for (size_t i = 0; i < candidates->size; ++i) {
  7884. const llama_token id = candidates->data[i].id;
  7885. const std::string piece = llama_token_to_piece(ctx, id);
  7886. if (id == eos) {
  7887. if (!allow_eos) {
  7888. candidates->data[i].logit = -INFINITY;
  7889. }
  7890. } else if (piece.empty() || piece[0] == 0) {
  7891. candidates->data[i].logit = -INFINITY;
  7892. } else {
  7893. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  7894. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  7895. }
  7896. }
  7897. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  7898. for (const auto & reject : rejects) {
  7899. candidates->data[reject.index].logit = -INFINITY;
  7900. }
  7901. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7902. }
  7903. static void llama_log_softmax(float * array, size_t size) {
  7904. float max_l = *std::max_element(array, array + size);
  7905. float sum = 0.f;
  7906. for (size_t i = 0; i < size; ++i) {
  7907. float p = expf(array[i] - max_l);
  7908. sum += p;
  7909. array[i] = p;
  7910. }
  7911. for (size_t i = 0; i < size; ++i) {
  7912. array[i] = logf(array[i] / sum);
  7913. }
  7914. }
  7915. void llama_sample_apply_guidance(
  7916. struct llama_context * ctx,
  7917. float * logits,
  7918. float * logits_guidance,
  7919. float scale) {
  7920. GGML_ASSERT(ctx);
  7921. const auto t_start_sample_us = ggml_time_us();
  7922. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  7923. llama_log_softmax(logits, n_vocab);
  7924. llama_log_softmax(logits_guidance, n_vocab);
  7925. for (int i = 0; i < n_vocab; ++i) {
  7926. auto & l = logits[i];
  7927. const auto & g = logits_guidance[i];
  7928. l = scale * (l - g) + g;
  7929. }
  7930. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7931. }
  7932. void llama_sample_classifier_free_guidance(
  7933. struct llama_context * ctx,
  7934. llama_token_data_array * candidates,
  7935. struct llama_context * guidance_ctx,
  7936. float scale) {
  7937. GGML_ASSERT(ctx);
  7938. int64_t t_start_sample_us;
  7939. t_start_sample_us = ggml_time_us();
  7940. const size_t n_vocab = llama_n_vocab(llama_get_model(ctx));
  7941. GGML_ASSERT(n_vocab == candidates->size);
  7942. GGML_ASSERT(!candidates->sorted);
  7943. std::vector<float> logits_base(n_vocab);
  7944. for (size_t i = 0; i < n_vocab; ++i) {
  7945. logits_base[i] = candidates->data[i].logit;
  7946. }
  7947. float * logits_guidance = llama_get_logits(guidance_ctx);
  7948. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7949. llama_sample_apply_guidance(ctx, logits_base.data(), logits_guidance, scale);
  7950. t_start_sample_us = ggml_time_us();
  7951. for (size_t i = 0; i < n_vocab; ++i) {
  7952. candidates->data[i].logit = logits_base[i];
  7953. }
  7954. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7955. }
  7956. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  7957. GGML_ASSERT(ctx);
  7958. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  7959. int64_t t_start_sample_us;
  7960. t_start_sample_us = ggml_time_us();
  7961. llama_sample_softmax(nullptr, candidates);
  7962. // Estimate s_hat using the most probable m tokens
  7963. float s_hat = 0.0;
  7964. float sum_ti_bi = 0.0;
  7965. float sum_ti_sq = 0.0;
  7966. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  7967. float t_i = logf(float(i + 2) / float(i + 1));
  7968. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  7969. sum_ti_bi += t_i * b_i;
  7970. sum_ti_sq += t_i * t_i;
  7971. }
  7972. s_hat = sum_ti_bi / sum_ti_sq;
  7973. // Compute k from the estimated s_hat and target surprise value
  7974. float epsilon_hat = s_hat - 1;
  7975. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  7976. // Sample the next word X using top-k sampling
  7977. llama_sample_top_k(nullptr, candidates, int(k), 1);
  7978. if (ctx) {
  7979. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7980. }
  7981. llama_token X = llama_sample_token(ctx, candidates);
  7982. t_start_sample_us = ggml_time_us();
  7983. // Compute error as the difference between observed surprise and target surprise value
  7984. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  7985. return candidate.id == X;
  7986. }));
  7987. float observed_surprise = -log2f(candidates->data[X_idx].p);
  7988. float e = observed_surprise - tau;
  7989. // Update mu using the learning rate and error
  7990. *mu = *mu - eta * e;
  7991. if (ctx) {
  7992. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7993. }
  7994. return X;
  7995. }
  7996. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  7997. int64_t t_start_sample_us;
  7998. t_start_sample_us = ggml_time_us();
  7999. llama_sample_softmax(ctx, candidates);
  8000. // Truncate the words with surprise values greater than mu
  8001. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  8002. return -log2f(candidate.p) > *mu;
  8003. }));
  8004. if (candidates->size == 0) {
  8005. candidates->size = 1;
  8006. }
  8007. if (ctx) {
  8008. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8009. }
  8010. // Normalize the probabilities of the remaining words
  8011. llama_sample_softmax(ctx, candidates);
  8012. // Sample the next word X from the remaining words
  8013. llama_token X = llama_sample_token(ctx, candidates);
  8014. t_start_sample_us = ggml_time_us();
  8015. // Compute error as the difference between observed surprise and target surprise value
  8016. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  8017. return candidate.id == X;
  8018. }));
  8019. float observed_surprise = -log2f(candidates->data[X_idx].p);
  8020. float e = observed_surprise - tau;
  8021. // Update mu using the learning rate and error
  8022. *mu = *mu - eta * e;
  8023. if (ctx) {
  8024. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8025. }
  8026. return X;
  8027. }
  8028. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  8029. const int64_t t_start_sample_us = ggml_time_us();
  8030. // Find max element
  8031. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  8032. return a.logit < b.logit;
  8033. });
  8034. llama_token result = max_iter->id;
  8035. if (ctx) {
  8036. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8037. ctx->n_sample++;
  8038. }
  8039. return result;
  8040. }
  8041. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  8042. GGML_ASSERT(ctx);
  8043. const int64_t t_start_sample_us = ggml_time_us();
  8044. llama_sample_softmax(nullptr, candidates);
  8045. std::vector<float> probs;
  8046. probs.reserve(candidates->size);
  8047. for (size_t i = 0; i < candidates->size; ++i) {
  8048. probs.push_back(candidates->data[i].p);
  8049. }
  8050. std::discrete_distribution<> dist(probs.begin(), probs.end());
  8051. auto & rng = ctx->rng;
  8052. int idx = dist(rng);
  8053. llama_token result = candidates->data[idx].id;
  8054. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8055. ctx->n_sample++;
  8056. return result;
  8057. }
  8058. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  8059. const int64_t t_start_sample_us = ggml_time_us();
  8060. if (token == llama_token_eos(&ctx->model)) {
  8061. for (const auto & stack : grammar->stacks) {
  8062. if (stack.empty()) {
  8063. return;
  8064. }
  8065. }
  8066. GGML_ASSERT(false);
  8067. }
  8068. const std::string piece = llama_token_to_piece(ctx, token);
  8069. // Note terminating 0 in decoded string
  8070. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  8071. const auto & code_points = decoded.first;
  8072. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  8073. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  8074. }
  8075. grammar->partial_utf8 = decoded.second;
  8076. GGML_ASSERT(!grammar->stacks.empty());
  8077. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8078. }
  8079. //
  8080. // Beam search
  8081. //
  8082. struct llama_beam {
  8083. std::vector<llama_token> tokens;
  8084. float p; // Cumulative beam probability (renormalized relative to all beams)
  8085. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  8086. // Sort beams by probability. In case of ties, prefer beams at eob.
  8087. bool operator<(const llama_beam & rhs) const {
  8088. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  8089. }
  8090. // Shift off first n tokens and discard them.
  8091. void shift_tokens(const size_t n) {
  8092. if (n) {
  8093. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  8094. tokens.resize(tokens.size() - n);
  8095. }
  8096. }
  8097. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  8098. };
  8099. // A struct for calculating logit-related info.
  8100. struct llama_logit_info {
  8101. const float * const logits;
  8102. const int n_vocab;
  8103. const float max_l;
  8104. const float normalizer;
  8105. struct sum_exp {
  8106. float max_l;
  8107. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  8108. };
  8109. llama_logit_info(llama_context * ctx)
  8110. : logits(llama_get_logits(ctx))
  8111. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  8112. , max_l(*std::max_element(logits, logits + n_vocab))
  8113. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  8114. { }
  8115. llama_token_data get_token_data(const llama_token token_id) const {
  8116. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  8117. return {token_id, logits[token_id], p};
  8118. }
  8119. // Return top k token_data by logit.
  8120. std::vector<llama_token_data> top_k(size_t k) {
  8121. std::vector<llama_token_data> min_heap; // min-heap by logit
  8122. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  8123. min_heap.reserve(k_min);
  8124. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  8125. min_heap.push_back(get_token_data(token_id));
  8126. }
  8127. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  8128. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  8129. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  8130. if (min_heap.front().logit < logits[token_id]) {
  8131. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  8132. min_heap.back().id = token_id;
  8133. min_heap.back().logit = logits[token_id];
  8134. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  8135. }
  8136. }
  8137. return min_heap;
  8138. }
  8139. float probability_from_logit(float logit) const {
  8140. return normalizer * std::exp(logit - max_l);
  8141. }
  8142. };
  8143. struct llama_beam_search_data {
  8144. llama_context * ctx;
  8145. size_t n_beams;
  8146. int n_past;
  8147. int n_predict;
  8148. std::vector<llama_beam> beams;
  8149. std::vector<llama_beam> next_beams;
  8150. // Re-calculated on each loop iteration
  8151. size_t common_prefix_length;
  8152. // Used to communicate to/from callback on beams state.
  8153. std::vector<llama_beam_view> beam_views;
  8154. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  8155. : ctx(ctx)
  8156. , n_beams(n_beams)
  8157. , n_past(n_past)
  8158. , n_predict(n_predict)
  8159. , beam_views(n_beams) {
  8160. beams.reserve(n_beams);
  8161. next_beams.reserve(n_beams);
  8162. }
  8163. // Collapse beams to a single beam given by index.
  8164. void collapse_beams(const size_t beam_idx) {
  8165. if (0u < beam_idx) {
  8166. std::swap(beams[0], beams[beam_idx]);
  8167. }
  8168. beams.resize(1);
  8169. }
  8170. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  8171. // The repetitive patterns below reflect the 2 stages of heaps:
  8172. // * Gather elements until the vector is full, then call std::make_heap() on it.
  8173. // * If the heap is full and a new element is found that should be included, pop the
  8174. // least element to the back(), replace it with the new, then push it into the heap.
  8175. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  8176. // Min-heaps use a greater-than comparator.
  8177. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  8178. if (beam.eob) {
  8179. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  8180. if (next_beams.size() < n_beams) {
  8181. next_beams.push_back(std::move(beam));
  8182. if (next_beams.size() == n_beams) {
  8183. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  8184. }
  8185. } else if (next_beams.front().p < beam.p) {
  8186. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8187. next_beams.back() = std::move(beam);
  8188. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8189. }
  8190. } else {
  8191. // beam is not at end-of-sentence, so branch with next top_k tokens.
  8192. if (!beam.tokens.empty()) {
  8193. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  8194. }
  8195. llama_logit_info logit_info(ctx);
  8196. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  8197. size_t i=0;
  8198. if (next_beams.size() < n_beams) {
  8199. for (; next_beams.size() < n_beams ; ++i) {
  8200. llama_beam next_beam = beam;
  8201. next_beam.tokens.push_back(next_tokens[i].id);
  8202. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  8203. next_beams.push_back(std::move(next_beam));
  8204. }
  8205. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  8206. } else {
  8207. for (; next_beams.front().p == 0.0f ; ++i) {
  8208. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8209. next_beams.back() = beam;
  8210. next_beams.back().tokens.push_back(next_tokens[i].id);
  8211. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  8212. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8213. }
  8214. }
  8215. for (; i < n_beams ; ++i) {
  8216. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  8217. if (next_beams.front().p < next_p) {
  8218. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8219. next_beams.back() = beam;
  8220. next_beams.back().tokens.push_back(next_tokens[i].id);
  8221. next_beams.back().p = next_p;
  8222. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8223. }
  8224. }
  8225. }
  8226. }
  8227. // Find common_prefix_length based on beams.
  8228. // Requires beams is not empty.
  8229. size_t find_common_prefix_length() {
  8230. size_t common_prefix_length = beams[0].tokens.size();
  8231. for (size_t i = 1 ; i < beams.size() ; ++i) {
  8232. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  8233. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  8234. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  8235. common_prefix_length = j;
  8236. break;
  8237. }
  8238. }
  8239. }
  8240. return common_prefix_length;
  8241. }
  8242. // Construct beams_state to send back to caller via the callback function.
  8243. // Side effect: set common_prefix_length = find_common_prefix_length();
  8244. llama_beams_state get_beams_state(const bool last_call) {
  8245. for (size_t i = 0 ; i < beams.size() ; ++i) {
  8246. beam_views[i] = beams[i].view();
  8247. }
  8248. common_prefix_length = find_common_prefix_length();
  8249. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  8250. }
  8251. // Loop:
  8252. // * while i < n_predict, AND
  8253. // * any of the beams have not yet reached end-of-beam (eob), AND
  8254. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  8255. // (since all other beam probabilities can only decrease)
  8256. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  8257. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  8258. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  8259. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  8260. !beams[top_beam_index()].eob ; ++i) {
  8261. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  8262. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  8263. if (common_prefix_length) {
  8264. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  8265. n_past += common_prefix_length;
  8266. }
  8267. // Zero-out next_beam probabilities to place them last in following min-heap.
  8268. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  8269. for (llama_beam & beam : beams) {
  8270. beam.shift_tokens(common_prefix_length);
  8271. fill_next_beams_by_top_probabilities(beam);
  8272. }
  8273. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  8274. beams.swap(next_beams);
  8275. renormalize_beam_probabilities(beams);
  8276. }
  8277. collapse_beams(top_beam_index());
  8278. callback(callback_data, get_beams_state(true));
  8279. }
  8280. // As beams grow, the cumulative probabilities decrease.
  8281. // Renormalize them to avoid floating point underflow.
  8282. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  8283. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  8284. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  8285. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  8286. }
  8287. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  8288. size_t top_beam_index() {
  8289. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  8290. }
  8291. // Copy (p,eob) for each beam which may have been changed by the callback.
  8292. void update_beams_from_beam_views() {
  8293. for (size_t i = 0 ; i < beams.size() ; ++i) {
  8294. beams[i].p = beam_views[i].p;
  8295. beams[i].eob = beam_views[i].eob;
  8296. }
  8297. }
  8298. };
  8299. void llama_beam_search(llama_context * ctx,
  8300. llama_beam_search_callback_fn_t callback, void * callback_data,
  8301. size_t n_beams, int n_past, int n_predict) {
  8302. assert(ctx);
  8303. const int64_t t_start_sample_us = ggml_time_us();
  8304. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  8305. beam_search_data.loop(callback, callback_data);
  8306. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8307. ctx->n_sample++;
  8308. }
  8309. //
  8310. // quantization
  8311. //
  8312. struct quantize_state_internal {
  8313. const llama_model & model;
  8314. const llama_model_quantize_params * params;
  8315. int n_attention_wv = 0;
  8316. int n_ffn_down = 0;
  8317. int n_ffn_gate = 0;
  8318. int n_ffn_up = 0;
  8319. int i_attention_wv = 0;
  8320. int i_ffn_down = 0;
  8321. int i_ffn_gate = 0;
  8322. int i_ffn_up = 0;
  8323. int n_k_quantized = 0;
  8324. int n_fallback = 0;
  8325. bool has_imatrix = false;
  8326. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  8327. : model(model)
  8328. , params(params)
  8329. {}
  8330. };
  8331. static void llama_convert_tensor_internal(
  8332. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  8333. const size_t nelements, const int nthread
  8334. ) {
  8335. if (output.size() < nelements) {
  8336. output.resize(nelements);
  8337. }
  8338. float * f32_output = (float *) output.data();
  8339. ggml_type_traits_t qtype;
  8340. if (ggml_is_quantized(tensor->type)) {
  8341. qtype = ggml_internal_get_type_traits(tensor->type);
  8342. if (qtype.to_float == NULL) {
  8343. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  8344. }
  8345. } else if (tensor->type != GGML_TYPE_F16) {
  8346. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  8347. }
  8348. if (nthread < 2) {
  8349. if (tensor->type == GGML_TYPE_F16) {
  8350. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  8351. } else if (ggml_is_quantized(tensor->type)) {
  8352. qtype.to_float(tensor->data, f32_output, nelements);
  8353. } else {
  8354. GGML_ASSERT(false); // unreachable
  8355. }
  8356. return;
  8357. }
  8358. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  8359. size_t block_size_bytes = ggml_type_size(tensor->type);
  8360. GGML_ASSERT(nelements % block_size == 0);
  8361. size_t nblocks = nelements / block_size;
  8362. size_t blocks_per_thread = nblocks / nthread;
  8363. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  8364. size_t in_buff_offs = 0;
  8365. size_t out_buff_offs = 0;
  8366. for (int tnum = 0; tnum < nthread; tnum++) {
  8367. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  8368. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  8369. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  8370. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  8371. if (typ == GGML_TYPE_F16) {
  8372. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  8373. } else {
  8374. qtype.to_float(inbuf, outbuf, nels);
  8375. }
  8376. };
  8377. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  8378. in_buff_offs += thr_block_bytes;
  8379. out_buff_offs += thr_elems;
  8380. }
  8381. for (auto & w : workers) { w.join(); }
  8382. workers.clear();
  8383. }
  8384. static ggml_type get_k_quant_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  8385. const std::string name = ggml_get_name(tensor);
  8386. // TODO: avoid hardcoded tensor names - use the TN_* constants
  8387. const llm_arch arch = qs.model.arch;
  8388. const auto tn = LLM_TN(arch);
  8389. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  8390. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  8391. };
  8392. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  8393. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  8394. if (n_expert > 1) {
  8395. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  8396. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  8397. // for getting the current layer as I initially thought, and we need to resort to parsing the
  8398. // tensor name.
  8399. n_layer /= n_expert;
  8400. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  8401. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  8402. }
  8403. if (i_layer < 0 || i_layer >= n_layer) {
  8404. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  8405. }
  8406. }
  8407. return std::make_pair(i_layer, n_layer);
  8408. };
  8409. if (name == tn(LLM_TENSOR_OUTPUT, "weight")) {
  8410. int nx = tensor->ne[0];
  8411. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  8412. new_type = GGML_TYPE_Q8_0;
  8413. }
  8414. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS) {
  8415. new_type = GGML_TYPE_Q5_K;
  8416. }
  8417. else if (new_type != GGML_TYPE_Q8_0) {
  8418. new_type = GGML_TYPE_Q6_K;
  8419. }
  8420. } else if (name == "token_embd.weight") {
  8421. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS) {
  8422. new_type = GGML_TYPE_Q2_K;
  8423. }
  8424. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  8425. new_type = GGML_TYPE_Q4_K;
  8426. }
  8427. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS) {
  8428. if (name.find("attn_v.weight") != std::string::npos) {
  8429. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  8430. else new_type = GGML_TYPE_Q2_K;
  8431. ++qs.i_attention_wv;
  8432. }
  8433. else if (name.find("ffn_down") != std::string::npos) {
  8434. if (qs.i_ffn_down < qs.n_ffn_down/8) new_type = GGML_TYPE_Q2_K;
  8435. ++qs.i_ffn_down;
  8436. }
  8437. } else if (name.find("attn_v.weight") != std::string::npos) {
  8438. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  8439. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  8440. }
  8441. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  8442. new_type = GGML_TYPE_Q4_K;
  8443. }
  8444. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  8445. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_Q3_K : GGML_TYPE_IQ3_XXS;
  8446. }
  8447. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  8448. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  8449. }
  8450. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  8451. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  8452. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  8453. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  8454. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  8455. (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;
  8456. if (qs.model.type == MODEL_70B) {
  8457. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  8458. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  8459. // nearly negligible increase in model size by quantizing this tensor with more bits:
  8460. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  8461. }
  8462. if (qs.model.hparams.n_expert == 8) {
  8463. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  8464. // TODO: explore better strategies
  8465. new_type = GGML_TYPE_Q8_0;
  8466. }
  8467. ++qs.i_attention_wv;
  8468. } else if (name.find("attn_k.weight") != std::string::npos) {
  8469. if (qs.model.hparams.n_expert == 8) {
  8470. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  8471. // TODO: explore better strategies
  8472. new_type = GGML_TYPE_Q8_0;
  8473. }
  8474. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS) {
  8475. new_type = GGML_TYPE_Q2_K;
  8476. }
  8477. } else if (name.find("ffn_down") != std::string::npos) {
  8478. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  8479. int i_layer = info.first, n_layer = info.second;
  8480. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  8481. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS) {
  8482. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  8483. }
  8484. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  8485. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  8486. }
  8487. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  8488. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  8489. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  8490. : GGML_TYPE_Q3_K;
  8491. }
  8492. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  8493. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  8494. }
  8495. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  8496. if (arch == LLM_ARCH_FALCON) {
  8497. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  8498. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  8499. } else {
  8500. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  8501. }
  8502. }
  8503. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  8504. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  8505. new_type = GGML_TYPE_Q5_K;
  8506. }
  8507. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  8508. && qs.has_imatrix && i_layer < n_layer/8) {
  8509. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  8510. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  8511. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  8512. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  8513. }
  8514. ++qs.i_ffn_down;
  8515. } else if (name.find("attn_output.weight") != std::string::npos) {
  8516. if (arch != LLM_ARCH_FALCON) {
  8517. if (qs.model.hparams.n_expert == 8) {
  8518. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  8519. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ||
  8520. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  8521. new_type = GGML_TYPE_Q5_K;
  8522. }
  8523. } else {
  8524. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  8525. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_Q3_K;
  8526. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) new_type = GGML_TYPE_Q4_K;
  8527. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  8528. }
  8529. } else {
  8530. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  8531. }
  8532. }
  8533. else if (name.find("attn_qkv.weight") != std::string::npos) {
  8534. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  8535. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  8536. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  8537. }
  8538. else if (name.find("ffn_gate") != std::string::npos) {
  8539. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  8540. int i_layer = info.first, n_layer = info.second;
  8541. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS && !use_more_bits(i_layer, n_layer)) {
  8542. new_type = GGML_TYPE_Q2_K;
  8543. }
  8544. ++qs.i_ffn_gate;
  8545. }
  8546. else if (name.find("ffn_up") != std::string::npos) {
  8547. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  8548. int i_layer = info.first, n_layer = info.second;
  8549. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS && !use_more_bits(i_layer, n_layer)) {
  8550. new_type = GGML_TYPE_Q2_K;
  8551. }
  8552. ++qs.i_ffn_up;
  8553. }
  8554. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  8555. //}
  8556. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  8557. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  8558. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  8559. //}
  8560. // This can be used to reduce the size of the Q5_K_S model.
  8561. // The associated PPL increase is fully in line with the size reduction
  8562. //else {
  8563. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  8564. //}
  8565. bool convert_incompatible_tensor = false;
  8566. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  8567. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K ||
  8568. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS ||
  8569. new_type == GGML_TYPE_IQ3_XXS) {
  8570. int nx = tensor->ne[0];
  8571. int ny = tensor->ne[1];
  8572. if (nx % QK_K != 0) {
  8573. 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));
  8574. convert_incompatible_tensor = true;
  8575. } else {
  8576. ++qs.n_k_quantized;
  8577. }
  8578. }
  8579. if (convert_incompatible_tensor) {
  8580. switch (new_type) {
  8581. case GGML_TYPE_IQ2_XXS:
  8582. case GGML_TYPE_IQ2_XS:
  8583. case GGML_TYPE_IQ3_XXS:
  8584. case GGML_TYPE_Q2_K: new_type = GGML_TYPE_Q4_0; break;
  8585. case GGML_TYPE_Q3_K: new_type = GGML_TYPE_Q4_1; break;
  8586. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  8587. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  8588. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  8589. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  8590. }
  8591. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  8592. ++qs.n_fallback;
  8593. }
  8594. return new_type;
  8595. }
  8596. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  8597. ggml_type quantized_type;
  8598. llama_ftype ftype = params->ftype;
  8599. switch (params->ftype) {
  8600. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  8601. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  8602. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  8603. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  8604. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  8605. case LLAMA_FTYPE_MOSTLY_F16: quantized_type = GGML_TYPE_F16; break;
  8606. case LLAMA_FTYPE_ALL_F32: quantized_type = GGML_TYPE_F32; break;
  8607. // K-quants
  8608. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  8609. case LLAMA_FTYPE_MOSTLY_Q2_K: quantized_type = GGML_TYPE_Q2_K; break;
  8610. case LLAMA_FTYPE_MOSTLY_Q3_K_XS:
  8611. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  8612. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  8613. case LLAMA_FTYPE_MOSTLY_Q3_K_L: quantized_type = GGML_TYPE_Q3_K; break;
  8614. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  8615. case LLAMA_FTYPE_MOSTLY_Q4_K_M: quantized_type = GGML_TYPE_Q4_K; break;
  8616. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  8617. case LLAMA_FTYPE_MOSTLY_Q5_K_M: quantized_type = GGML_TYPE_Q5_K; break;
  8618. case LLAMA_FTYPE_MOSTLY_Q6_K: quantized_type = GGML_TYPE_Q6_K; break;
  8619. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: quantized_type = GGML_TYPE_IQ2_XXS; break;
  8620. case LLAMA_FTYPE_MOSTLY_IQ2_XS: quantized_type = GGML_TYPE_IQ2_XS; break;
  8621. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: quantized_type = GGML_TYPE_IQ3_XXS; break;
  8622. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  8623. }
  8624. int nthread = params->nthread;
  8625. if (nthread <= 0) {
  8626. nthread = std::thread::hardware_concurrency();
  8627. }
  8628. // mmap consistently increases speed Linux, and also increases speed on Windows with
  8629. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  8630. #if defined(__linux__) || defined(_WIN32)
  8631. constexpr bool use_mmap = true;
  8632. #else
  8633. constexpr bool use_mmap = false;
  8634. #endif
  8635. llama_model_loader ml(fname_inp, use_mmap, NULL);
  8636. ml.init_mapping(false); // no prefetching?
  8637. llama_model model;
  8638. llm_load_arch(ml, model);
  8639. llm_load_hparams(ml, model);
  8640. struct quantize_state_internal qs(model, params);
  8641. if (params->only_copy) {
  8642. ftype = model.ftype;
  8643. }
  8644. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  8645. if (params->imatrix) {
  8646. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  8647. if (imatrix_data) {
  8648. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  8649. qs.has_imatrix = true;
  8650. }
  8651. }
  8652. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  8653. struct gguf_context * ctx_out = gguf_init_empty();
  8654. // copy the KV pairs from the input file
  8655. gguf_set_kv (ctx_out, ml.ctx_gguf);
  8656. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  8657. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  8658. for (int i = 0; i < ml.n_tensors; ++i) {
  8659. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  8660. const std::string name = ggml_get_name(meta);
  8661. // TODO: avoid hardcoded tensor names - use the TN_* constants
  8662. if (name.find("attn_v.weight") != std::string::npos || name.find("attn_qkv.weight") != std::string::npos) {
  8663. ++qs.n_attention_wv;
  8664. }
  8665. else if (name.find("ffn_down") != std::string::npos) {
  8666. ++qs.n_ffn_down;
  8667. }
  8668. else if (name.find("ffn_gate") != std::string::npos) {
  8669. ++qs.n_ffn_gate;
  8670. }
  8671. else if (name.find("ffn_up") != std::string::npos) {
  8672. ++qs.n_ffn_up;
  8673. }
  8674. }
  8675. if (qs.n_attention_wv != qs.n_ffn_down || (uint32_t)qs.n_attention_wv != model.hparams.n_layer) {
  8676. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_ffn_down = %d, hparams.n_layer = %d\n",
  8677. __func__, qs.n_attention_wv, qs.n_ffn_down, model.hparams.n_layer);
  8678. }
  8679. size_t total_size_org = 0;
  8680. size_t total_size_new = 0;
  8681. std::vector<int64_t> hist_all(1 << 4, 0);
  8682. std::vector<std::thread> workers;
  8683. workers.reserve(nthread);
  8684. std::mutex mutex;
  8685. int idx = 0;
  8686. std::vector<no_init<uint8_t>> read_data;
  8687. std::vector<no_init<uint8_t>> work;
  8688. std::vector<no_init<float>> f32_conv_buf;
  8689. // populate the original tensors so we get an initial meta data
  8690. for (int i = 0; i < ml.n_tensors; ++i) {
  8691. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  8692. gguf_add_tensor(ctx_out, meta);
  8693. }
  8694. std::ofstream fout(fname_out, std::ios::binary);
  8695. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  8696. const size_t meta_size = gguf_get_meta_size(ctx_out);
  8697. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  8698. // placeholder for the meta data
  8699. ::zeros(fout, meta_size);
  8700. for (int i = 0; i < ml.n_tensors; ++i) {
  8701. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  8702. const std::string name = ggml_get_name(tensor);
  8703. if (!ml.use_mmap) {
  8704. if (read_data.size() < ggml_nbytes(tensor)) {
  8705. read_data.resize(ggml_nbytes(tensor));
  8706. }
  8707. tensor->data = read_data.data();
  8708. }
  8709. ml.load_data_for(tensor);
  8710. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  8711. ++idx, ml.n_tensors,
  8712. ggml_get_name(tensor),
  8713. llama_format_tensor_shape(tensor).c_str(),
  8714. ggml_type_name(tensor->type));
  8715. // This used to be a regex, but <regex> has an extreme cost to compile times.
  8716. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  8717. // quantize only 2D tensors
  8718. quantize &= (ggml_n_dims(tensor) == 2);
  8719. quantize &= params->quantize_output_tensor || name != "output.weight";
  8720. quantize &= !params->only_copy;
  8721. // do not quantize expert gating tensors
  8722. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  8723. enum ggml_type new_type;
  8724. void * new_data;
  8725. size_t new_size;
  8726. if (quantize) {
  8727. new_type = quantized_type;
  8728. if (!params->pure) {
  8729. new_type = get_k_quant_type(qs, new_type, tensor, ftype);
  8730. }
  8731. // If we've decided to quantize to the same type the tensor is already
  8732. // in then there's nothing to do.
  8733. quantize = tensor->type != new_type;
  8734. }
  8735. if (!quantize) {
  8736. new_type = tensor->type;
  8737. new_data = tensor->data;
  8738. new_size = ggml_nbytes(tensor);
  8739. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  8740. } else {
  8741. const size_t nelements = ggml_nelements(tensor);
  8742. const float * imatrix = nullptr;
  8743. if (imatrix_data) {
  8744. auto it = imatrix_data->find(tensor->name);
  8745. if (it == imatrix_data->end()) {
  8746. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  8747. } else {
  8748. if (it->second.size() == (size_t)tensor->ne[0]) {
  8749. imatrix = it->second.data();
  8750. } else {
  8751. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  8752. int(it->second.size()), int(tensor->ne[0]), tensor->name);
  8753. }
  8754. }
  8755. }
  8756. if ((new_type == GGML_TYPE_IQ2_XXS ||
  8757. new_type == GGML_TYPE_IQ2_XS ||
  8758. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  8759. LLAMA_LOG_ERROR("\n\n============================================================\n");
  8760. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  8761. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  8762. LLAMA_LOG_ERROR("============================================================\n\n");
  8763. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  8764. }
  8765. float * f32_data;
  8766. if (tensor->type == GGML_TYPE_F32) {
  8767. f32_data = (float *) tensor->data;
  8768. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  8769. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  8770. } else {
  8771. llama_convert_tensor_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  8772. f32_data = (float *) f32_conv_buf.data();
  8773. }
  8774. LLAMA_LOG_INFO("quantizing to %s .. ", ggml_type_name(new_type));
  8775. fflush(stdout);
  8776. if (work.size() < nelements * 4) {
  8777. work.resize(nelements * 4); // upper bound on size
  8778. }
  8779. new_data = work.data();
  8780. std::array<int64_t, 1 << 4> hist_cur = {};
  8781. const int n_per_row = tensor->ne[0];
  8782. const int nrows = nelements / n_per_row;
  8783. static const int min_chunk_size = 32 * 512;
  8784. 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);
  8785. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  8786. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  8787. if (nthread_use < 2) {
  8788. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, hist_cur.data(), imatrix);
  8789. } else {
  8790. int counter = 0;
  8791. new_size = 0;
  8792. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, chunk_size,
  8793. nrows, n_per_row, imatrix]() {
  8794. std::array<int64_t, 1 << 4> local_hist = {};
  8795. const int nrows_per_chunk = chunk_size / n_per_row;
  8796. size_t local_size = 0;
  8797. while (true) {
  8798. std::unique_lock<std::mutex> lock(mutex);
  8799. int first_row = counter; counter += nrows_per_chunk;
  8800. if (first_row >= nrows) {
  8801. if (local_size > 0) {
  8802. for (int j=0; j<int(local_hist.size()); ++j) {
  8803. hist_cur[j] += local_hist[j];
  8804. }
  8805. new_size += local_size;
  8806. }
  8807. break;
  8808. }
  8809. lock.unlock();
  8810. const int this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  8811. local_size += ggml_quantize_chunk(new_type, f32_data, new_data,
  8812. first_row * n_per_row, this_nrow, n_per_row, local_hist.data(), imatrix);
  8813. }
  8814. };
  8815. for (int it = 0; it < nthread_use - 1; ++it) {
  8816. workers.emplace_back(compute);
  8817. }
  8818. compute();
  8819. for (auto & w : workers) { w.join(); }
  8820. workers.clear();
  8821. }
  8822. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  8823. int64_t tot_count = 0;
  8824. for (size_t i = 0; i < hist_cur.size(); i++) {
  8825. hist_all[i] += hist_cur[i];
  8826. tot_count += hist_cur[i];
  8827. }
  8828. if (tot_count > 0) {
  8829. LLAMA_LOG_INFO(" | hist: ");
  8830. for (size_t i = 0; i < hist_cur.size(); i++) {
  8831. LLAMA_LOG_INFO("%5.3f ", hist_cur[i] / float(nelements));
  8832. }
  8833. }
  8834. LLAMA_LOG_INFO("\n");
  8835. }
  8836. total_size_org += ggml_nbytes(tensor);
  8837. total_size_new += new_size;
  8838. // update the gguf meta data as we go
  8839. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  8840. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  8841. // write tensor data + padding
  8842. fout.write((const char *) new_data, new_size);
  8843. zeros(fout, GGML_PAD(new_size, align) - new_size);
  8844. }
  8845. // go back to beginning of file and write the updated meta data
  8846. {
  8847. fout.seekp(0);
  8848. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  8849. gguf_get_meta_data(ctx_out, data.data());
  8850. fout.write((const char *) data.data(), data.size());
  8851. }
  8852. fout.close();
  8853. gguf_free(ctx_out);
  8854. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  8855. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  8856. // print histogram for all tensors
  8857. {
  8858. int64_t sum_all = 0;
  8859. for (size_t i = 0; i < hist_all.size(); i++) {
  8860. sum_all += hist_all[i];
  8861. }
  8862. if (sum_all > 0) {
  8863. LLAMA_LOG_INFO("%s: hist: ", __func__);
  8864. for (size_t i = 0; i < hist_all.size(); i++) {
  8865. LLAMA_LOG_INFO("%5.3f ", hist_all[i] / float(sum_all));
  8866. }
  8867. LLAMA_LOG_INFO("\n");
  8868. }
  8869. }
  8870. if (qs.n_fallback > 0) {
  8871. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) incompatible with k-quants and required fallback quantization\n",
  8872. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  8873. }
  8874. }
  8875. static int llama_apply_lora_from_file_internal(
  8876. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  8877. ) {
  8878. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  8879. const int64_t t_start_lora_us = ggml_time_us();
  8880. llama_file fin(path_lora, "rb");
  8881. // verify magic and version
  8882. {
  8883. uint32_t magic = fin.read_u32();
  8884. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  8885. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  8886. return 1;
  8887. }
  8888. uint32_t format_version = fin.read_u32();
  8889. if (format_version != 1) {
  8890. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  8891. return 1;
  8892. }
  8893. }
  8894. int32_t lora_r = fin.read_u32();
  8895. int32_t lora_alpha = fin.read_u32();
  8896. float scaling = scale * (float)lora_alpha / (float)lora_r;
  8897. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  8898. // load base model
  8899. std::unique_ptr<llama_model_loader> ml;
  8900. if (path_base_model) {
  8901. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  8902. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  8903. ml->init_mapping(/*prefetch*/ false); // no prefetching
  8904. }
  8905. struct tensor_meta {
  8906. std::string name;
  8907. ggml_type type;
  8908. int32_t ne[2];
  8909. size_t offset;
  8910. };
  8911. std::map<std::string, tensor_meta> tensor_meta_map;
  8912. // load all tensor meta
  8913. while (true) {
  8914. if (fin.tell() == fin.size) {
  8915. // eof
  8916. break;
  8917. }
  8918. int32_t n_dims;
  8919. int32_t name_len;
  8920. int32_t ftype;
  8921. fin.read_raw(&n_dims, sizeof(n_dims));
  8922. fin.read_raw(&name_len, sizeof(name_len));
  8923. fin.read_raw(&ftype, sizeof(ftype));
  8924. if (n_dims != 1 && n_dims != 2) {
  8925. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  8926. return 1;
  8927. }
  8928. int32_t ne[2] = { 1, 1 };
  8929. for (int i = 0; i < n_dims; ++i) {
  8930. fin.read_raw(&ne[i], sizeof(ne[i]));
  8931. }
  8932. std::string name;
  8933. {
  8934. GGML_ASSERT(name_len < GGML_MAX_NAME);
  8935. char buf[GGML_MAX_NAME];
  8936. fin.read_raw(buf, name_len);
  8937. name = std::string(buf, name_len);
  8938. }
  8939. // check for lora suffix
  8940. std::string lora_suffix;
  8941. if (name.length() > 6) {
  8942. lora_suffix = name.substr(name.length() - 6);
  8943. }
  8944. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  8945. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  8946. return 1;
  8947. }
  8948. // tensor type
  8949. ggml_type wtype;
  8950. switch (ftype) {
  8951. case 0: wtype = GGML_TYPE_F32; break;
  8952. case 1: wtype = GGML_TYPE_F16; break;
  8953. default:
  8954. {
  8955. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  8956. __func__, ftype);
  8957. return false;
  8958. }
  8959. }
  8960. // data offset
  8961. size_t offset = fin.tell();
  8962. offset = (offset + 31) & -32;
  8963. // skip tensor data
  8964. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  8965. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  8966. }
  8967. bool warned = false;
  8968. int n_tensors = 0;
  8969. // apply
  8970. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  8971. if (backend_cpu == nullptr) {
  8972. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  8973. return 1;
  8974. }
  8975. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  8976. std::vector<no_init<uint8_t>> read_buf;
  8977. for (const auto & it : model.tensors_by_name) {
  8978. const std::string & base_name = it.first;
  8979. ggml_tensor * model_t = it.second;
  8980. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  8981. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  8982. continue;
  8983. }
  8984. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  8985. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  8986. ggml_init_params lora_init_params = {
  8987. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  8988. /* .mem_buffer */ nullptr,
  8989. /* .no_alloc */ true,
  8990. };
  8991. ggml_context * lora_ctx = ggml_init(lora_init_params);
  8992. if (lora_ctx == nullptr) {
  8993. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  8994. ggml_backend_free(backend_cpu);
  8995. return 1;
  8996. }
  8997. // create tensors
  8998. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  8999. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  9000. ggml_set_name(loraA, metaA.name.c_str());
  9001. ggml_set_name(loraB, metaB.name.c_str());
  9002. ggml_tensor * base_t;
  9003. if (ml) {
  9004. if (gguf_find_tensor(ml->ctx_gguf, base_name.c_str()) < 0) {
  9005. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  9006. return 1;
  9007. }
  9008. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  9009. } else {
  9010. base_t = ggml_dup_tensor(lora_ctx, model_t);
  9011. }
  9012. ggml_set_name(base_t, base_name.c_str());
  9013. // allocate in backend buffer
  9014. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  9015. if (lora_buf == nullptr) {
  9016. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  9017. return 1;
  9018. }
  9019. // load tensor data
  9020. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  9021. read_buf.resize(ggml_nbytes(tensor));
  9022. fin.seek(tensor_meta.offset, SEEK_SET);
  9023. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  9024. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  9025. };
  9026. load_tensor(metaA, loraA);
  9027. load_tensor(metaB, loraB);
  9028. // load base model tensor data
  9029. if (ml) {
  9030. ml->load_data_for(base_t);
  9031. } else {
  9032. ggml_backend_tensor_copy(model_t, base_t);
  9033. }
  9034. if (ggml_is_quantized(base_t->type) && !warned) {
  9035. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  9036. "use a f16 or f32 base model with --lora-base\n", __func__);
  9037. warned = true;
  9038. }
  9039. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  9040. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  9041. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  9042. ggml_free(lora_ctx);
  9043. ggml_backend_buffer_free(lora_buf);
  9044. ggml_backend_free(backend_cpu);
  9045. return 1;
  9046. }
  9047. auto build_lora_graph = [&]() {
  9048. // w = w + BA*s
  9049. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  9050. ggml_set_name(BA, "BA");
  9051. if (scaling != 1.0f) {
  9052. BA = ggml_scale(lora_ctx, BA, scaling);
  9053. ggml_set_name(BA, "BA_scaled");
  9054. }
  9055. ggml_tensor * r;
  9056. r = ggml_add_inplace(lora_ctx, base_t, BA);
  9057. ggml_set_name(r, "r_add");
  9058. if (base_t->type != model_t->type) {
  9059. // convert the result to the model type
  9060. r = ggml_cast(lora_ctx, r, model_t->type);
  9061. ggml_set_name(r, "r_cast");
  9062. }
  9063. return r;
  9064. };
  9065. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  9066. ggml_tensor * r = build_lora_graph();
  9067. ggml_build_forward_expand(gf, r);
  9068. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  9069. if (graph_buf == nullptr) {
  9070. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  9071. ggml_free(lora_ctx);
  9072. ggml_backend_buffer_free(lora_buf);
  9073. ggml_backend_free(backend_cpu);
  9074. return 1;
  9075. }
  9076. ggml_backend_graph_compute(backend_cpu, gf);
  9077. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  9078. #if 0
  9079. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  9080. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  9081. // sched compute
  9082. ggml_build_forward_expand(gf, build_graph());
  9083. ggml_backend_sched_init_measure(sched, gf);
  9084. // create the graph again, since the previous one was destroyed by the measure
  9085. ggml_graph_clear(gf);
  9086. ggml_build_forward_expand(gf, build_graph());
  9087. ggml_backend_sched_graph_compute(sched, gf);
  9088. ggml_backend_sched_free(sched);
  9089. #endif
  9090. ggml_backend_buffer_free(lora_buf);
  9091. ggml_backend_buffer_free(graph_buf);
  9092. ggml_free(lora_ctx);
  9093. n_tensors++;
  9094. if (n_tensors % 4 == 0) {
  9095. LLAMA_LOG_INFO(".");
  9096. }
  9097. }
  9098. ggml_backend_free(backend_cpu);
  9099. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  9100. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  9101. return 0;
  9102. }
  9103. //
  9104. // interface implementation
  9105. //
  9106. struct llama_model_params llama_model_default_params() {
  9107. struct llama_model_params result = {
  9108. /*.n_gpu_layers =*/ 0,
  9109. /*.split_mode =*/ LLAMA_SPLIT_LAYER,
  9110. /*.main_gpu =*/ 0,
  9111. /*.tensor_split =*/ nullptr,
  9112. /*.progress_callback =*/ nullptr,
  9113. /*.progress_callback_user_data =*/ nullptr,
  9114. /*.kv_overrides =*/ nullptr,
  9115. /*.vocab_only =*/ false,
  9116. /*.use_mmap =*/ true,
  9117. /*.use_mlock =*/ false,
  9118. };
  9119. #ifdef GGML_USE_METAL
  9120. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  9121. result.n_gpu_layers = 999;
  9122. #endif
  9123. return result;
  9124. }
  9125. struct llama_context_params llama_context_default_params() {
  9126. struct llama_context_params result = {
  9127. /*.seed =*/ LLAMA_DEFAULT_SEED,
  9128. /*.n_ctx =*/ 512,
  9129. /*.n_batch =*/ 512,
  9130. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  9131. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  9132. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_UNSPECIFIED,
  9133. /*.rope_freq_base =*/ 0.0f,
  9134. /*.rope_freq_scale =*/ 0.0f,
  9135. /*.yarn_ext_factor =*/ -1.0f,
  9136. /*.yarn_attn_factor =*/ 1.0f,
  9137. /*.yarn_beta_fast =*/ 32.0f,
  9138. /*.yarn_beta_slow =*/ 1.0f,
  9139. /*.yarn_orig_ctx =*/ 0,
  9140. /*.cb_eval =*/ nullptr,
  9141. /*.cb_eval_user_data =*/ nullptr,
  9142. /*.type_k =*/ GGML_TYPE_F16,
  9143. /*.type_v =*/ GGML_TYPE_F16,
  9144. /*.mul_mat_q =*/ true,
  9145. /*.logits_all =*/ false,
  9146. /*.embedding =*/ false,
  9147. /*.offload_kqv =*/ true,
  9148. };
  9149. return result;
  9150. }
  9151. struct llama_model_quantize_params llama_model_quantize_default_params() {
  9152. struct llama_model_quantize_params result = {
  9153. /*.nthread =*/ 0,
  9154. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  9155. /*.allow_requantize =*/ false,
  9156. /*.quantize_output_tensor =*/ true,
  9157. /*.only_copy =*/ false,
  9158. /*.pure =*/ false,
  9159. /*.imatrix =*/ nullptr,
  9160. };
  9161. return result;
  9162. }
  9163. size_t llama_max_devices(void) {
  9164. #if defined(GGML_USE_METAL)
  9165. return 1;
  9166. #elif defined(GGML_USE_CUBLAS)
  9167. return GGML_CUDA_MAX_DEVICES;
  9168. #elif defined(GGML_USE_SYCL)
  9169. return GGML_SYCL_MAX_DEVICES;
  9170. #elif defined(GGML_USE_VULKAN)
  9171. return GGML_VK_MAX_DEVICES;
  9172. #else
  9173. return 1;
  9174. #endif
  9175. }
  9176. bool llama_supports_mmap(void) {
  9177. return llama_mmap::SUPPORTED;
  9178. }
  9179. bool llama_supports_mlock(void) {
  9180. return llama_mlock::SUPPORTED;
  9181. }
  9182. bool llama_supports_gpu_offload(void) {
  9183. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  9184. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE)
  9185. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  9186. return true;
  9187. #else
  9188. return false;
  9189. #endif
  9190. }
  9191. // deprecated:
  9192. bool llama_mmap_supported(void) {
  9193. return llama_supports_mmap();
  9194. }
  9195. bool llama_mlock_supported(void) {
  9196. return llama_supports_mlock();
  9197. }
  9198. void llama_backend_init(bool numa) {
  9199. ggml_time_init();
  9200. // needed to initialize f16 tables
  9201. {
  9202. struct ggml_init_params params = { 0, NULL, false };
  9203. struct ggml_context * ctx = ggml_init(params);
  9204. ggml_free(ctx);
  9205. }
  9206. if (numa) {
  9207. ggml_numa_init();
  9208. }
  9209. #ifdef GGML_USE_MPI
  9210. ggml_mpi_backend_init();
  9211. #endif
  9212. }
  9213. void llama_backend_free(void) {
  9214. #ifdef GGML_USE_MPI
  9215. ggml_mpi_backend_free();
  9216. #endif
  9217. ggml_quantize_free();
  9218. }
  9219. int64_t llama_time_us(void) {
  9220. return ggml_time_us();
  9221. }
  9222. struct llama_model * llama_load_model_from_file(
  9223. const char * path_model,
  9224. struct llama_model_params params) {
  9225. ggml_time_init();
  9226. llama_model * model = new llama_model;
  9227. unsigned cur_percentage = 0;
  9228. if (params.progress_callback == NULL) {
  9229. params.progress_callback_user_data = &cur_percentage;
  9230. params.progress_callback = [](float progress, void * ctx) {
  9231. unsigned * cur_percentage_p = (unsigned *) ctx;
  9232. unsigned percentage = (unsigned) (100 * progress);
  9233. while (percentage > *cur_percentage_p) {
  9234. *cur_percentage_p = percentage;
  9235. LLAMA_LOG_INFO(".");
  9236. if (percentage >= 100) {
  9237. LLAMA_LOG_INFO("\n");
  9238. }
  9239. }
  9240. return true;
  9241. };
  9242. }
  9243. int status = llama_model_load(path_model, *model, params);
  9244. GGML_ASSERT(status <= 0);
  9245. if (status < 0) {
  9246. if (status == -1) {
  9247. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  9248. } else if (status == -2) {
  9249. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  9250. }
  9251. delete model;
  9252. return nullptr;
  9253. }
  9254. return model;
  9255. }
  9256. void llama_free_model(struct llama_model * model) {
  9257. delete model;
  9258. }
  9259. struct llama_context * llama_new_context_with_model(
  9260. struct llama_model * model,
  9261. struct llama_context_params params) {
  9262. if (!model) {
  9263. return nullptr;
  9264. }
  9265. llama_context * ctx = new llama_context(*model);
  9266. const auto & hparams = model->hparams;
  9267. auto & cparams = ctx->cparams;
  9268. cparams.n_batch = params.n_batch;
  9269. cparams.n_threads = params.n_threads;
  9270. cparams.n_threads_batch = params.n_threads_batch;
  9271. cparams.yarn_ext_factor = params.yarn_ext_factor;
  9272. cparams.yarn_attn_factor = params.yarn_attn_factor;
  9273. cparams.yarn_beta_fast = params.yarn_beta_fast;
  9274. cparams.yarn_beta_slow = params.yarn_beta_slow;
  9275. cparams.mul_mat_q = params.mul_mat_q;
  9276. cparams.offload_kqv = params.offload_kqv;
  9277. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  9278. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  9279. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  9280. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  9281. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  9282. hparams.n_ctx_train;
  9283. cparams.cb_eval = params.cb_eval;
  9284. cparams.cb_eval_user_data = params.cb_eval_user_data;
  9285. auto rope_scaling_type = params.rope_scaling_type;
  9286. if (rope_scaling_type == LLAMA_ROPE_SCALING_UNSPECIFIED) {
  9287. rope_scaling_type = hparams.rope_scaling_type_train;
  9288. }
  9289. if (rope_scaling_type == LLAMA_ROPE_SCALING_NONE) {
  9290. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  9291. }
  9292. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  9293. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_YARN ? 1.0f : 0.0f;
  9294. }
  9295. if (params.seed == LLAMA_DEFAULT_SEED) {
  9296. params.seed = time(NULL);
  9297. }
  9298. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  9299. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  9300. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  9301. ctx->rng = std::mt19937(params.seed);
  9302. ctx->logits_all = params.logits_all;
  9303. const ggml_type type_k = params.type_k;
  9304. const ggml_type type_v = params.type_v;
  9305. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  9306. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  9307. if (!hparams.vocab_only) {
  9308. // initialize backends
  9309. #ifdef GGML_USE_METAL
  9310. if (model->n_gpu_layers > 0) {
  9311. ctx->backend_metal = ggml_backend_metal_init();
  9312. if (ctx->backend_metal == nullptr) {
  9313. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  9314. llama_free(ctx);
  9315. return nullptr;
  9316. }
  9317. ctx->backends.push_back(ctx->backend_metal);
  9318. }
  9319. #elif defined(GGML_USE_CUBLAS)
  9320. if (model->n_gpu_layers > 0) {
  9321. // with split_mode LLAMA_SPLIT_NONE or LLAMA_SPLIT_ROW, only the main GPU backend is used
  9322. if (model->split_mode == LLAMA_SPLIT_NONE || model->split_mode == LLAMA_SPLIT_ROW) {
  9323. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  9324. if (backend == nullptr) {
  9325. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  9326. llama_free(ctx);
  9327. return nullptr;
  9328. }
  9329. ctx->backends.push_back(backend);
  9330. } else {
  9331. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  9332. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  9333. ggml_backend_t backend = ggml_backend_cuda_init(device);
  9334. if (backend == nullptr) {
  9335. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  9336. llama_free(ctx);
  9337. return nullptr;
  9338. }
  9339. ctx->backends.push_back(backend);
  9340. }
  9341. }
  9342. }
  9343. #elif defined(GGML_USE_VULKAN)
  9344. if (model->n_gpu_layers > 0) {
  9345. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  9346. ggml_backend_t backend = ggml_backend_vk_init(device);
  9347. if (backend == nullptr) {
  9348. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  9349. llama_free(ctx);
  9350. return nullptr;
  9351. }
  9352. ctx->backends.push_back(backend);
  9353. }
  9354. }
  9355. #elif defined(GGML_USE_SYCL)
  9356. if (model->n_gpu_layers > 0) {
  9357. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  9358. if (backend == nullptr) {
  9359. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d backend\n", __func__, model->main_gpu);
  9360. llama_free(ctx);
  9361. return nullptr;
  9362. }
  9363. ctx->backends.push_back(backend);
  9364. }
  9365. #elif defined(GGML_USE_KOMPUTE)
  9366. if (model->n_gpu_layers > 0) {
  9367. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  9368. if (backend == nullptr) {
  9369. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  9370. llama_free(ctx);
  9371. return nullptr;
  9372. }
  9373. ctx->backends.push_back(backend);
  9374. }
  9375. #endif
  9376. ctx->backend_cpu = ggml_backend_cpu_init();
  9377. if (ctx->backend_cpu == nullptr) {
  9378. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  9379. llama_free(ctx);
  9380. return nullptr;
  9381. }
  9382. ctx->backends.push_back(ctx->backend_cpu);
  9383. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v,
  9384. cparams.n_ctx, cparams.offload_kqv)) {
  9385. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  9386. llama_free(ctx);
  9387. return nullptr;
  9388. }
  9389. {
  9390. size_t memory_size_k = 0;
  9391. size_t memory_size_v = 0;
  9392. for (auto & k : ctx->kv_self.k_l) {
  9393. memory_size_k += ggml_nbytes(k);
  9394. }
  9395. for (auto & v : ctx->kv_self.v_l) {
  9396. memory_size_v += ggml_nbytes(v);
  9397. }
  9398. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  9399. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  9400. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  9401. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  9402. }
  9403. // resized during inference, reserve maximum
  9404. ctx->logits.reserve(hparams.n_vocab*cparams.n_batch);
  9405. if (params.embedding){
  9406. ctx->embedding.resize(hparams.n_embd);
  9407. }
  9408. // graph inputs
  9409. {
  9410. ggml_init_params init_params = {
  9411. /* .mem_size */ ggml_tensor_overhead()*7,
  9412. /* .mem_buffer */ nullptr,
  9413. /* .no_alloc */ true,
  9414. };
  9415. ctx->ctx_input = ggml_init(init_params);
  9416. ctx->inp_tokens = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  9417. ctx->inp_embd = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, hparams.n_embd, cparams.n_batch);
  9418. ctx->inp_pos = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  9419. ctx->inp_KQ_mask = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_ctx, cparams.n_batch);
  9420. ctx->inp_K_shift = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_ctx);
  9421. ctx->inp_sum = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, 1, cparams.n_batch);
  9422. ggml_set_name(ctx->inp_tokens, "inp_tokens");
  9423. ggml_set_name(ctx->inp_embd, "inp_embd");
  9424. ggml_set_name(ctx->inp_pos, "inp_pos");
  9425. ggml_set_name(ctx->inp_KQ_mask, "inp_KQ_mask");
  9426. ggml_set_name(ctx->inp_K_shift, "inp_K_shift");
  9427. ggml_set_name(ctx->inp_sum, "inp_sum");
  9428. ctx->buf_input = ggml_backend_alloc_ctx_tensors_from_buft(ctx->ctx_input, llama_default_buffer_type_cpu(true));
  9429. LLAMA_LOG_INFO("%s: %10s input buffer size = %8.2f MiB\n", __func__,
  9430. ggml_backend_buffer_name(ctx->buf_input),
  9431. ggml_backend_buffer_get_size(ctx->buf_input) / 1024.0 / 1024.0);
  9432. }
  9433. // scheduler and compute buffers
  9434. {
  9435. // buffer types used for the compute buffer of each backend
  9436. std::vector<ggml_backend_buffer_type_t> backend_buft;
  9437. for (auto * backend : ctx->backends) {
  9438. if (ggml_backend_is_cpu(backend)) {
  9439. // use host buffers for the CPU backend compute buffer
  9440. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  9441. } else {
  9442. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  9443. }
  9444. }
  9445. // buffer used to store the computation graph and the tensor meta data
  9446. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead());
  9447. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES);
  9448. // build worst-case graph
  9449. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_batch);
  9450. int n_past = cparams.n_ctx - n_tokens;
  9451. 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
  9452. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  9453. // initialize scheduler with the worst-case graph
  9454. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  9455. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  9456. llama_free(ctx);
  9457. return nullptr;
  9458. }
  9459. for (size_t i = 0; i < ctx->backends.size(); i++) {
  9460. ggml_backend_t backend = ctx->backends[i];
  9461. ggml_backend_buffer_type_t buft = backend_buft[i];
  9462. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  9463. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  9464. ggml_backend_buft_name(buft),
  9465. size / 1024.0 / 1024.0);
  9466. }
  9467. // note: the number of splits during measure is higher than during inference due to the kv shift
  9468. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  9469. LLAMA_LOG_INFO("%s: graph splits (measure): %d\n", __func__, n_splits);
  9470. }
  9471. }
  9472. #ifdef GGML_USE_MPI
  9473. ctx->ctx_mpi = ggml_mpi_init();
  9474. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  9475. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  9476. // TODO: needs fix after #3228
  9477. GGML_ASSERT(false && "not implemented");
  9478. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  9479. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  9480. llama_backend_free();
  9481. exit(1);
  9482. }
  9483. #endif
  9484. return ctx;
  9485. }
  9486. void llama_free(struct llama_context * ctx) {
  9487. delete ctx;
  9488. }
  9489. const llama_model * llama_get_model(const struct llama_context * ctx) {
  9490. return &ctx->model;
  9491. }
  9492. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  9493. return ctx->cparams.n_ctx;
  9494. }
  9495. uint32_t llama_n_batch(const struct llama_context * ctx) {
  9496. return ctx->cparams.n_batch;
  9497. }
  9498. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  9499. return model->vocab.type;
  9500. }
  9501. int32_t llama_n_vocab(const struct llama_model * model) {
  9502. return model->vocab.id_to_token.size();
  9503. }
  9504. int32_t llama_n_ctx_train(const struct llama_model * model) {
  9505. return model->hparams.n_ctx_train;
  9506. }
  9507. int32_t llama_n_embd(const struct llama_model * model) {
  9508. return model->hparams.n_embd;
  9509. }
  9510. float llama_rope_freq_scale_train(const struct llama_model * model) {
  9511. return model->hparams.rope_freq_scale_train;
  9512. }
  9513. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  9514. const auto & it = model->gguf_kv.find(key);
  9515. if (it == model->gguf_kv.end()) {
  9516. if (buf_size > 0) {
  9517. buf[0] = '\0';
  9518. }
  9519. return -1;
  9520. }
  9521. return snprintf(buf, buf_size, "%s", it->second.c_str());
  9522. }
  9523. int32_t llama_model_meta_count(const struct llama_model * model) {
  9524. return (int)model->gguf_kv.size();
  9525. }
  9526. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  9527. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  9528. if (buf_size > 0) {
  9529. buf[0] = '\0';
  9530. }
  9531. return -1;
  9532. }
  9533. auto it = model->gguf_kv.begin();
  9534. std::advance(it, i);
  9535. return snprintf(buf, buf_size, "%s", it->first.c_str());
  9536. }
  9537. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  9538. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  9539. if (buf_size > 0) {
  9540. buf[0] = '\0';
  9541. }
  9542. return -1;
  9543. }
  9544. auto it = model->gguf_kv.begin();
  9545. std::advance(it, i);
  9546. return snprintf(buf, buf_size, "%s", it->second.c_str());
  9547. }
  9548. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  9549. return snprintf(buf, buf_size, "%s %s %s",
  9550. llama_model_arch_name(model->arch),
  9551. llama_model_type_name(model->type),
  9552. llama_model_ftype_name(model->ftype).c_str());
  9553. }
  9554. uint64_t llama_model_size(const struct llama_model * model) {
  9555. uint64_t size = 0;
  9556. for (const auto & it : model->tensors_by_name) {
  9557. size += ggml_nbytes(it.second);
  9558. }
  9559. return size;
  9560. }
  9561. uint64_t llama_model_n_params(const struct llama_model * model) {
  9562. uint64_t nparams = 0;
  9563. for (const auto & it : model->tensors_by_name) {
  9564. nparams += ggml_nelements(it.second);
  9565. }
  9566. return nparams;
  9567. }
  9568. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  9569. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  9570. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  9571. return it.first == name;
  9572. });
  9573. if (it == model->tensors_by_name.end()) {
  9574. return nullptr;
  9575. }
  9576. return it->second;
  9577. }
  9578. uint32_t llama_model_quantize(
  9579. const char * fname_inp,
  9580. const char * fname_out,
  9581. const llama_model_quantize_params * params) {
  9582. try {
  9583. llama_model_quantize_internal(fname_inp, fname_out, params);
  9584. return 0;
  9585. } catch (const std::exception & err) {
  9586. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  9587. return 1;
  9588. }
  9589. }
  9590. int32_t llama_apply_lora_from_file(struct llama_context * ctx, const char * path_lora, float scale, const char * path_base_model, int32_t n_threads) {
  9591. try {
  9592. return llama_apply_lora_from_file_internal(ctx->model, path_lora, scale, path_base_model, n_threads);
  9593. } catch (const std::exception & err) {
  9594. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  9595. return 1;
  9596. }
  9597. }
  9598. 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) {
  9599. try {
  9600. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  9601. } catch (const std::exception & err) {
  9602. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  9603. return 1;
  9604. }
  9605. }
  9606. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_max_seq) {
  9607. struct llama_kv_cache_view result = {
  9608. /*.n_cells = */ 0,
  9609. /*.n_max_seq = */ n_max_seq,
  9610. /*.token_count = */ 0,
  9611. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  9612. /*.max_contiguous = */ 0,
  9613. /*.max_contiguous_idx = */ -1,
  9614. /*.cells = */ nullptr,
  9615. /*.cells_sequences = */ nullptr,
  9616. };
  9617. return result;
  9618. }
  9619. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  9620. if (view->cells != nullptr) {
  9621. free(view->cells);
  9622. view->cells = nullptr;
  9623. }
  9624. if (view->cells_sequences != nullptr) {
  9625. free(view->cells_sequences);
  9626. view->cells_sequences = nullptr;
  9627. }
  9628. }
  9629. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  9630. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  9631. view->n_cells = int32_t(ctx->kv_self.size);
  9632. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  9633. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  9634. view->cells = (struct llama_kv_cache_view_cell *)p;
  9635. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_max_seq * view->n_cells);
  9636. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  9637. view->cells_sequences = (llama_seq_id *)p;
  9638. }
  9639. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  9640. llama_kv_cache_view_cell * c_curr = view->cells;
  9641. llama_seq_id * cs_curr = view->cells_sequences;
  9642. int32_t used_cells = 0;
  9643. int32_t token_count = 0;
  9644. int32_t curr_contig_idx = -1;
  9645. uint32_t max_contig = 0;
  9646. int32_t max_contig_idx = -1;
  9647. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_max_seq) {
  9648. const size_t curr_size = kv_cells[i].seq_id.size();
  9649. token_count += curr_size;
  9650. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  9651. if (curr_size > 0) {
  9652. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  9653. max_contig = i - curr_contig_idx;
  9654. max_contig_idx = curr_contig_idx;
  9655. }
  9656. curr_contig_idx = -1;
  9657. } else if (curr_contig_idx < 0) {
  9658. curr_contig_idx = i;
  9659. }
  9660. int seq_idx = 0;
  9661. for (const llama_seq_id it : kv_cells[i].seq_id) {
  9662. if (seq_idx >= view->n_max_seq) {
  9663. break;
  9664. }
  9665. cs_curr[seq_idx] = it;
  9666. seq_idx++;
  9667. }
  9668. if (seq_idx != 0) {
  9669. used_cells++;
  9670. }
  9671. for (; seq_idx < view->n_max_seq; seq_idx++) {
  9672. cs_curr[seq_idx] = -1;
  9673. }
  9674. }
  9675. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  9676. max_contig_idx = curr_contig_idx;
  9677. max_contig = kv_cells.size() - curr_contig_idx;
  9678. }
  9679. view->max_contiguous = max_contig;
  9680. view->max_contiguous_idx = max_contig_idx;
  9681. view->token_count = token_count;
  9682. view->used_cells = used_cells;
  9683. if (uint32_t(used_cells) != ctx->kv_self.used) {
  9684. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  9685. __func__, ctx->kv_self.used, used_cells);
  9686. }
  9687. }
  9688. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  9689. int result = 0;
  9690. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  9691. result += ctx->kv_self.cells[i].seq_id.size();
  9692. }
  9693. return result;
  9694. }
  9695. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  9696. return ctx->kv_self.used;
  9697. }
  9698. void llama_kv_cache_clear(struct llama_context * ctx) {
  9699. llama_kv_cache_clear(ctx->kv_self);
  9700. }
  9701. void llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  9702. llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  9703. }
  9704. 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) {
  9705. if (seq_id_src == seq_id_dst) {
  9706. return;
  9707. }
  9708. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  9709. }
  9710. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  9711. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  9712. }
  9713. void llama_kv_cache_seq_shift(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  9714. if (delta == 0) {
  9715. return;
  9716. }
  9717. llama_kv_cache_seq_shift(ctx->kv_self, seq_id, p0, p1, delta);
  9718. }
  9719. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  9720. if (d == 1) {
  9721. return;
  9722. }
  9723. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  9724. }
  9725. // Returns the *maximum* size of the state
  9726. size_t llama_get_state_size(const struct llama_context * ctx) {
  9727. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  9728. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  9729. const size_t s_rng_size = sizeof(size_t);
  9730. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  9731. const size_t s_logits_size = sizeof(size_t);
  9732. // assume worst case for logits although only currently set ones are serialized
  9733. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  9734. const size_t s_embedding_size = sizeof(size_t);
  9735. const size_t s_embedding = ctx->embedding.size() * sizeof(float);
  9736. const size_t s_kv_size = sizeof(size_t);
  9737. const size_t s_kv_ntok = sizeof(int);
  9738. const size_t s_kv = ctx->kv_self.total_size();
  9739. const size_t s_total = (
  9740. + s_rng_size
  9741. + s_rng
  9742. + s_logits_size
  9743. + s_logits
  9744. + s_embedding_size
  9745. + s_embedding
  9746. + s_kv_size
  9747. + s_kv_ntok
  9748. + s_kv
  9749. );
  9750. return s_total;
  9751. }
  9752. // llama_context_data
  9753. struct llama_data_context {
  9754. virtual void write(const void * src, size_t size) = 0;
  9755. virtual size_t get_size_written() = 0;
  9756. virtual ~llama_data_context() = default;
  9757. };
  9758. struct llama_data_buffer_context : llama_data_context {
  9759. uint8_t * ptr;
  9760. size_t size_written = 0;
  9761. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  9762. void write(const void * src, size_t size) override {
  9763. memcpy(ptr, src, size);
  9764. ptr += size;
  9765. size_written += size;
  9766. }
  9767. size_t get_size_written() override {
  9768. return size_written;
  9769. }
  9770. };
  9771. struct llama_data_file_context : llama_data_context {
  9772. llama_file * file;
  9773. size_t size_written = 0;
  9774. llama_data_file_context(llama_file * f) : file(f) {}
  9775. void write(const void * src, size_t size) override {
  9776. file->write_raw(src, size);
  9777. size_written += size;
  9778. }
  9779. size_t get_size_written() override {
  9780. return size_written;
  9781. }
  9782. };
  9783. /** copy state data into either a buffer or file depending on the passed in context
  9784. *
  9785. * file context:
  9786. * llama_file file("/path", "wb");
  9787. * llama_data_file_context data_ctx(&file);
  9788. * llama_copy_state_data(ctx, &data_ctx);
  9789. *
  9790. * buffer context:
  9791. * std::vector<uint8_t> buf(max_size, 0);
  9792. * llama_data_buffer_context data_ctx(&buf.data());
  9793. * llama_copy_state_data(ctx, &data_ctx);
  9794. *
  9795. */
  9796. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  9797. // copy rng
  9798. {
  9799. std::ostringstream rng_ss;
  9800. rng_ss << ctx->rng;
  9801. const std::string & rng_str = rng_ss.str();
  9802. const size_t rng_size = rng_str.size();
  9803. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  9804. data_ctx->write(&rng_size, sizeof(rng_size));
  9805. data_ctx->write(rng_str.data(), rng_size);
  9806. }
  9807. // copy logits
  9808. {
  9809. const size_t logits_size = ctx->logits.size();
  9810. data_ctx->write(&logits_size, sizeof(logits_size));
  9811. if (logits_size) {
  9812. data_ctx->write(ctx->logits.data(), logits_size * sizeof(float));
  9813. }
  9814. }
  9815. // copy embeddings
  9816. {
  9817. const size_t embedding_size = ctx->embedding.size();
  9818. data_ctx->write(&embedding_size, sizeof(embedding_size));
  9819. if (embedding_size) {
  9820. data_ctx->write(ctx->embedding.data(), embedding_size * sizeof(float));
  9821. }
  9822. }
  9823. // copy kv cache
  9824. {
  9825. const auto & kv_self = ctx->kv_self;
  9826. const auto & hparams = ctx->model.hparams;
  9827. const auto & cparams = ctx->cparams;
  9828. const auto n_layer = hparams.n_layer;
  9829. const auto n_embd_k_gqa = hparams.n_embd_k_gqa();
  9830. const auto n_embd_v_gqa = hparams.n_embd_v_gqa();
  9831. const auto n_ctx = cparams.n_ctx;
  9832. const size_t kv_buf_size = kv_self.total_size();
  9833. const uint32_t kv_head = kv_self.head;
  9834. const uint32_t kv_size = kv_self.size;
  9835. const uint32_t kv_used = kv_self.used;
  9836. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  9837. data_ctx->write(&kv_head, sizeof(kv_head));
  9838. data_ctx->write(&kv_size, sizeof(kv_size));
  9839. data_ctx->write(&kv_used, sizeof(kv_used));
  9840. if (kv_buf_size) {
  9841. const size_t elt_size = ggml_element_size(kv_self.k_l[0]);
  9842. std::vector<uint8_t> tmp_buf;
  9843. for (int il = 0; il < (int) n_layer; ++il) {
  9844. tmp_buf.resize(elt_size*n_embd_k_gqa*kv_head);
  9845. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  9846. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  9847. // v is not contiguous, copy row by row
  9848. tmp_buf.resize(elt_size*kv_head);
  9849. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  9850. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*elt_size*n_ctx, tmp_buf.size());
  9851. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  9852. }
  9853. }
  9854. }
  9855. for (uint32_t i = 0; i < kv_size; ++i) {
  9856. const auto & cell = kv_self.cells[i];
  9857. const llama_pos pos = cell.pos;
  9858. const size_t seq_id_size = cell.seq_id.size();
  9859. data_ctx->write(&pos, sizeof(pos));
  9860. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  9861. for (auto seq_id : cell.seq_id) {
  9862. data_ctx->write(&seq_id, sizeof(seq_id));
  9863. }
  9864. }
  9865. }
  9866. }
  9867. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  9868. llama_data_buffer_context data_ctx(dst);
  9869. llama_copy_state_data_internal(ctx, &data_ctx);
  9870. return data_ctx.get_size_written();
  9871. }
  9872. // Sets the state reading from the specified source address
  9873. size_t llama_set_state_data(struct llama_context * ctx, uint8_t * src) {
  9874. uint8_t * inp = src;
  9875. // set rng
  9876. {
  9877. size_t rng_size;
  9878. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  9879. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  9880. std::string rng_str((char *)inp, rng_size); inp += rng_size;
  9881. std::istringstream rng_ss(rng_str);
  9882. rng_ss >> ctx->rng;
  9883. GGML_ASSERT(!rng_ss.fail());
  9884. }
  9885. // set logits
  9886. {
  9887. size_t logits_size;
  9888. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  9889. GGML_ASSERT(ctx->logits.capacity() >= logits_size);
  9890. if (logits_size) {
  9891. ctx->logits.resize(logits_size);
  9892. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  9893. inp += logits_size * sizeof(float);
  9894. }
  9895. }
  9896. // set embeddings
  9897. {
  9898. size_t embedding_size;
  9899. memcpy(&embedding_size, inp, sizeof(embedding_size)); inp += sizeof(embedding_size);
  9900. GGML_ASSERT(ctx->embedding.capacity() == embedding_size);
  9901. if (embedding_size) {
  9902. memcpy(ctx->embedding.data(), inp, embedding_size * sizeof(float));
  9903. inp += embedding_size * sizeof(float);
  9904. }
  9905. }
  9906. // set kv cache
  9907. {
  9908. const auto & kv_self = ctx->kv_self;
  9909. const auto & hparams = ctx->model.hparams;
  9910. const auto & cparams = ctx->cparams;
  9911. const int n_layer = hparams.n_layer;
  9912. const int n_embd_k_gqa = hparams.n_embd_k_gqa();
  9913. const int n_embd_v_gqa = hparams.n_embd_v_gqa();
  9914. const int n_ctx = cparams.n_ctx;
  9915. size_t kv_buf_size;
  9916. uint32_t kv_head;
  9917. uint32_t kv_size;
  9918. uint32_t kv_used;
  9919. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  9920. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  9921. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  9922. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  9923. if (kv_buf_size) {
  9924. GGML_ASSERT(kv_self.total_size() == kv_buf_size);
  9925. const size_t elt_size = ggml_element_size(kv_self.k_l[0]);
  9926. for (int il = 0; il < (int) n_layer; ++il) {
  9927. size_t k_size = elt_size*n_embd_k_gqa*kv_head;
  9928. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  9929. inp += k_size;
  9930. // v is not contiguous, copy row by row
  9931. size_t v_row_size = elt_size*kv_head;
  9932. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  9933. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*elt_size*n_ctx, v_row_size);
  9934. inp += v_row_size;
  9935. }
  9936. }
  9937. }
  9938. ctx->kv_self.head = kv_head;
  9939. ctx->kv_self.size = kv_size;
  9940. ctx->kv_self.used = kv_used;
  9941. ctx->kv_self.cells.resize(kv_size);
  9942. for (uint32_t i = 0; i < kv_size; ++i) {
  9943. llama_pos pos;
  9944. size_t seq_id_size;
  9945. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  9946. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  9947. ctx->kv_self.cells[i].pos = pos;
  9948. llama_seq_id seq_id;
  9949. for (size_t j = 0; j < seq_id_size; ++j) {
  9950. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  9951. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  9952. }
  9953. }
  9954. }
  9955. const size_t nread = inp - src;
  9956. const size_t max_size = llama_get_state_size(ctx);
  9957. GGML_ASSERT(nread <= max_size);
  9958. return nread;
  9959. }
  9960. 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) {
  9961. llama_file file(path_session, "rb");
  9962. // sanity checks
  9963. {
  9964. const uint32_t magic = file.read_u32();
  9965. const uint32_t version = file.read_u32();
  9966. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  9967. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  9968. return false;
  9969. }
  9970. llama_hparams session_hparams;
  9971. file.read_raw(&session_hparams, sizeof(llama_hparams));
  9972. if (session_hparams != ctx->model.hparams) {
  9973. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  9974. return false;
  9975. }
  9976. }
  9977. // load the prompt
  9978. {
  9979. const uint32_t n_token_count = file.read_u32();
  9980. if (n_token_count > n_token_capacity) {
  9981. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  9982. return false;
  9983. }
  9984. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  9985. *n_token_count_out = n_token_count;
  9986. }
  9987. // restore the context state
  9988. {
  9989. const size_t n_state_size_cur = file.size - file.tell();
  9990. const size_t n_state_size_max = llama_get_state_size(ctx);
  9991. if (n_state_size_cur > n_state_size_max) {
  9992. 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);
  9993. return false;
  9994. }
  9995. std::vector<uint8_t> state_data(n_state_size_max);
  9996. file.read_raw(state_data.data(), n_state_size_cur);
  9997. llama_set_state_data(ctx, state_data.data());
  9998. }
  9999. return true;
  10000. }
  10001. 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) {
  10002. try {
  10003. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  10004. } catch (const std::exception & err) {
  10005. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  10006. return false;
  10007. }
  10008. }
  10009. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  10010. llama_file file(path_session, "wb");
  10011. file.write_u32(LLAMA_SESSION_MAGIC);
  10012. file.write_u32(LLAMA_SESSION_VERSION);
  10013. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  10014. // save the prompt
  10015. file.write_u32((uint32_t) n_token_count);
  10016. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  10017. // save the context state using stream saving
  10018. llama_data_file_context data_ctx(&file);
  10019. llama_copy_state_data_internal(ctx, &data_ctx);
  10020. return true;
  10021. }
  10022. int llama_eval(
  10023. struct llama_context * ctx,
  10024. llama_token * tokens,
  10025. int32_t n_tokens,
  10026. int32_t n_past) {
  10027. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  10028. const int ret = llama_decode_internal(*ctx, llama_batch_get_one(tokens, n_tokens, n_past, 0));
  10029. if (ret < 0) {
  10030. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  10031. }
  10032. return ret;
  10033. }
  10034. int llama_eval_embd(
  10035. struct llama_context * ctx,
  10036. float * embd,
  10037. int32_t n_tokens,
  10038. int32_t n_past) {
  10039. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  10040. llama_batch batch = { n_tokens, nullptr, embd, nullptr, nullptr, nullptr, nullptr, n_past, 1, 0, };
  10041. const int ret = llama_decode_internal(*ctx, batch);
  10042. if (ret < 0) {
  10043. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  10044. }
  10045. return ret;
  10046. }
  10047. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  10048. ctx->cparams.n_threads = n_threads;
  10049. ctx->cparams.n_threads_batch = n_threads_batch;
  10050. }
  10051. struct llama_batch llama_batch_get_one(
  10052. llama_token * tokens,
  10053. int32_t n_tokens,
  10054. llama_pos pos_0,
  10055. llama_seq_id seq_id) {
  10056. return {
  10057. /*n_tokens =*/ n_tokens,
  10058. /*tokens =*/ tokens,
  10059. /*embd =*/ nullptr,
  10060. /*pos =*/ nullptr,
  10061. /*n_seq_id =*/ nullptr,
  10062. /*seq_id =*/ nullptr,
  10063. /*logits =*/ nullptr,
  10064. /*all_pos_0 =*/ pos_0,
  10065. /*all_pos_1 =*/ 1,
  10066. /*all_seq_id =*/ seq_id,
  10067. };
  10068. }
  10069. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  10070. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  10071. if (embd) {
  10072. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  10073. } else {
  10074. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  10075. }
  10076. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  10077. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  10078. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  10079. for (int i = 0; i < n_tokens_alloc; ++i) {
  10080. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  10081. }
  10082. batch.seq_id[n_tokens_alloc] = nullptr;
  10083. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  10084. return batch;
  10085. }
  10086. void llama_batch_free(struct llama_batch batch) {
  10087. if (batch.token) free(batch.token);
  10088. if (batch.embd) free(batch.embd);
  10089. if (batch.pos) free(batch.pos);
  10090. if (batch.n_seq_id) free(batch.n_seq_id);
  10091. if (batch.seq_id) {
  10092. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  10093. free(batch.seq_id[i]);
  10094. }
  10095. free(batch.seq_id);
  10096. }
  10097. if (batch.logits) free(batch.logits);
  10098. }
  10099. int32_t llama_decode(
  10100. struct llama_context * ctx,
  10101. struct llama_batch batch) {
  10102. const int ret = llama_decode_internal(*ctx, batch);
  10103. if (ret < 0) {
  10104. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  10105. }
  10106. return ret;
  10107. }
  10108. float * llama_get_logits(struct llama_context * ctx) {
  10109. return ctx->logits.data();
  10110. }
  10111. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  10112. assert(ctx->logits_valid.at(i));
  10113. return ctx->logits.data() + i*ctx->model.hparams.n_vocab;
  10114. }
  10115. float * llama_get_embeddings(struct llama_context * ctx) {
  10116. return ctx->embedding.data();
  10117. }
  10118. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  10119. return model->vocab.id_to_token[token].text.c_str();
  10120. }
  10121. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  10122. return model->vocab.id_to_token[token].score;
  10123. }
  10124. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  10125. return model->vocab.id_to_token[token].type;
  10126. }
  10127. llama_token llama_token_bos(const struct llama_model * model) {
  10128. return model->vocab.special_bos_id;
  10129. }
  10130. llama_token llama_token_eos(const struct llama_model * model) {
  10131. return model->vocab.special_eos_id;
  10132. }
  10133. llama_token llama_token_nl(const struct llama_model * model) {
  10134. return model->vocab.linefeed_id;
  10135. }
  10136. int32_t llama_add_bos_token(const struct llama_model * model) {
  10137. return model->vocab.special_add_bos;
  10138. }
  10139. int32_t llama_add_eos_token(const struct llama_model * model) {
  10140. return model->vocab.special_add_eos;
  10141. }
  10142. llama_token llama_token_prefix(const struct llama_model * model) {
  10143. return model->vocab.special_prefix_id;
  10144. }
  10145. llama_token llama_token_middle(const struct llama_model * model) {
  10146. return model->vocab.special_middle_id;
  10147. }
  10148. llama_token llama_token_suffix(const struct llama_model * model) {
  10149. return model->vocab.special_suffix_id;
  10150. }
  10151. llama_token llama_token_eot(const struct llama_model * model) {
  10152. return model->vocab.special_eot_id;
  10153. }
  10154. int32_t llama_tokenize(
  10155. const struct llama_model * model,
  10156. const char * text,
  10157. int32_t text_len,
  10158. llama_token * tokens,
  10159. int32_t n_max_tokens,
  10160. bool add_bos,
  10161. bool special) {
  10162. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  10163. if (n_max_tokens < (int) res.size()) {
  10164. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  10165. return -((int) res.size());
  10166. }
  10167. for (size_t i = 0; i < res.size(); i++) {
  10168. tokens[i] = res[i];
  10169. }
  10170. return res.size();
  10171. }
  10172. static std::string llama_decode_text(const std::string & text) {
  10173. std::string decoded_text;
  10174. auto unicode_sequences = codepoints_from_utf8(text);
  10175. for (auto& unicode_sequence : unicode_sequences) {
  10176. decoded_text += unicode_to_bytes_bpe(codepoint_to_utf8(unicode_sequence));
  10177. }
  10178. return decoded_text;
  10179. }
  10180. // does not write null-terminator to buf
  10181. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  10182. if (0 <= token && token < llama_n_vocab(model)) {
  10183. switch (llama_vocab_get_type(model->vocab)) {
  10184. case LLAMA_VOCAB_TYPE_WPM:
  10185. case LLAMA_VOCAB_TYPE_SPM: {
  10186. // NOTE: we accept all unsupported token types,
  10187. // suppressing them like CONTROL tokens.
  10188. if (llama_is_normal_token(model->vocab, token)) {
  10189. std::string result = model->vocab.id_to_token[token].text;
  10190. llama_unescape_whitespace(result);
  10191. if (length < (int) result.length()) {
  10192. return -(int) result.length();
  10193. }
  10194. memcpy(buf, result.c_str(), result.length());
  10195. return result.length();
  10196. } else if (llama_is_user_defined_token(model->vocab, token)) {
  10197. std::string result = model->vocab.id_to_token[token].text;
  10198. if (length < (int) result.length()) {
  10199. return -result.length();
  10200. }
  10201. memcpy(buf, result.c_str(), result.length());
  10202. return result.length();
  10203. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  10204. if (length < 3) {
  10205. return -3;
  10206. }
  10207. memcpy(buf, "\xe2\x96\x85", 3);
  10208. return 3;
  10209. } else if (llama_is_control_token(model->vocab, token)) {
  10210. ;
  10211. } else if (llama_is_byte_token(model->vocab, token)) {
  10212. if (length < 1) {
  10213. return -1;
  10214. }
  10215. buf[0] = llama_token_to_byte(model->vocab, token);
  10216. return 1;
  10217. }
  10218. break;
  10219. }
  10220. case LLAMA_VOCAB_TYPE_BPE: {
  10221. // NOTE: we accept all unsupported token types,
  10222. // suppressing them like CONTROL tokens.
  10223. if (llama_is_normal_token(model->vocab, token)) {
  10224. std::string result = model->vocab.id_to_token[token].text;
  10225. result = llama_decode_text(result);
  10226. if (length < (int) result.length()) {
  10227. return -(int) result.length();
  10228. }
  10229. memcpy(buf, result.c_str(), result.length());
  10230. return result.length();
  10231. } else if (llama_is_user_defined_token(model->vocab, token)) {
  10232. std::string result = model->vocab.id_to_token[token].text;
  10233. if (length < (int) result.length()) {
  10234. return -result.length();
  10235. }
  10236. memcpy(buf, result.c_str(), result.length());
  10237. return result.length();
  10238. } else if (llama_is_control_token(model->vocab, token)) {
  10239. ;
  10240. }
  10241. break;
  10242. }
  10243. default:
  10244. GGML_ASSERT(false);
  10245. }
  10246. }
  10247. return 0;
  10248. }
  10249. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  10250. struct llama_timings result = {
  10251. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  10252. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  10253. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  10254. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  10255. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  10256. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  10257. /*.n_sample =*/ std::max(1, ctx->n_sample),
  10258. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  10259. /*.n_eval =*/ std::max(1, ctx->n_eval),
  10260. };
  10261. return result;
  10262. }
  10263. void llama_print_timings(struct llama_context * ctx) {
  10264. const llama_timings timings = llama_get_timings(ctx);
  10265. LLAMA_LOG_INFO("\n");
  10266. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  10267. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  10268. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  10269. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  10270. __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);
  10271. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  10272. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  10273. 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));
  10274. }
  10275. void llama_reset_timings(struct llama_context * ctx) {
  10276. ctx->t_start_us = ggml_time_us();
  10277. ctx->t_sample_us = ctx->n_sample = 0;
  10278. ctx->t_eval_us = ctx->n_eval = 0;
  10279. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  10280. }
  10281. const char * llama_print_system_info(void) {
  10282. static std::string s;
  10283. s = "";
  10284. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  10285. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  10286. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  10287. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  10288. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  10289. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  10290. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  10291. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  10292. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  10293. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  10294. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  10295. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  10296. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  10297. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  10298. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  10299. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  10300. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  10301. return s.c_str();
  10302. }
  10303. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  10304. fprintf(stream, "\n");
  10305. fprintf(stream, "###########\n");
  10306. fprintf(stream, "# Timings #\n");
  10307. fprintf(stream, "###########\n");
  10308. fprintf(stream, "\n");
  10309. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  10310. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  10311. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  10312. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  10313. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  10314. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  10315. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  10316. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  10317. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  10318. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  10319. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  10320. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  10321. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  10322. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  10323. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  10324. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  10325. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  10326. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  10327. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  10328. }
  10329. // For internal test use
  10330. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  10331. struct llama_context * ctx
  10332. ) {
  10333. return ctx->model.tensors_by_name;
  10334. }
  10335. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  10336. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  10337. g_state.log_callback_user_data = user_data;
  10338. #ifdef GGML_USE_METAL
  10339. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  10340. #endif
  10341. }
  10342. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  10343. va_list args_copy;
  10344. va_copy(args_copy, args);
  10345. char buffer[128];
  10346. int len = vsnprintf(buffer, 128, format, args);
  10347. if (len < 128) {
  10348. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  10349. } else {
  10350. char* buffer2 = new char[len+1];
  10351. vsnprintf(buffer2, len+1, format, args_copy);
  10352. buffer2[len] = 0;
  10353. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  10354. delete[] buffer2;
  10355. }
  10356. va_end(args_copy);
  10357. }
  10358. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  10359. va_list args;
  10360. va_start(args, format);
  10361. llama_log_internal_v(level, format, args);
  10362. va_end(args);
  10363. }
  10364. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  10365. (void) level;
  10366. (void) user_data;
  10367. fputs(text, stderr);
  10368. fflush(stderr);
  10369. }