llama.cpp 371 KB

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