llama.cpp 219 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254
  1. // Defines fileno on msys:
  2. #ifndef _GNU_SOURCE
  3. #define _GNU_SOURCE
  4. #include <cstddef>
  5. #include <cstdint>
  6. #include <cstdio>
  7. #endif
  8. #include "llama.h"
  9. #include "ggml.h"
  10. #include "ggml-alloc.h"
  11. #ifdef GGML_USE_CUBLAS
  12. # include "ggml-cuda.h"
  13. #elif defined(GGML_USE_CLBLAST)
  14. # include "ggml-opencl.h"
  15. #endif
  16. #ifdef GGML_USE_METAL
  17. # include "ggml-metal.h"
  18. #endif
  19. #ifdef GGML_USE_MPI
  20. # include "ggml-mpi.h"
  21. #endif
  22. #ifdef GGML_USE_K_QUANTS
  23. # ifndef QK_K
  24. # ifdef GGML_QKK_64
  25. # define QK_K 64
  26. # else
  27. # define QK_K 256
  28. # endif
  29. # endif
  30. #endif
  31. #ifdef __has_include
  32. #if __has_include(<unistd.h>)
  33. #include <unistd.h>
  34. #if defined(_POSIX_MAPPED_FILES)
  35. #include <sys/mman.h>
  36. #endif
  37. #if defined(_POSIX_MEMLOCK_RANGE)
  38. #include <sys/resource.h>
  39. #endif
  40. #endif
  41. #endif
  42. #if defined(_WIN32)
  43. #define WIN32_LEAN_AND_MEAN
  44. #ifndef NOMINMAX
  45. #define NOMINMAX
  46. #endif
  47. #include <windows.h>
  48. #include <io.h>
  49. #include <stdio.h> // for _fseeki64
  50. #endif
  51. #include <algorithm>
  52. #include <array>
  53. #include <cassert>
  54. #include <cinttypes>
  55. #include <climits>
  56. #include <cstdarg>
  57. #include <cstring>
  58. #include <ctime>
  59. #include <fstream>
  60. #include <initializer_list>
  61. #include <map>
  62. #include <memory>
  63. #include <mutex>
  64. #include <numeric>
  65. #include <queue>
  66. #include <random>
  67. #include <regex>
  68. #include <sstream>
  69. #include <thread>
  70. #include <unordered_map>
  71. #if defined(_MSC_VER)
  72. #pragma warning(disable: 4244 4267) // possible loss of data
  73. #endif
  74. #ifdef __GNUC__
  75. #ifdef __MINGW32__
  76. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  77. #else
  78. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  79. #endif
  80. #else
  81. #define LLAMA_ATTRIBUTE_FORMAT(...)
  82. #endif
  83. //
  84. // logging
  85. //
  86. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  87. static void llama_log_internal (llama_log_level level, const char* format, ...);
  88. static void llama_log_callback_default(llama_log_level level, const char * text, void * user_data);
  89. #define LLAMA_LOG_INFO(...) llama_log_internal(LLAMA_LOG_LEVEL_INFO , __VA_ARGS__)
  90. #define LLAMA_LOG_WARN(...) llama_log_internal(LLAMA_LOG_LEVEL_WARN , __VA_ARGS__)
  91. #define LLAMA_LOG_ERROR(...) llama_log_internal(LLAMA_LOG_LEVEL_ERROR, __VA_ARGS__)
  92. //
  93. // helpers
  94. //
  95. static size_t utf8_len(char src) {
  96. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  97. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  98. return lookup[highbits];
  99. }
  100. void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  101. for (size_t pos = 0; ; pos += replace.length()) {
  102. pos = s.find(search, pos);
  103. if (pos == std::string::npos) break;
  104. s.erase(pos, search.length());
  105. s.insert(pos, replace);
  106. }
  107. }
  108. static void zeros(std::ofstream & file, size_t n) {
  109. char zero = 0;
  110. for (size_t i = 0; i < n; ++i) {
  111. file.write(&zero, 1);
  112. }
  113. }
  114. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  115. static std::string format(const char * fmt, ...) {
  116. va_list ap;
  117. va_list ap2;
  118. va_start(ap, fmt);
  119. va_copy(ap2, ap);
  120. int size = vsnprintf(NULL, 0, fmt, ap);
  121. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  122. std::vector<char> buf(size + 1);
  123. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  124. GGML_ASSERT(size2 == size);
  125. va_end(ap2);
  126. va_end(ap);
  127. return std::string(buf.data(), size);
  128. }
  129. //
  130. // gguf constants (sync with gguf.py)
  131. //
  132. enum llm_arch {
  133. LLM_ARCH_LLAMA,
  134. LLM_ARCH_FALCON,
  135. LLM_ARCH_GPT2,
  136. LLM_ARCH_GPTJ,
  137. LLM_ARCH_GPTNEOX,
  138. LLM_ARCH_MPT,
  139. LLM_ARCH_UNKNOWN,
  140. };
  141. static std::map<llm_arch, std::string> LLM_ARCH_NAMES = {
  142. { LLM_ARCH_LLAMA, "llama" },
  143. { LLM_ARCH_FALCON, "falcon" },
  144. { LLM_ARCH_GPT2, "gpt2" },
  145. { LLM_ARCH_GPTJ, "gptj" },
  146. { LLM_ARCH_GPTNEOX, "gptneox" },
  147. { LLM_ARCH_MPT, "mpt" },
  148. };
  149. enum llm_kv {
  150. LLM_KV_GENERAL_ARCHITECTURE,
  151. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  152. LLM_KV_GENERAL_ALIGNMENT,
  153. LLM_KV_GENERAL_NAME,
  154. LLM_KV_GENERAL_AUTHOR,
  155. LLM_KV_GENERAL_URL,
  156. LLM_KV_GENERAL_DESCRIPTION,
  157. LLM_KV_GENERAL_LICENSE,
  158. LLM_KV_GENERAL_SOURCE_URL,
  159. LLM_KV_GENERAL_SOURCE_HF_REPO,
  160. LLM_KV_CONTEXT_LENGTH,
  161. LLM_KV_EMBEDDING_LENGTH,
  162. LLM_KV_BLOCK_COUNT,
  163. LLM_KV_FEED_FORWARD_LENGTH,
  164. LLM_KV_USE_PARALLEL_RESIDUAL,
  165. LLM_KV_TENSOR_DATA_LAYOUT,
  166. LLM_KV_ATTENTION_HEAD_COUNT,
  167. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  168. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  169. LLM_KV_ATTENTION_CLAMP_KQV,
  170. LLM_KV_ATTENTION_LAYERNORM_EPS,
  171. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  172. LLM_KV_ROPE_DIMENSION_COUNT,
  173. LLM_KV_ROPE_FREQ_BASE,
  174. LLM_KV_ROPE_SCALE_LINEAR,
  175. LLM_KV_TOKENIZER_MODEL,
  176. LLM_KV_TOKENIZER_LIST,
  177. LLM_KV_TOKENIZER_TOKEN_TYPE,
  178. LLM_KV_TOKENIZER_SCORES,
  179. LLM_KV_TOKENIZER_MERGES,
  180. LLM_KV_TOKENIZER_BOS_ID,
  181. LLM_KV_TOKENIZER_EOS_ID,
  182. LLM_KV_TOKENIZER_UNK_ID,
  183. LLM_KV_TOKENIZER_SEP_ID,
  184. LLM_KV_TOKENIZER_PAD_ID,
  185. LLM_KV_TOKENIZER_HF_JSON,
  186. LLM_KV_TOKENIZER_RWKV,
  187. };
  188. static std::map<llm_kv, std::string> LLM_KV_NAMES = {
  189. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  190. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  191. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  192. { LLM_KV_GENERAL_NAME, "general.name" },
  193. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  194. { LLM_KV_GENERAL_URL, "general.url" },
  195. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  196. { LLM_KV_GENERAL_LICENSE, "general.license" },
  197. { LLM_KV_GENERAL_SOURCE_URL, "general.source_url" },
  198. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source_hf_repo" },
  199. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  200. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  201. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  202. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  203. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  204. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  205. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  206. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  207. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  208. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  209. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  210. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  211. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  212. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  213. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  214. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  215. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  216. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  217. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  218. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  219. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  220. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  221. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  222. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  223. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  224. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  225. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  226. };
  227. struct LLM_KV {
  228. LLM_KV(llm_arch arch) : arch(arch) {}
  229. llm_arch arch;
  230. std::string operator()(llm_kv kv) const {
  231. return ::format(LLM_KV_NAMES[kv].c_str(), LLM_ARCH_NAMES[arch].c_str());
  232. }
  233. };
  234. enum llm_tensor {
  235. LLM_TENSOR_TOKEN_EMBD,
  236. LLM_TENSOR_POS_EMBD,
  237. LLM_TENSOR_OUTPUT,
  238. LLM_TENSOR_OUTPUT_NORM,
  239. LLM_TENSOR_ROPE_FREQS,
  240. LLM_TENSOR_ATTN_Q,
  241. LLM_TENSOR_ATTN_K,
  242. LLM_TENSOR_ATTN_V,
  243. LLM_TENSOR_ATTN_QKV,
  244. LLM_TENSOR_ATTN_OUT,
  245. LLM_TENSOR_ATTN_NORM,
  246. LLM_TENSOR_ATTN_NORM_2,
  247. LLM_TENSOR_ATTN_ROT_EMBD,
  248. LLM_TENSOR_FFN_GATE,
  249. LLM_TENSOR_FFN_DOWN,
  250. LLM_TENSOR_FFN_UP,
  251. LLM_TENSOR_FFN_NORM,
  252. };
  253. static std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  254. {
  255. LLM_ARCH_LLAMA,
  256. {
  257. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  258. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  259. { LLM_TENSOR_OUTPUT, "output" },
  260. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  261. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  262. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  263. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  264. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  265. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  266. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  267. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  268. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  269. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  270. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  271. },
  272. },
  273. {
  274. LLM_ARCH_FALCON,
  275. {
  276. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  277. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  278. { LLM_TENSOR_OUTPUT, "output" },
  279. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  280. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  281. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  282. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  283. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  284. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  285. },
  286. },
  287. };
  288. static llm_arch llm_arch_from_string(const std::string & name) {
  289. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  290. if (kv.second == name) {
  291. return kv.first;
  292. }
  293. }
  294. return LLM_ARCH_UNKNOWN;
  295. }
  296. // helper to handle gguf constants
  297. // usage:
  298. //
  299. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  300. //
  301. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  302. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  303. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  304. //
  305. struct LLM_TN {
  306. LLM_TN(llm_arch arch) : arch(arch) {}
  307. llm_arch arch;
  308. std::string operator()(llm_tensor tensor) const {
  309. return LLM_TENSOR_NAMES[arch].at(tensor);
  310. }
  311. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  312. return LLM_TENSOR_NAMES[arch].at(tensor) + "." + suffix;
  313. }
  314. std::string operator()(llm_tensor tensor, int bid) const {
  315. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid);
  316. }
  317. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  318. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid) + "." + suffix;
  319. }
  320. };
  321. //
  322. // gguf helpers
  323. //
  324. #define GGUF_GET_KEY(ctx, dst, func, type, req, key) \
  325. { \
  326. const std::string skey(key); \
  327. const int kid = gguf_find_key(ctx, skey.c_str()); \
  328. if (kid >= 0) { \
  329. enum gguf_type ktype = gguf_get_kv_type(ctx, kid); \
  330. if (ktype != (type)) { \
  331. throw std::runtime_error(format("key %s has wrong type: %s", skey.c_str(), gguf_type_name(ktype))); \
  332. } \
  333. (dst) = func(ctx, kid); \
  334. } else if (req) { \
  335. throw std::runtime_error(format("key not found in model: %s", skey.c_str())); \
  336. } \
  337. }
  338. //
  339. // ggml helpers
  340. //
  341. static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
  342. struct ggml_cplan plan = ggml_graph_plan(graph, n_threads);
  343. if (plan.work_size > 0) {
  344. buf.resize(plan.work_size);
  345. plan.work_data = buf.data();
  346. }
  347. ggml_graph_compute(graph, &plan);
  348. }
  349. //
  350. // llama helpers
  351. //
  352. #ifdef GGML_USE_CUBLAS
  353. # define llama_host_malloc(n) ggml_cuda_host_malloc(n)
  354. # define llama_host_free(data) ggml_cuda_host_free(data)
  355. #elif GGML_USE_METAL
  356. # define llama_host_malloc(n) ggml_metal_host_malloc(n)
  357. # define llama_host_free(data) ggml_metal_host_free(data)
  358. #else
  359. # define llama_host_malloc(n) malloc(n)
  360. # define llama_host_free(data) free(data)
  361. #endif
  362. #if defined(_WIN32)
  363. static std::string llama_format_win_err(DWORD err) {
  364. LPSTR buf;
  365. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  366. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  367. if (!size) {
  368. return "FormatMessageA failed";
  369. }
  370. std::string ret(buf, size);
  371. LocalFree(buf);
  372. return ret;
  373. }
  374. #endif
  375. struct llama_buffer {
  376. void * data = NULL;
  377. size_t size = 0;
  378. // fallback to malloc / free
  379. // useful in cases where CUDA can try to allocate PINNED memory
  380. bool fallback = false;
  381. void resize(size_t n) {
  382. llama_host_free(data);
  383. data = llama_host_malloc(n);
  384. if (!data) {
  385. fallback = true;
  386. data = malloc(n);
  387. } else {
  388. fallback = false;
  389. }
  390. GGML_ASSERT(data);
  391. size = n;
  392. }
  393. ~llama_buffer() {
  394. if (data) {
  395. if (fallback) { // NOLINT
  396. free(data);
  397. } else {
  398. llama_host_free(data);
  399. }
  400. }
  401. data = NULL;
  402. }
  403. };
  404. struct llama_file {
  405. // use FILE * so we don't have to re-open the file to mmap
  406. FILE * fp;
  407. size_t size;
  408. llama_file(const char * fname, const char * mode) {
  409. fp = std::fopen(fname, mode);
  410. if (fp == NULL) {
  411. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  412. }
  413. seek(0, SEEK_END);
  414. size = tell();
  415. seek(0, SEEK_SET);
  416. }
  417. size_t tell() const {
  418. #ifdef _WIN32
  419. __int64 ret = _ftelli64(fp);
  420. #else
  421. long ret = std::ftell(fp);
  422. #endif
  423. GGML_ASSERT(ret != -1); // this really shouldn't fail
  424. return (size_t) ret;
  425. }
  426. void seek(size_t offset, int whence) const {
  427. #ifdef _WIN32
  428. int ret = _fseeki64(fp, (__int64) offset, whence);
  429. #else
  430. int ret = std::fseek(fp, (long) offset, whence);
  431. #endif
  432. GGML_ASSERT(ret == 0); // same
  433. }
  434. void read_raw(void * ptr, size_t len) const {
  435. if (len == 0) {
  436. return;
  437. }
  438. errno = 0;
  439. std::size_t ret = std::fread(ptr, len, 1, fp);
  440. if (ferror(fp)) {
  441. throw std::runtime_error(format("read error: %s", strerror(errno)));
  442. }
  443. if (ret != 1) {
  444. throw std::runtime_error(std::string("unexpectedly reached end of file"));
  445. }
  446. }
  447. uint32_t read_u32() const {
  448. uint32_t ret;
  449. read_raw(&ret, sizeof(ret));
  450. return ret;
  451. }
  452. void write_raw(const void * ptr, size_t len) const {
  453. if (len == 0) {
  454. return;
  455. }
  456. errno = 0;
  457. size_t ret = std::fwrite(ptr, len, 1, fp);
  458. if (ret != 1) {
  459. throw std::runtime_error(format("write error: %s", strerror(errno)));
  460. }
  461. }
  462. void write_u32(std::uint32_t val) const {
  463. write_raw(&val, sizeof(val));
  464. }
  465. ~llama_file() {
  466. if (fp) {
  467. std::fclose(fp);
  468. }
  469. }
  470. };
  471. struct llama_mmap {
  472. void * addr;
  473. size_t size;
  474. llama_mmap(const llama_mmap &) = delete;
  475. #ifdef _POSIX_MAPPED_FILES
  476. static constexpr bool SUPPORTED = true;
  477. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  478. size = file->size;
  479. int fd = fileno(file->fp);
  480. int flags = MAP_SHARED;
  481. // prefetch/readahead impairs performance on NUMA systems
  482. if (numa) { prefetch = 0; }
  483. #ifdef __linux__
  484. if (prefetch) { flags |= MAP_POPULATE; }
  485. #endif
  486. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  487. if (addr == MAP_FAILED) {
  488. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  489. }
  490. if (prefetch > 0) {
  491. // Advise the kernel to preload the mapped memory
  492. if (madvise(addr, std::min(file->size, prefetch), MADV_WILLNEED)) {
  493. fprintf(stderr, "warning: madvise(.., MADV_WILLNEED) failed: %s\n",
  494. strerror(errno));
  495. }
  496. }
  497. if (numa) {
  498. // advise the kernel not to use readahead
  499. // (because the next page might not belong on the same node)
  500. if (madvise(addr, file->size, MADV_RANDOM)) {
  501. fprintf(stderr, "warning: madvise(.., MADV_RANDOM) failed: %s\n",
  502. strerror(errno));
  503. }
  504. }
  505. }
  506. ~llama_mmap() {
  507. munmap(addr, size);
  508. }
  509. #elif defined(_WIN32)
  510. static constexpr bool SUPPORTED = true;
  511. llama_mmap(struct llama_file * file, bool prefetch = true, bool numa = false) {
  512. (void) numa;
  513. size = file->size;
  514. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  515. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  516. DWORD error = GetLastError();
  517. if (hMapping == NULL) {
  518. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  519. }
  520. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  521. error = GetLastError();
  522. CloseHandle(hMapping);
  523. if (addr == NULL) {
  524. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  525. }
  526. #if _WIN32_WINNT >= _WIN32_WINNT_WIN8
  527. if (prefetch) {
  528. // Advise the kernel to preload the mapped memory
  529. WIN32_MEMORY_RANGE_ENTRY range;
  530. range.VirtualAddress = addr;
  531. range.NumberOfBytes = (SIZE_T)size;
  532. if (!PrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  533. fprintf(stderr, "warning: PrefetchVirtualMemory failed: %s\n",
  534. llama_format_win_err(GetLastError()).c_str());
  535. }
  536. }
  537. #else
  538. #pragma message("warning: You are building for pre-Windows 8; prefetch not supported")
  539. #endif // _WIN32_WINNT >= _WIN32_WINNT_WIN8
  540. }
  541. ~llama_mmap() {
  542. if (!UnmapViewOfFile(addr)) {
  543. fprintf(stderr, "warning: UnmapViewOfFile failed: %s\n",
  544. llama_format_win_err(GetLastError()).c_str());
  545. }
  546. }
  547. #else
  548. static constexpr bool SUPPORTED = false;
  549. llama_mmap(struct llama_file * file, bool prefetch = true, bool numa = false) {
  550. (void) file;
  551. (void) prefetch;
  552. (void) numa;
  553. throw std::runtime_error(std::string("mmap not supported"));
  554. }
  555. #endif
  556. };
  557. // Represents some region of memory being locked using mlock or VirtualLock;
  558. // will automatically unlock on destruction.
  559. struct llama_mlock {
  560. void * addr = NULL;
  561. size_t size = 0;
  562. bool failed_already = false;
  563. llama_mlock() {}
  564. llama_mlock(const llama_mlock &) = delete;
  565. ~llama_mlock() {
  566. if (size) {
  567. raw_unlock(addr, size);
  568. }
  569. }
  570. void init(void * ptr) {
  571. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  572. addr = ptr;
  573. }
  574. void grow_to(size_t target_size) {
  575. GGML_ASSERT(addr);
  576. if (failed_already) {
  577. return;
  578. }
  579. size_t granularity = lock_granularity();
  580. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  581. if (target_size > size) {
  582. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  583. size = target_size;
  584. } else {
  585. failed_already = true;
  586. }
  587. }
  588. }
  589. #ifdef _POSIX_MEMLOCK_RANGE
  590. static constexpr bool SUPPORTED = true;
  591. static size_t lock_granularity() {
  592. return (size_t) sysconf(_SC_PAGESIZE);
  593. }
  594. #ifdef __APPLE__
  595. #define MLOCK_SUGGESTION \
  596. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  597. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MLOCK (ulimit -l).\n"
  598. #else
  599. #define MLOCK_SUGGESTION \
  600. "Try increasing RLIMIT_MLOCK ('ulimit -l' as root).\n"
  601. #endif
  602. bool raw_lock(const void * addr, size_t size) const {
  603. if (!mlock(addr, size)) {
  604. return true;
  605. }
  606. char* errmsg = std::strerror(errno);
  607. bool suggest = (errno == ENOMEM);
  608. // Check if the resource limit is fine after all
  609. struct rlimit lock_limit;
  610. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  611. suggest = false;
  612. }
  613. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  614. suggest = false;
  615. }
  616. fprintf(stderr, "warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  617. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  618. return false;
  619. }
  620. #undef MLOCK_SUGGESTION
  621. static void raw_unlock(void * addr, size_t size) {
  622. if (munlock(addr, size)) {
  623. fprintf(stderr, "warning: failed to munlock buffer: %s\n", std::strerror(errno));
  624. }
  625. }
  626. #elif defined(_WIN32)
  627. static constexpr bool SUPPORTED = true;
  628. static size_t lock_granularity() {
  629. SYSTEM_INFO si;
  630. GetSystemInfo(&si);
  631. return (size_t) si.dwPageSize;
  632. }
  633. bool raw_lock(void * ptr, size_t len) const {
  634. for (int tries = 1; ; tries++) {
  635. if (VirtualLock(ptr, len)) {
  636. return true;
  637. }
  638. if (tries == 2) {
  639. fprintf(stderr, "warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  640. len, size, llama_format_win_err(GetLastError()).c_str());
  641. return false;
  642. }
  643. // It failed but this was only the first try; increase the working
  644. // set size and try again.
  645. SIZE_T min_ws_size, max_ws_size;
  646. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  647. fprintf(stderr, "warning: GetProcessWorkingSetSize failed: %s\n",
  648. llama_format_win_err(GetLastError()).c_str());
  649. return false;
  650. }
  651. // Per MSDN: "The maximum number of pages that a process can lock
  652. // is equal to the number of pages in its minimum working set minus
  653. // a small overhead."
  654. // Hopefully a megabyte is enough overhead:
  655. size_t increment = len + 1048576;
  656. // The minimum must be <= the maximum, so we need to increase both:
  657. min_ws_size += increment;
  658. max_ws_size += increment;
  659. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  660. fprintf(stderr, "warning: SetProcessWorkingSetSize failed: %s\n",
  661. llama_format_win_err(GetLastError()).c_str());
  662. return false;
  663. }
  664. }
  665. }
  666. static void raw_unlock(void * ptr, size_t len) {
  667. if (!VirtualUnlock(ptr, len)) {
  668. fprintf(stderr, "warning: failed to VirtualUnlock buffer: %s\n",
  669. llama_format_win_err(GetLastError()).c_str());
  670. }
  671. }
  672. #else
  673. static constexpr bool SUPPORTED = false;
  674. static size_t lock_granularity() {
  675. return (size_t) 65536;
  676. }
  677. bool raw_lock(const void * addr, size_t len) const {
  678. fprintf(stderr, "warning: mlock not supported on this system\n");
  679. return false;
  680. }
  681. static void raw_unlock(const void * addr, size_t len) {}
  682. #endif
  683. };
  684. typedef void (*offload_func_t)(struct ggml_tensor * tensor);
  685. static void llama_nop(struct ggml_tensor * tensor) { // don't offload by default
  686. (void) tensor;
  687. }
  688. static std::string llama_token_to_text(const struct llama_context * ctx, llama_token token) {
  689. std::vector<char> result(8, 0);
  690. const int n_tokens = llama_token_to_str(ctx, token, result.data(), result.size());
  691. if (n_tokens < 0) {
  692. result.resize(-n_tokens);
  693. int check = llama_token_to_str(ctx, token, result.data(), result.size());
  694. GGML_ASSERT(check == -n_tokens);
  695. } else {
  696. result.resize(n_tokens);
  697. }
  698. return std::string(result.data(), result.size());
  699. }
  700. //
  701. // globals
  702. //
  703. struct llama_state {
  704. // We save the log callback globally
  705. llama_log_callback log_callback = llama_log_callback_default;
  706. void * log_callback_user_data = nullptr;
  707. };
  708. static llama_state g_state;
  709. // available llama models
  710. enum e_model {
  711. MODEL_UNKNOWN,
  712. MODEL_3B,
  713. MODEL_7B,
  714. MODEL_13B,
  715. MODEL_30B,
  716. MODEL_34B,
  717. MODEL_40B,
  718. MODEL_65B,
  719. MODEL_70B,
  720. };
  721. static const size_t kB = 1024;
  722. static const size_t MB = kB*kB;
  723. // default hparams (LLaMA 7B)
  724. struct llama_hparams {
  725. uint32_t n_vocab = 32000;
  726. uint32_t n_ctx_train = 2048; // the context size used during training
  727. uint32_t n_ctx = 512; // the context size used during inference
  728. uint32_t n_embd = 4096;
  729. uint32_t n_head = 32;
  730. uint32_t n_head_kv = 32;
  731. uint32_t n_layer = 32;
  732. uint32_t n_rot = 64;
  733. uint32_t n_ff = 11008;
  734. float f_norm_eps = 1e-5;
  735. float f_norm_rms_eps = 1e-5;
  736. float rope_freq_base = 10000.0f;
  737. float rope_freq_scale = 1.0f;
  738. bool operator!=(const llama_hparams & other) const {
  739. return static_cast<bool>(memcmp(this, &other, sizeof(llama_hparams))); // NOLINT
  740. }
  741. uint32_t n_gqa() const {
  742. return n_head/n_head_kv;
  743. }
  744. uint32_t n_embd_head() const {
  745. return n_embd/n_head;
  746. }
  747. uint32_t n_embd_gqa() const {
  748. return n_embd/n_gqa();
  749. }
  750. size_t kv_size() const {
  751. size_t result = 2ull;
  752. result *= (size_t) n_embd_gqa();
  753. result *= (size_t) n_ctx;
  754. result *= (size_t) n_layer;
  755. result *= sizeof(ggml_fp16_t);
  756. return result;
  757. }
  758. };
  759. struct llama_layer {
  760. // normalization
  761. struct ggml_tensor * attn_norm;
  762. struct ggml_tensor * attn_norm_b;
  763. struct ggml_tensor * attn_norm_2;
  764. struct ggml_tensor * attn_norm_2_b;
  765. // attention
  766. struct ggml_tensor * wq;
  767. struct ggml_tensor * wk;
  768. struct ggml_tensor * wv;
  769. struct ggml_tensor * wo;
  770. struct ggml_tensor * wqkv;
  771. // normalization
  772. struct ggml_tensor * ffn_norm;
  773. // ff
  774. struct ggml_tensor * w1; // ffn_gate
  775. struct ggml_tensor * w2; // ffn_down
  776. struct ggml_tensor * w3; // ffn_up
  777. };
  778. struct llama_kv_cache {
  779. struct ggml_tensor * k = NULL;
  780. struct ggml_tensor * v = NULL;
  781. struct ggml_context * ctx = NULL;
  782. llama_buffer buf;
  783. int n; // number of tokens currently in the cache
  784. ~llama_kv_cache() {
  785. if (ctx) {
  786. ggml_free(ctx);
  787. }
  788. #ifdef GGML_USE_CUBLAS
  789. ggml_cuda_free_data(k);
  790. ggml_cuda_free_data(v);
  791. #endif // GGML_USE_CUBLAS
  792. }
  793. };
  794. struct llama_vocab {
  795. using id = int32_t;
  796. using token = std::string;
  797. using ttype = llama_token_type;
  798. struct token_data {
  799. token text;
  800. float score;
  801. ttype type;
  802. };
  803. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  804. std::unordered_map<token, id> token_to_id;
  805. std::vector<token_data> id_to_token;
  806. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  807. // default LLaMA special tokens
  808. id special_bos_id = 1;
  809. id special_eos_id = 2;
  810. id special_unk_id = 0;
  811. id special_sep_id = -1;
  812. id special_pad_id = -1;
  813. id linefeed_id = 13;
  814. int find_bpe_rank(std::string token_left, std::string token_right) const {
  815. replace_all(token_left, " ", "Ġ");
  816. replace_all(token_left, "\n", "Ċ");
  817. replace_all(token_right, " ", "Ġ");
  818. replace_all(token_right, "\n", "Ċ");
  819. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  820. if (it == bpe_ranks.end()) {
  821. return -1;
  822. }
  823. return it->second;
  824. }
  825. };
  826. struct llama_model {
  827. e_model type = MODEL_UNKNOWN;
  828. llm_arch arch = LLM_ARCH_UNKNOWN;
  829. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  830. std::string name = "n/a";
  831. llama_hparams hparams;
  832. llama_vocab vocab;
  833. struct ggml_tensor * tok_embeddings;
  834. struct ggml_tensor * output_norm;
  835. struct ggml_tensor * output_norm_b;
  836. struct ggml_tensor * output;
  837. std::vector<llama_layer> layers;
  838. int n_gpu_layers;
  839. // context
  840. struct ggml_context * ctx = NULL;
  841. // the model memory buffer
  842. llama_buffer buf;
  843. // model memory mapped file
  844. std::unique_ptr<llama_mmap> mapping;
  845. // objects representing data potentially being locked in memory
  846. llama_mlock mlock_buf;
  847. llama_mlock mlock_mmap;
  848. // for quantize-stats only
  849. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  850. int64_t t_load_us = 0;
  851. int64_t t_start_us = 0;
  852. ~llama_model() {
  853. if (ctx) {
  854. ggml_free(ctx);
  855. }
  856. #ifdef GGML_USE_CUBLAS
  857. for (size_t i = 0; i < tensors_by_name.size(); ++i) {
  858. ggml_cuda_free_data(tensors_by_name[i].second);
  859. }
  860. ggml_cuda_free_scratch();
  861. #elif defined(GGML_USE_CLBLAST)
  862. for (size_t i = 0; i < tensors_by_name.size(); ++i) {
  863. ggml_cl_free_data(tensors_by_name[i].second);
  864. }
  865. #endif
  866. }
  867. };
  868. struct llama_context {
  869. llama_context(const llama_model & model) : model(model), t_load_us(model.t_load_us), t_start_us(model.t_start_us) {}
  870. ~llama_context() {
  871. if (model_owner) {
  872. delete &model;
  873. }
  874. #ifdef GGML_USE_METAL
  875. if (ctx_metal) {
  876. ggml_metal_free(ctx_metal);
  877. }
  878. #endif
  879. if (alloc) {
  880. ggml_allocr_free(alloc);
  881. }
  882. }
  883. std::mt19937 rng;
  884. bool has_evaluated_once = false;
  885. int64_t t_sample_us = 0;
  886. int64_t t_eval_us = 0;
  887. int64_t t_p_eval_us = 0;
  888. int32_t n_sample = 0; // number of tokens sampled
  889. int32_t n_eval = 0; // number of eval calls
  890. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  891. const llama_model & model;
  892. bool model_owner = false;
  893. int64_t t_load_us;
  894. int64_t t_start_us;
  895. // key + value cache for the self attention
  896. struct llama_kv_cache kv_self;
  897. // decode output (2-dimensional array: [n_tokens][n_vocab])
  898. std::vector<float> logits;
  899. bool logits_all = false;
  900. // input embedding (1-dimensional array: [n_embd])
  901. std::vector<float> embedding;
  902. // reusable buffer for `struct ggml_graph_plan.work_data`
  903. std::vector<uint8_t> work_buffer;
  904. // memory buffers used to evaluate the model
  905. llama_buffer buf_compute;
  906. llama_buffer buf_alloc;
  907. ggml_allocr * alloc = NULL;
  908. #ifdef GGML_USE_METAL
  909. ggml_metal_context * ctx_metal = NULL;
  910. #endif
  911. #ifdef GGML_USE_MPI
  912. ggml_mpi_context * ctx_mpi = NULL;
  913. #endif
  914. };
  915. //
  916. // kv cache helpers
  917. //
  918. static bool llama_kv_cache_init(
  919. const struct llama_hparams & hparams,
  920. struct llama_kv_cache & cache,
  921. ggml_type wtype,
  922. int n_ctx,
  923. int n_gpu_layers) {
  924. const int n_embd = hparams.n_embd_gqa();
  925. const int n_layer = hparams.n_layer;
  926. const int64_t n_mem = n_layer*n_ctx;
  927. const int64_t n_elements = n_embd*n_mem;
  928. cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*MB);
  929. cache.n = 0;
  930. struct ggml_init_params params;
  931. params.mem_size = cache.buf.size;
  932. params.mem_buffer = cache.buf.data;
  933. params.no_alloc = false;
  934. cache.ctx = ggml_init(params);
  935. if (!cache.ctx) {
  936. LLAMA_LOG_ERROR("%s: failed to allocate memory for kv cache\n", __func__);
  937. return false;
  938. }
  939. cache.k = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  940. cache.v = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  941. ggml_set_name(cache.k, "cache_k");
  942. ggml_set_name(cache.v, "cache_v");
  943. (void) n_gpu_layers;
  944. #ifdef GGML_USE_CUBLAS
  945. if (n_gpu_layers > n_layer + 1) {
  946. ggml_cuda_assign_buffers_no_scratch(cache.v);
  947. }
  948. if (n_gpu_layers > n_layer + 2) {
  949. ggml_cuda_assign_buffers_no_scratch(cache.k);
  950. }
  951. #endif // GGML_USE_CUBLAS
  952. return true;
  953. }
  954. //
  955. // model loading and saving
  956. //
  957. enum llama_fver {
  958. GGUF_FILE_VERSION_V1 = 1,
  959. };
  960. static const char * llama_file_version_name(llama_fver version) {
  961. switch (version) {
  962. case GGUF_FILE_VERSION_V1: return "GGUF V1 (latest)";
  963. }
  964. return "unknown";
  965. }
  966. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  967. char buf[256];
  968. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  969. for (size_t i = 1; i < ne.size(); i++) {
  970. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  971. }
  972. return buf;
  973. }
  974. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  975. char buf[256];
  976. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  977. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  978. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  979. }
  980. return buf;
  981. }
  982. struct llama_model_loader {
  983. int n_kv = 0;
  984. int n_tensors = 0;
  985. int n_created = 0;
  986. int64_t n_elements = 0;
  987. bool use_mmap = false;
  988. llama_file file;
  989. llama_ftype ftype;
  990. llama_fver fver;
  991. std::unique_ptr<llama_mmap> mapping;
  992. struct gguf_context * ctx_gguf = NULL;
  993. struct ggml_context * ctx_meta = NULL;
  994. llama_model_loader(const std::string & fname, bool use_mmap) : file(fname.c_str(), "rb") {
  995. struct gguf_init_params params = {
  996. /*.no_alloc = */ true,
  997. /*.ctx = */ &ctx_meta,
  998. };
  999. ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  1000. if (!ctx_gguf) {
  1001. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  1002. }
  1003. n_kv = gguf_get_n_kv(ctx_gguf);
  1004. n_tensors = gguf_get_n_tensors(ctx_gguf);
  1005. fver = (enum llama_fver ) gguf_get_version(ctx_gguf);
  1006. for (int i = 0; i < n_tensors; i++) {
  1007. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  1008. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, name);
  1009. n_elements += ggml_nelements(t);
  1010. }
  1011. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  1012. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  1013. // determine file type based on the number of tensors for each quantization and print meta data
  1014. // TODO: make optional
  1015. {
  1016. std::map<enum ggml_type, uint32_t> n_type;
  1017. uint32_t n_type_max = 0;
  1018. enum ggml_type type_max = GGML_TYPE_F32;
  1019. for (int i = 0; i < n_tensors; i++) {
  1020. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  1021. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, name);
  1022. n_type[meta->type]++;
  1023. if (n_type_max < n_type[meta->type]) {
  1024. n_type_max = n_type[meta->type];
  1025. type_max = meta->type;
  1026. }
  1027. 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());
  1028. }
  1029. switch (type_max) {
  1030. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  1031. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  1032. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  1033. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  1034. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  1035. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  1036. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  1037. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  1038. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  1039. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  1040. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  1041. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  1042. default:
  1043. {
  1044. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  1045. ftype = LLAMA_FTYPE_ALL_F32;
  1046. } break;
  1047. }
  1048. // this is a way to mark that we have "guessed" the file type
  1049. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  1050. {
  1051. const int kid = gguf_find_key(ctx_gguf, "general.file_type");
  1052. if (kid >= 0) {
  1053. ftype = (llama_ftype) gguf_get_val_u32(ctx_gguf, kid);
  1054. }
  1055. }
  1056. for (int i = 0; i < n_kv; i++) {
  1057. const char * name = gguf_get_key(ctx_gguf, i);
  1058. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  1059. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-8s\n", __func__, i, name, gguf_type_name(type));
  1060. }
  1061. // print type counts
  1062. for (auto & kv : n_type) {
  1063. if (kv.second == 0) {
  1064. continue;
  1065. }
  1066. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  1067. }
  1068. }
  1069. if (!llama_mmap::SUPPORTED) {
  1070. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  1071. use_mmap = false;
  1072. }
  1073. this->use_mmap = use_mmap;
  1074. }
  1075. ~llama_model_loader() {
  1076. if (ctx_gguf) {
  1077. gguf_free(ctx_gguf);
  1078. }
  1079. if (ctx_meta) {
  1080. ggml_free(ctx_meta);
  1081. }
  1082. }
  1083. std::string get_arch_name() const {
  1084. const auto kv = LLM_KV(LLM_ARCH_UNKNOWN);
  1085. std::string arch_name;
  1086. GGUF_GET_KEY(ctx_gguf, arch_name, gguf_get_val_str, GGUF_TYPE_STRING, false, kv(LLM_KV_GENERAL_ARCHITECTURE));
  1087. return arch_name;
  1088. }
  1089. enum llm_arch get_arch() const {
  1090. const std::string arch_name = get_arch_name();
  1091. return llm_arch_from_string(arch_name);
  1092. }
  1093. const char * get_tensor_name(int i) const {
  1094. return gguf_get_tensor_name(ctx_gguf, i);
  1095. }
  1096. struct ggml_tensor * get_tensor_meta(int i) const {
  1097. return ggml_get_tensor(ctx_meta, get_tensor_name(i));
  1098. }
  1099. void calc_sizes(size_t & ctx_size_p, size_t & mmapped_size_p) const {
  1100. ctx_size_p = 0;
  1101. mmapped_size_p = 0;
  1102. for (int i = 0; i < n_tensors; i++) {
  1103. struct ggml_tensor * meta = get_tensor_meta(i);
  1104. ctx_size_p += sizeof(struct ggml_tensor) + GGML_OBJECT_SIZE;
  1105. (use_mmap ? mmapped_size_p : ctx_size_p) += ggml_nbytes_pad(meta);
  1106. }
  1107. }
  1108. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, struct ggml_tensor * meta, ggml_backend backend) {
  1109. if (backend != GGML_BACKEND_CPU) {
  1110. ggml_set_no_alloc(ctx, true);
  1111. }
  1112. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
  1113. tensor->backend = backend; // TODO: ggml_set_backend
  1114. ggml_set_name(tensor, ggml_get_name(meta));
  1115. if (backend != GGML_BACKEND_CPU) {
  1116. ggml_set_no_alloc(ctx, use_mmap);
  1117. }
  1118. n_created++;
  1119. return tensor;
  1120. }
  1121. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, ggml_backend backend) {
  1122. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, name.c_str());
  1123. if (cur == NULL) {
  1124. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  1125. }
  1126. {
  1127. bool is_ok = true;
  1128. for (size_t i = 0; i < ne.size(); ++i) {
  1129. if (ne[i] != cur->ne[i]) {
  1130. is_ok = false;
  1131. break;
  1132. }
  1133. }
  1134. if (!is_ok) {
  1135. throw std::runtime_error(
  1136. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  1137. __func__, name.c_str(),
  1138. llama_format_tensor_shape(ne).c_str(),
  1139. llama_format_tensor_shape(cur).c_str()));
  1140. }
  1141. }
  1142. return create_tensor_for(ctx, cur, backend);
  1143. }
  1144. void done_getting_tensors() const {
  1145. if (n_created != n_tensors) {
  1146. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  1147. }
  1148. }
  1149. size_t file_offset(const char * name) const {
  1150. const int idx = gguf_find_tensor(ctx_gguf, name);
  1151. if (idx < 0) {
  1152. throw std::runtime_error(format("%s: tensor '%s' not found in the file", __func__, name));
  1153. }
  1154. return gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, idx);
  1155. }
  1156. void load_data_for(struct ggml_tensor * cur) const {
  1157. const size_t offs = file_offset(ggml_get_name(cur));
  1158. if (use_mmap) {
  1159. cur->data = (uint8_t *) mapping->addr + offs;
  1160. } else {
  1161. file.seek(offs, SEEK_SET);
  1162. file.read_raw(cur->data, ggml_nbytes(cur));
  1163. }
  1164. }
  1165. void load_all_data(struct ggml_context * ctx, llama_progress_callback progress_callback, void * progress_callback_user_data, llama_mlock * lmlock) {
  1166. size_t size_data = 0;
  1167. size_t size_lock = 0;
  1168. size_t size_pref = 0; // prefetch
  1169. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  1170. struct ggml_tensor * cur = ggml_get_tensor(ctx, gguf_get_tensor_name(ctx_gguf, i));
  1171. size_data += ggml_nbytes(cur);
  1172. if (cur->backend == GGML_BACKEND_CPU) {
  1173. size_pref += ggml_nbytes(cur);
  1174. }
  1175. }
  1176. if (use_mmap) {
  1177. mapping.reset(new llama_mmap(&file, size_pref, ggml_is_numa()));
  1178. if (lmlock) {
  1179. lmlock->init(mapping->addr);
  1180. }
  1181. }
  1182. size_t done_size = 0;
  1183. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  1184. struct ggml_tensor * cur = ggml_get_tensor(ctx, gguf_get_tensor_name(ctx_gguf, i));
  1185. GGML_ASSERT(cur); // unused tensors should have been caught by load_data already
  1186. if (progress_callback) {
  1187. progress_callback((float) done_size / size_data, progress_callback_user_data);
  1188. }
  1189. // allocate temp buffer if not using mmap
  1190. if (!use_mmap && cur->data == NULL) {
  1191. GGML_ASSERT(cur->backend != GGML_BACKEND_CPU);
  1192. cur->data = malloc(ggml_nbytes(cur));
  1193. }
  1194. load_data_for(cur);
  1195. switch (cur->backend) {
  1196. case GGML_BACKEND_CPU:
  1197. if (use_mmap && lmlock) {
  1198. size_lock += ggml_nbytes(cur);
  1199. lmlock->grow_to(size_lock);
  1200. }
  1201. break;
  1202. #if defined(GGML_USE_CUBLAS)
  1203. case GGML_BACKEND_GPU:
  1204. case GGML_BACKEND_GPU_SPLIT:
  1205. // old code:
  1206. //ggml_cuda_transform_tensor(lt.data, lt.ggml_tensor);
  1207. // TODO: test if this works !!
  1208. ggml_cuda_transform_tensor(cur->data, cur);
  1209. if (!use_mmap) {
  1210. free(cur->data);
  1211. }
  1212. break;
  1213. #elif defined(GGML_USE_CLBLAST)
  1214. case GGML_BACKEND_GPU:
  1215. ggml_cl_transform_tensor(cur->data, cur);
  1216. if (!use_mmap) {
  1217. free(cur->data);
  1218. }
  1219. break;
  1220. #endif
  1221. default:
  1222. continue;
  1223. }
  1224. done_size += ggml_nbytes(cur);
  1225. }
  1226. }
  1227. };
  1228. //
  1229. // load LLaMA models
  1230. //
  1231. std::string llama_model_ftype_name(enum llama_ftype ftype) {
  1232. if (ftype & LLAMA_FTYPE_GUESSED) {
  1233. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  1234. }
  1235. switch (ftype) {
  1236. case LLAMA_FTYPE_ALL_F32: return "all F32";
  1237. case LLAMA_FTYPE_MOSTLY_F16: return "mostly F16";
  1238. case LLAMA_FTYPE_MOSTLY_Q4_0: return "mostly Q4_0";
  1239. case LLAMA_FTYPE_MOSTLY_Q4_1: return "mostly Q4_1";
  1240. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  1241. return "mostly Q4_1, some F16";
  1242. case LLAMA_FTYPE_MOSTLY_Q5_0: return "mostly Q5_0";
  1243. case LLAMA_FTYPE_MOSTLY_Q5_1: return "mostly Q5_1";
  1244. case LLAMA_FTYPE_MOSTLY_Q8_0: return "mostly Q8_0";
  1245. // K-quants
  1246. case LLAMA_FTYPE_MOSTLY_Q2_K: return "mostly Q2_K";
  1247. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "mostly Q3_K - Small";
  1248. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "mostly Q3_K - Medium";
  1249. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "mostly Q3_K - Large";
  1250. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "mostly Q4_K - Small";
  1251. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "mostly Q4_K - Medium";
  1252. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "mostly Q5_K - Small";
  1253. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "mostly Q5_K - Medium";
  1254. case LLAMA_FTYPE_MOSTLY_Q6_K: return "mostly Q6_K";
  1255. default: return "unknown, may not work";
  1256. }
  1257. }
  1258. static const char * llama_model_type_name(e_model type) {
  1259. switch (type) {
  1260. case MODEL_3B: return "3B";
  1261. case MODEL_7B: return "7B";
  1262. case MODEL_13B: return "13B";
  1263. case MODEL_30B: return "30B";
  1264. case MODEL_34B: return "34B";
  1265. case MODEL_40B: return "40B";
  1266. case MODEL_65B: return "65B";
  1267. case MODEL_70B: return "70B";
  1268. default: return "?B";
  1269. }
  1270. }
  1271. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  1272. model.arch = ml.get_arch();
  1273. if (model.arch == LLM_ARCH_UNKNOWN) {
  1274. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  1275. }
  1276. }
  1277. static void llm_load_hparams(
  1278. llama_model_loader & ml,
  1279. llama_model & model,
  1280. int n_ctx,
  1281. float rope_freq_base,
  1282. float rope_freq_scale) {
  1283. struct gguf_context * ctx = ml.ctx_gguf;
  1284. const auto kv = LLM_KV(model.arch);
  1285. auto & hparams = model.hparams;
  1286. // get general kv
  1287. GGUF_GET_KEY(ctx, model.name, gguf_get_val_str, GGUF_TYPE_STRING, false, kv(LLM_KV_GENERAL_NAME));
  1288. // get hparams kv
  1289. GGUF_GET_KEY(ctx, hparams.n_vocab, gguf_get_arr_n, GGUF_TYPE_ARRAY, true, kv(LLM_KV_TOKENIZER_LIST));
  1290. GGUF_GET_KEY(ctx, hparams.n_ctx_train, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_CONTEXT_LENGTH));
  1291. GGUF_GET_KEY(ctx, hparams.n_embd, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_EMBEDDING_LENGTH));
  1292. GGUF_GET_KEY(ctx, hparams.n_ff, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_FEED_FORWARD_LENGTH));
  1293. GGUF_GET_KEY(ctx, hparams.n_head, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_ATTENTION_HEAD_COUNT));
  1294. GGUF_GET_KEY(ctx, hparams.n_layer, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_BLOCK_COUNT));
  1295. // n_head_kv is optional, default to n_head
  1296. hparams.n_head_kv = hparams.n_head;
  1297. GGUF_GET_KEY(ctx, hparams.n_head_kv, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_ATTENTION_HEAD_COUNT_KV));
  1298. // TODO: manually setting rope freq base and scale should override this
  1299. // FIXME: partial fix when the param specified is not the default value, but
  1300. // will not work for overriding the model value to the params default
  1301. llama_context_params defaults = llama_context_default_params();
  1302. // rope_freq_base
  1303. {
  1304. float ropebase = 10000.0f;
  1305. GGUF_GET_KEY(ctx, ropebase, gguf_get_val_f32, GGUF_TYPE_FLOAT32, false, kv(LLM_KV_ROPE_FREQ_BASE));
  1306. if (ropebase != 10000.0f && rope_freq_base == defaults.rope_freq_base) {
  1307. rope_freq_base = ropebase;
  1308. }
  1309. }
  1310. // rope_freq_scale (inverse of the kv) is optional
  1311. {
  1312. float ropescale = 1.0f;
  1313. GGUF_GET_KEY(ctx, ropescale, gguf_get_val_f32, GGUF_TYPE_FLOAT32, false, kv(LLM_KV_ROPE_SCALE_LINEAR));
  1314. if (ropescale != 1.0f && rope_freq_scale == defaults.rope_freq_scale) {
  1315. rope_freq_scale = 1.0f/ropescale;
  1316. }
  1317. }
  1318. // sanity check for n_rot (optional)
  1319. {
  1320. hparams.n_rot = hparams.n_embd / hparams.n_head;
  1321. GGUF_GET_KEY(ctx, hparams.n_rot, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_ROPE_DIMENSION_COUNT));
  1322. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  1323. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  1324. }
  1325. }
  1326. // arch-specific KVs
  1327. switch (model.arch) {
  1328. case LLM_ARCH_LLAMA:
  1329. {
  1330. GGUF_GET_KEY(ctx, hparams.f_norm_rms_eps, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, kv(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS));
  1331. switch (hparams.n_layer) {
  1332. case 26: model.type = e_model::MODEL_3B; break;
  1333. case 32: model.type = e_model::MODEL_7B; break;
  1334. case 40: model.type = e_model::MODEL_13B; break;
  1335. case 48: model.type = e_model::MODEL_34B; break;
  1336. case 60: model.type = e_model::MODEL_30B; break;
  1337. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  1338. default: model.type = e_model::MODEL_UNKNOWN;
  1339. }
  1340. } break;
  1341. case LLM_ARCH_FALCON:
  1342. {
  1343. GGUF_GET_KEY(ctx, hparams.f_norm_eps, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, kv(LLM_KV_ATTENTION_LAYERNORM_EPS));
  1344. switch (hparams.n_layer) {
  1345. case 32: model.type = e_model::MODEL_7B; break;
  1346. case 60: model.type = e_model::MODEL_40B; break;
  1347. default: model.type = e_model::MODEL_UNKNOWN;
  1348. }
  1349. } break;
  1350. default: (void)0;
  1351. };
  1352. model.ftype = ml.ftype;
  1353. hparams.n_ctx = n_ctx;
  1354. hparams.rope_freq_base = rope_freq_base;
  1355. hparams.rope_freq_scale = rope_freq_scale;
  1356. }
  1357. // TODO: This should probably be in llama.h
  1358. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, const std::string & raw_text, bool bos, bool escape);
  1359. static void llm_load_vocab(
  1360. llama_model_loader & ml,
  1361. llama_model & model) {
  1362. auto & vocab = model.vocab;
  1363. struct gguf_context * ctx = ml.ctx_gguf;
  1364. const auto kv = LLM_KV(model.arch);
  1365. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  1366. if (token_idx == -1) {
  1367. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  1368. }
  1369. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  1370. if (score_idx == -1) {
  1371. throw std::runtime_error("cannot find tokenizer scores in model file\n");
  1372. }
  1373. const float * scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  1374. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  1375. if (toktype_idx == -1) {
  1376. throw std::runtime_error("cannot find token type list in GGUF file\n");
  1377. }
  1378. const int * toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  1379. // determine vocab type
  1380. {
  1381. std::string tokenizer_name;
  1382. GGUF_GET_KEY(ctx, tokenizer_name, gguf_get_val_str, GGUF_TYPE_STRING, true, kv(LLM_KV_TOKENIZER_MODEL));
  1383. if (tokenizer_name == "llama") {
  1384. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  1385. // default special tokens
  1386. vocab.special_bos_id = 1;
  1387. vocab.special_eos_id = 2;
  1388. vocab.special_unk_id = 0;
  1389. vocab.special_sep_id = -1;
  1390. vocab.special_pad_id = -1;
  1391. } else if (tokenizer_name == "gpt2") {
  1392. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  1393. // read bpe merges and populate bpe ranks
  1394. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  1395. if (merges_keyidx == -1) {
  1396. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  1397. }
  1398. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  1399. for (int i = 0; i < n_merges; i++) {
  1400. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  1401. std::string first;
  1402. std::string second;
  1403. const size_t pos = word.find(' ', 1);
  1404. if (pos != std::string::npos) {
  1405. first = word.substr(0, pos);
  1406. second = word.substr(pos + 1);
  1407. }
  1408. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  1409. }
  1410. // default special tokens
  1411. vocab.special_bos_id = 11;
  1412. vocab.special_eos_id = 11;
  1413. vocab.special_unk_id = -1;
  1414. vocab.special_sep_id = -1;
  1415. vocab.special_pad_id = -1;
  1416. } else {
  1417. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  1418. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  1419. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  1420. }
  1421. }
  1422. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  1423. vocab.id_to_token.resize(n_vocab);
  1424. for (uint32_t i = 0; i < n_vocab; i++) {
  1425. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  1426. vocab.token_to_id[word] = i;
  1427. auto & token_data = vocab.id_to_token[i];
  1428. token_data.text = std::move(word);
  1429. token_data.score = scores[i];
  1430. token_data.type = (llama_token_type) toktypes[i];
  1431. }
  1432. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  1433. vocab.linefeed_id = llama_tokenize_internal(vocab, "\n", false, false)[0];
  1434. // special tokens
  1435. GGUF_GET_KEY(ctx, vocab.special_bos_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_BOS_ID));
  1436. GGUF_GET_KEY(ctx, vocab.special_eos_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_EOS_ID));
  1437. GGUF_GET_KEY(ctx, vocab.special_unk_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_UNK_ID));
  1438. GGUF_GET_KEY(ctx, vocab.special_sep_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_SEP_ID));
  1439. GGUF_GET_KEY(ctx, vocab.special_pad_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_PAD_ID));
  1440. }
  1441. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  1442. const auto & hparams = model.hparams;
  1443. const auto & vocab = model.vocab;
  1444. // hparams
  1445. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  1446. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch).c_str());
  1447. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, vocab.type == LLAMA_VOCAB_TYPE_SPM ? "SPM" : "BPE"); // TODO: fix
  1448. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  1449. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  1450. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  1451. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, hparams.n_ctx);
  1452. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  1453. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  1454. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  1455. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  1456. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot); // a.k.a. n_embd_head, n_head_dim
  1457. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  1458. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  1459. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  1460. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  1461. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, hparams.rope_freq_base);
  1462. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, hparams.rope_freq_scale);
  1463. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  1464. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  1465. LLAMA_LOG_INFO("%s: model size = %.2f B\n", __func__, ml.n_elements*1e-9);
  1466. // general kv
  1467. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  1468. // special tokens
  1469. 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() ); }
  1470. 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() ); }
  1471. 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() ); }
  1472. 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() ); }
  1473. 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() ); }
  1474. 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() ); }
  1475. }
  1476. static void llm_load_tensors(
  1477. llama_model_loader & ml,
  1478. llama_model & model,
  1479. int n_batch,
  1480. int n_gpu_layers,
  1481. int main_gpu,
  1482. const float * tensor_split,
  1483. const bool mul_mat_q,
  1484. bool low_vram,
  1485. ggml_type memory_type,
  1486. bool use_mlock,
  1487. llama_progress_callback progress_callback,
  1488. void * progress_callback_user_data) {
  1489. model.t_start_us = ggml_time_us();
  1490. auto & ctx = model.ctx;
  1491. auto & hparams = model.hparams;
  1492. model.n_gpu_layers = n_gpu_layers;
  1493. size_t ctx_size;
  1494. size_t mmapped_size;
  1495. ml.calc_sizes(ctx_size, mmapped_size);
  1496. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MB\n", __func__, ctx_size/1024.0/1024.0);
  1497. // create the ggml context
  1498. {
  1499. model.buf.resize(ctx_size);
  1500. if (use_mlock) {
  1501. model.mlock_buf.init (model.buf.data);
  1502. model.mlock_buf.grow_to(model.buf.size);
  1503. }
  1504. struct ggml_init_params params = {
  1505. /*.mem_size =*/ model.buf.size,
  1506. /*.mem_buffer =*/ model.buf.data,
  1507. /*.no_alloc =*/ ml.use_mmap,
  1508. };
  1509. model.ctx = ggml_init(params);
  1510. if (!model.ctx) {
  1511. throw std::runtime_error(format("ggml_init() failed"));
  1512. }
  1513. }
  1514. (void) main_gpu;
  1515. (void) mul_mat_q;
  1516. #if defined(GGML_USE_CUBLAS)
  1517. LLAMA_LOG_INFO("%s: using " GGML_CUDA_NAME " for GPU acceleration\n", __func__);
  1518. ggml_cuda_set_main_device(main_gpu);
  1519. ggml_cuda_set_mul_mat_q(mul_mat_q);
  1520. #define LLAMA_BACKEND_OFFLOAD GGML_BACKEND_GPU
  1521. #define LLAMA_BACKEND_OFFLOAD_SPLIT GGML_BACKEND_GPU_SPLIT
  1522. #elif defined(GGML_USE_CLBLAST)
  1523. LLAMA_LOG_INFO("%s: using OpenCL for GPU acceleration\n", __func__);
  1524. #define LLAMA_BACKEND_OFFLOAD GGML_BACKEND_GPU
  1525. #define LLAMA_BACKEND_OFFLOAD_SPLIT GGML_BACKEND_GPU
  1526. #else
  1527. #define LLAMA_BACKEND_OFFLOAD GGML_BACKEND_CPU
  1528. #define LLAMA_BACKEND_OFFLOAD_SPLIT GGML_BACKEND_CPU
  1529. #endif
  1530. // prepare memory for the weights
  1531. size_t vram_weights = 0;
  1532. {
  1533. const int64_t n_embd = hparams.n_embd;
  1534. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  1535. const int64_t n_layer = hparams.n_layer;
  1536. const int64_t n_vocab = hparams.n_vocab;
  1537. const auto tn = LLM_TN(model.arch);
  1538. switch (model.arch) {
  1539. case LLM_ARCH_LLAMA:
  1540. {
  1541. model.tok_embeddings = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, GGML_BACKEND_CPU);
  1542. // output
  1543. {
  1544. ggml_backend backend_norm;
  1545. ggml_backend backend_output;
  1546. if (n_gpu_layers > int(n_layer)) {
  1547. // norm is not performance relevant on its own but keeping it in VRAM reduces data copying
  1548. // on Windows however this is detrimental unless everything is on the GPU
  1549. #ifndef _WIN32
  1550. backend_norm = low_vram ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  1551. #else
  1552. backend_norm = low_vram || n_gpu_layers <= (int) n_layer + 2 ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  1553. #endif // _WIN32
  1554. backend_output = LLAMA_BACKEND_OFFLOAD_SPLIT;
  1555. } else {
  1556. backend_norm = GGML_BACKEND_CPU;
  1557. backend_output = GGML_BACKEND_CPU;
  1558. }
  1559. model.output_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, backend_norm);
  1560. model.output = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, backend_output);
  1561. if (backend_norm == GGML_BACKEND_GPU) {
  1562. vram_weights += ggml_nbytes(model.output_norm);
  1563. }
  1564. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  1565. vram_weights += ggml_nbytes(model.output);
  1566. }
  1567. }
  1568. const uint32_t n_ff = hparams.n_ff;
  1569. const int i_gpu_start = n_layer - n_gpu_layers;
  1570. model.layers.resize(n_layer);
  1571. for (uint32_t i = 0; i < n_layer; ++i) {
  1572. const ggml_backend backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD; // NOLINT
  1573. const ggml_backend backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD_SPLIT; // NOLINT
  1574. auto & layer = model.layers[i];
  1575. layer.attn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, backend);
  1576. layer.wq = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, backend_split);
  1577. layer.wk = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, backend_split);
  1578. layer.wv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, backend_split);
  1579. layer.wo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, backend_split);
  1580. layer.ffn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, backend);
  1581. layer.w1 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, backend_split);
  1582. layer.w2 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, backend_split);
  1583. layer.w3 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, backend_split);
  1584. if (backend == GGML_BACKEND_GPU) {
  1585. vram_weights +=
  1586. ggml_nbytes(layer.attn_norm) + ggml_nbytes(layer.wq) + ggml_nbytes(layer.wk) +
  1587. ggml_nbytes(layer.wv) + ggml_nbytes(layer.wo) + ggml_nbytes(layer.ffn_norm) +
  1588. ggml_nbytes(layer.w1) + ggml_nbytes(layer.w2) + ggml_nbytes(layer.w3);
  1589. }
  1590. }
  1591. } break;
  1592. case LLM_ARCH_FALCON:
  1593. {
  1594. // TODO: CPU-only for now
  1595. model.tok_embeddings = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, GGML_BACKEND_CPU);
  1596. // output
  1597. {
  1598. ggml_backend backend_norm;
  1599. ggml_backend backend_output;
  1600. if (n_gpu_layers > int(n_layer)) {
  1601. // norm is not performance relevant on its own but keeping it in VRAM reduces data copying
  1602. // on Windows however this is detrimental unless everything is on the GPU
  1603. #ifndef _WIN32
  1604. backend_norm = low_vram ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  1605. #else
  1606. backend_norm = low_vram || n_gpu_layers <= (int) n_layer + 2 ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  1607. #endif // _WIN32
  1608. backend_output = LLAMA_BACKEND_OFFLOAD_SPLIT;
  1609. } else {
  1610. backend_norm = GGML_BACKEND_CPU;
  1611. backend_output = GGML_BACKEND_CPU;
  1612. }
  1613. model.output_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, backend_norm);
  1614. model.output_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, backend_norm);
  1615. model.output = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, backend_output);
  1616. if (backend_norm == GGML_BACKEND_GPU) {
  1617. vram_weights += ggml_nbytes(model.output_norm);
  1618. vram_weights += ggml_nbytes(model.output_norm_b);
  1619. }
  1620. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  1621. vram_weights += ggml_nbytes(model.output);
  1622. }
  1623. }
  1624. const uint32_t n_ff = hparams.n_ff;
  1625. const int i_gpu_start = n_layer - n_gpu_layers;
  1626. model.layers.resize(n_layer);
  1627. for (uint32_t i = 0; i < n_layer; ++i) {
  1628. const ggml_backend backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD; // NOLINT
  1629. const ggml_backend backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD_SPLIT; // NOLINT
  1630. auto & layer = model.layers[i];
  1631. layer.attn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, backend);
  1632. layer.attn_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, backend);
  1633. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i).c_str()) >= 0) {
  1634. layer.attn_norm_2 = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd}, backend);
  1635. layer.attn_norm_2_b = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd}, backend);
  1636. if (backend == GGML_BACKEND_GPU) {
  1637. vram_weights += ggml_nbytes(layer.attn_norm_2);
  1638. vram_weights += ggml_nbytes(layer.attn_norm_2_b);
  1639. }
  1640. }
  1641. layer.wqkv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, backend_split);
  1642. layer.wo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, backend_split);
  1643. layer.w2 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, backend_split);
  1644. layer.w3 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, backend_split);
  1645. if (backend == GGML_BACKEND_GPU) {
  1646. vram_weights +=
  1647. ggml_nbytes(layer.attn_norm) + ggml_nbytes(layer.attn_norm_b) +
  1648. ggml_nbytes(layer.wqkv) + ggml_nbytes(layer.wo) +
  1649. ggml_nbytes(layer.w2) + ggml_nbytes(layer.w3);
  1650. }
  1651. }
  1652. } break;
  1653. default:
  1654. throw std::runtime_error("unknown architecture");
  1655. };
  1656. }
  1657. ml.done_getting_tensors();
  1658. // print memory requirements
  1659. {
  1660. const size_t scale = memory_type == GGML_TYPE_F32 ? 2 : 1;
  1661. // this is the total memory required to run the inference
  1662. size_t mem_required =
  1663. ctx_size +
  1664. mmapped_size - vram_weights; // weights in VRAM not in memory
  1665. // this is the memory required by one llama_state
  1666. const size_t mem_required_state = scale*hparams.kv_size();
  1667. LLAMA_LOG_INFO("%s: mem required = %7.2f MB (+ %7.2f MB per state)\n", __func__,
  1668. mem_required / 1024.0 / 1024.0, mem_required_state / 1024.0 / 1024.0);
  1669. (void) n_batch;
  1670. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST)
  1671. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  1672. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  1673. if (n_gpu_layers > (int) hparams.n_layer) {
  1674. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  1675. }
  1676. size_t vram_kv_cache = 0;
  1677. #ifdef GGML_USE_CUBLAS
  1678. const int max_backend_supported_layers = hparams.n_layer + 3;
  1679. const int max_offloadable_layers = low_vram ? hparams.n_layer + 1 : hparams.n_layer + 3;
  1680. if (n_gpu_layers > (int) hparams.n_layer + 1) {
  1681. if (low_vram) {
  1682. LLAMA_LOG_INFO("%s: cannot offload v cache to GPU due to low VRAM option\n", __func__);
  1683. } else {
  1684. LLAMA_LOG_INFO("%s: offloading v cache to GPU\n", __func__);
  1685. vram_kv_cache += hparams.kv_size() / 2;
  1686. }
  1687. }
  1688. if (n_gpu_layers > (int) hparams.n_layer + 2) {
  1689. if (low_vram) {
  1690. LLAMA_LOG_WARN("%s: cannot offload k cache to GPU due to low VRAM option\n", __func__);
  1691. } else {
  1692. LLAMA_LOG_INFO("%s: offloading k cache to GPU\n", __func__);
  1693. vram_kv_cache += hparams.kv_size() / 2;
  1694. }
  1695. }
  1696. #elif defined(GGML_USE_CLBLAST)
  1697. const int max_backend_supported_layers = hparams.n_layer + 1;
  1698. const int max_offloadable_layers = hparams.n_layer + 1;
  1699. #endif // GGML_USE_CUBLAS
  1700. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n",
  1701. __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  1702. LLAMA_LOG_INFO("%s: VRAM used: %zu MB\n",
  1703. __func__, (vram_weights + vram_kv_cache + MB - 1) / MB); // round up
  1704. #else
  1705. (void) n_gpu_layers;
  1706. #endif // defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST)
  1707. }
  1708. // populate `tensors_by_name`
  1709. for (int i = 0; i < ml.n_tensors; ++i) {
  1710. struct ggml_tensor * cur = ggml_get_tensor(ctx, ml.get_tensor_name(i));
  1711. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  1712. }
  1713. (void) tensor_split;
  1714. #if defined(GGML_USE_CUBLAS)
  1715. {
  1716. ggml_cuda_set_tensor_split(tensor_split);
  1717. }
  1718. #endif
  1719. ml.load_all_data(ctx, progress_callback, progress_callback_user_data, use_mlock ? &model.mlock_mmap : NULL);
  1720. if (progress_callback) {
  1721. progress_callback(1.0f, progress_callback_user_data);
  1722. }
  1723. model.mapping = std::move(ml.mapping);
  1724. // loading time will be recalculate after the first eval, so
  1725. // we take page faults deferred by mmap() into consideration
  1726. model.t_load_us = ggml_time_us() - model.t_start_us;
  1727. }
  1728. static bool llama_model_load(
  1729. const std::string & fname,
  1730. llama_model & model,
  1731. int n_ctx,
  1732. int n_batch,
  1733. int n_gpu_layers,
  1734. int main_gpu,
  1735. const float * tensor_split,
  1736. const bool mul_mat_q,
  1737. float rope_freq_base,
  1738. float rope_freq_scale,
  1739. bool low_vram,
  1740. ggml_type memory_type,
  1741. bool use_mmap,
  1742. bool use_mlock,
  1743. bool vocab_only,
  1744. llama_progress_callback progress_callback,
  1745. void *progress_callback_user_data) {
  1746. try {
  1747. std::unique_ptr<llama_model_loader> ml(new llama_model_loader(fname, use_mmap));
  1748. llm_load_arch (*ml, model);
  1749. llm_load_hparams(*ml, model, n_ctx, rope_freq_base, rope_freq_scale);
  1750. llm_load_vocab (*ml, model);
  1751. llm_load_print_meta(*ml, model);
  1752. if (model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  1753. throw std::runtime_error("vocab size mismatch");
  1754. }
  1755. if (vocab_only) {
  1756. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  1757. return true;
  1758. }
  1759. llm_load_tensors(
  1760. *ml, model, n_batch, n_gpu_layers,
  1761. main_gpu, tensor_split, mul_mat_q, low_vram, memory_type,
  1762. use_mlock, progress_callback, progress_callback_user_data);
  1763. } catch (const std::exception & err) {
  1764. LLAMA_LOG_ERROR("error loading model: %s\n", err.what());
  1765. return false;
  1766. }
  1767. return true;
  1768. }
  1769. static struct ggml_cgraph * llm_build_llama(
  1770. llama_context & lctx,
  1771. const llama_token * tokens,
  1772. const float * embd,
  1773. int n_tokens,
  1774. int n_past) {
  1775. GGML_ASSERT((!tokens && embd) || (tokens && !embd)); // NOLINT
  1776. const int N = n_tokens;
  1777. const auto & model = lctx.model;
  1778. const auto & hparams = model.hparams;
  1779. const auto & kv_self = lctx.kv_self;
  1780. GGML_ASSERT(!!kv_self.ctx);
  1781. const int64_t n_embd = hparams.n_embd;
  1782. const int64_t n_layer = hparams.n_layer;
  1783. const int64_t n_ctx = hparams.n_ctx;
  1784. const int64_t n_head = hparams.n_head;
  1785. const int64_t n_head_kv = hparams.n_head_kv;
  1786. const int64_t n_embd_head = hparams.n_embd_head();
  1787. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  1788. GGML_ASSERT(n_embd_head == hparams.n_rot);
  1789. const float freq_base = hparams.rope_freq_base;
  1790. const float freq_scale = hparams.rope_freq_scale;
  1791. const float norm_rms_eps = hparams.f_norm_rms_eps;
  1792. const int n_gpu_layers = model.n_gpu_layers;
  1793. auto & buf_compute = lctx.buf_compute;
  1794. struct ggml_init_params params = {
  1795. /*.mem_size =*/ buf_compute.size,
  1796. /*.mem_buffer =*/ buf_compute.data,
  1797. /*.no_alloc =*/ false,
  1798. };
  1799. params.no_alloc = true;
  1800. struct ggml_context * ctx0 = ggml_init(params);
  1801. ggml_cgraph * gf = ggml_new_graph(ctx0);
  1802. struct ggml_tensor * cur;
  1803. struct ggml_tensor * inpL;
  1804. if (tokens) {
  1805. struct ggml_tensor * inp_tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  1806. ggml_allocr_alloc(lctx.alloc, inp_tokens);
  1807. if (!ggml_allocr_is_measure(lctx.alloc)) {
  1808. memcpy(inp_tokens->data, tokens, N*ggml_element_size(inp_tokens));
  1809. }
  1810. ggml_set_name(inp_tokens, "inp_tokens");
  1811. inpL = ggml_get_rows(ctx0, model.tok_embeddings, inp_tokens);
  1812. } else {
  1813. #ifdef GGML_USE_MPI
  1814. GGML_ASSERT(false && "not implemented");
  1815. #endif
  1816. inpL = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N);
  1817. ggml_allocr_alloc(lctx.alloc, inpL);
  1818. if (!ggml_allocr_is_measure(lctx.alloc)) {
  1819. memcpy(inpL->data, embd, N * n_embd * ggml_element_size(inpL));
  1820. }
  1821. }
  1822. const int i_gpu_start = n_layer - n_gpu_layers;
  1823. (void) i_gpu_start;
  1824. // offload functions set the tensor output backend to GPU
  1825. // tensors are GPU-accelerated if any input or the output has been offloaded
  1826. //
  1827. // with the low VRAM option VRAM scratch is disabled in llama_load_model_internal
  1828. // in that case ggml_cuda_assign_buffers has no effect
  1829. offload_func_t offload_func_nr = llama_nop; // nr = non-repeating
  1830. offload_func_t offload_func_kq = llama_nop;
  1831. offload_func_t offload_func_v = llama_nop;
  1832. #ifdef GGML_USE_CUBLAS
  1833. if (n_gpu_layers > n_layer) {
  1834. offload_func_nr = ggml_cuda_assign_buffers_no_alloc;
  1835. }
  1836. if (n_gpu_layers > n_layer + 1) {
  1837. offload_func_v = ggml_cuda_assign_buffers_no_alloc;
  1838. }
  1839. if (n_gpu_layers > n_layer + 2) {
  1840. offload_func_kq = ggml_cuda_assign_buffers_no_alloc;
  1841. }
  1842. #endif // GGML_USE_CUBLAS
  1843. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  1844. ggml_allocr_alloc(lctx.alloc, KQ_scale);
  1845. if (!ggml_allocr_is_measure(lctx.alloc)) {
  1846. ggml_set_f32(KQ_scale, 1.0f/sqrtf(float(n_embd)/n_head));
  1847. }
  1848. ggml_set_name(KQ_scale, "1/sqrt(n_embd_head)");
  1849. for (int il = 0; il < n_layer; ++il) {
  1850. ggml_format_name(inpL, "layer_inp_%d", il);
  1851. offload_func_t offload_func = llama_nop;
  1852. #ifdef GGML_USE_CUBLAS
  1853. if (il >= i_gpu_start) {
  1854. offload_func = ggml_cuda_assign_buffers_no_alloc;
  1855. }
  1856. #endif // GGML_USE_CUBLAS
  1857. struct ggml_tensor * inpSA = inpL;
  1858. // norm
  1859. {
  1860. cur = ggml_rms_norm(ctx0, inpL, norm_rms_eps);
  1861. offload_func(cur);
  1862. ggml_set_name(cur, "rms_norm_0");
  1863. // cur = cur*attn_norm(broadcasted)
  1864. cur = ggml_mul(ctx0, cur, model.layers[il].attn_norm);
  1865. offload_func(cur);
  1866. ggml_set_name(cur, "attention_norm_0");
  1867. }
  1868. // self-attention
  1869. {
  1870. // compute Q and K and RoPE them
  1871. struct ggml_tensor * tmpk = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  1872. offload_func_kq(tmpk);
  1873. ggml_set_name(tmpk, "tmpk");
  1874. struct ggml_tensor * tmpq = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  1875. offload_func_kq(tmpq);
  1876. ggml_set_name(tmpq, "tmpq");
  1877. struct ggml_tensor * Kcur = ggml_rope_custom_inplace(ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, N), n_past, n_embd_head, 0, 0, freq_base, freq_scale);
  1878. offload_func_kq(Kcur);
  1879. ggml_set_name(Kcur, "Kcur");
  1880. struct ggml_tensor * Qcur = ggml_rope_custom_inplace(ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, N), n_past, n_embd_head, 0, 0, freq_base, freq_scale);
  1881. offload_func_kq(Qcur);
  1882. ggml_set_name(Qcur, "Qcur");
  1883. // store key and value to memory
  1884. {
  1885. // compute the transposed [N, n_embd] V matrix
  1886. struct ggml_tensor * tmpv = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  1887. offload_func_v(tmpv);
  1888. ggml_set_name(tmpv, "tmpv");
  1889. struct ggml_tensor * Vcur = ggml_transpose(ctx0, ggml_reshape_2d(ctx0, tmpv, n_embd_gqa, N));
  1890. offload_func_v(Vcur);
  1891. ggml_set_name(Vcur, "Vcur");
  1892. struct ggml_tensor * k = ggml_view_1d(ctx0, kv_self.k, N*n_embd_gqa, (ggml_element_size(kv_self.k)*n_embd_gqa)*(il*n_ctx + n_past));
  1893. offload_func_kq(k);
  1894. ggml_set_name(k, "k");
  1895. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd_gqa,
  1896. ( n_ctx)*ggml_element_size(kv_self.v),
  1897. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd_gqa + n_past*ggml_element_size(kv_self.v));
  1898. offload_func_v(v);
  1899. ggml_set_name(v, "v");
  1900. // important: storing RoPE-ed version of K in the KV cache!
  1901. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
  1902. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
  1903. }
  1904. struct ggml_tensor * Q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  1905. offload_func_kq(Q);
  1906. ggml_set_name(Q, "Q");
  1907. struct ggml_tensor * K =
  1908. ggml_view_3d(ctx0, kv_self.k,
  1909. n_embd_head, n_past + N, n_head_kv,
  1910. ggml_element_size(kv_self.k)*n_embd_gqa,
  1911. ggml_element_size(kv_self.k)*n_embd_head,
  1912. ggml_element_size(kv_self.k)*n_embd_gqa*n_ctx*il);
  1913. offload_func_kq(K);
  1914. ggml_set_name(K, "K");
  1915. // K * Q
  1916. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  1917. offload_func_kq(KQ);
  1918. ggml_set_name(KQ, "KQ");
  1919. // KQ_scaled = KQ / sqrt(n_embd_head)
  1920. // KQ_scaled shape [n_past + N, N, n_head, 1]
  1921. struct ggml_tensor * KQ_scaled = ggml_scale_inplace(ctx0, KQ, KQ_scale);
  1922. offload_func_kq(KQ_scaled);
  1923. ggml_set_name(KQ_scaled, "KQ_scaled");
  1924. // KQ_masked = mask_past(KQ_scaled)
  1925. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf_inplace(ctx0, KQ_scaled, n_past);
  1926. offload_func_kq(KQ_masked);
  1927. ggml_set_name(KQ_masked, "KQ_masked");
  1928. // KQ = soft_max(KQ_masked)
  1929. struct ggml_tensor * KQ_soft_max = ggml_soft_max_inplace(ctx0, KQ_masked);
  1930. offload_func_v(KQ_soft_max);
  1931. ggml_set_name(KQ_soft_max, "KQ_soft_max");
  1932. // split cached V into n_head heads
  1933. struct ggml_tensor * V =
  1934. ggml_view_3d(ctx0, kv_self.v,
  1935. n_past + N, n_embd_head, n_head_kv,
  1936. ggml_element_size(kv_self.v)*n_ctx,
  1937. ggml_element_size(kv_self.v)*n_ctx*n_embd_head,
  1938. ggml_element_size(kv_self.v)*n_ctx*n_embd_gqa*il);
  1939. offload_func_v(V);
  1940. ggml_set_name(V, "V");
  1941. #if 1
  1942. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  1943. offload_func_v(KQV);
  1944. ggml_set_name(KQV, "KQV");
  1945. #else
  1946. // make V contiguous in memory to speed up the matmul, however we waste time on the copy
  1947. // on M1 this is faster for the perplexity computation, but ~5% slower for the single-token generation
  1948. // is there a better way?
  1949. struct ggml_tensor * V_cont = ggml_cpy(ctx0, V, ggml_new_tensor_3d(ctx0, kv_self.v->type, n_past + N, n_embd_head, n_head));
  1950. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V_cont, KQ_soft_max);
  1951. #endif
  1952. // KQV_merged = KQV.permute(0, 2, 1, 3)
  1953. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  1954. offload_func_v(KQV_merged);
  1955. ggml_set_name(KQV_merged, "KQV_merged");
  1956. // cur = KQV_merged.contiguous().view(n_embd, N)
  1957. cur = ggml_cpy(ctx0,
  1958. KQV_merged,
  1959. ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  1960. offload_func_v(cur);
  1961. ggml_set_name(cur, "KQV_merged_contiguous");
  1962. // projection (no bias)
  1963. cur = ggml_mul_mat(ctx0,
  1964. model.layers[il].wo,
  1965. cur);
  1966. offload_func(cur);
  1967. ggml_set_name(cur, "result_wo");
  1968. }
  1969. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
  1970. offload_func(inpFF);
  1971. ggml_set_name(inpFF, "inpFF");
  1972. // feed-forward network
  1973. {
  1974. // norm
  1975. {
  1976. cur = ggml_rms_norm(ctx0, inpFF, norm_rms_eps);
  1977. offload_func(cur);
  1978. ggml_set_name(cur, "rms_norm_1");
  1979. // cur = cur*ffn_norm(broadcasted)
  1980. cur = ggml_mul(ctx0, cur, model.layers[il].ffn_norm);
  1981. offload_func(cur);
  1982. ggml_set_name(cur, "ffn_norm");
  1983. }
  1984. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  1985. model.layers[il].w3,
  1986. cur);
  1987. offload_func(tmp);
  1988. ggml_set_name(tmp, "result_w3");
  1989. cur = ggml_mul_mat(ctx0,
  1990. model.layers[il].w1,
  1991. cur);
  1992. offload_func(cur);
  1993. ggml_set_name(cur, "result_w1");
  1994. // SILU activation
  1995. cur = ggml_silu(ctx0, cur);
  1996. offload_func(cur);
  1997. ggml_set_name(cur, "silu");
  1998. cur = ggml_mul(ctx0, cur, tmp);
  1999. offload_func(cur);
  2000. ggml_set_name(cur, "silu_x_result_w3");
  2001. cur = ggml_mul_mat(ctx0,
  2002. model.layers[il].w2,
  2003. cur);
  2004. offload_func(cur);
  2005. ggml_set_name(cur, "result_w2");
  2006. }
  2007. cur = ggml_add(ctx0, cur, inpFF);
  2008. offload_func(cur);
  2009. ggml_set_name(cur, "inpFF_+_result_w2");
  2010. // input for next layer
  2011. inpL = cur;
  2012. }
  2013. cur = inpL;
  2014. // norm
  2015. {
  2016. cur = ggml_rms_norm(ctx0, cur, norm_rms_eps);
  2017. offload_func_nr(cur);
  2018. ggml_set_name(cur, "rms_norm_2");
  2019. // cur = cur*norm(broadcasted)
  2020. cur = ggml_mul(ctx0, cur, model.output_norm);
  2021. // offload_func_nr(cur); // TODO CPU + GPU mirrored backend
  2022. ggml_set_name(cur, "result_norm");
  2023. }
  2024. // lm_head
  2025. cur = ggml_mul_mat(ctx0, model.output, cur);
  2026. ggml_set_name(cur, "result_output");
  2027. ggml_build_forward_expand(gf, cur);
  2028. ggml_free(ctx0);
  2029. return gf;
  2030. }
  2031. static struct ggml_cgraph * llm_build_falcon(
  2032. llama_context & lctx,
  2033. const llama_token * tokens,
  2034. const float * embd,
  2035. int n_tokens,
  2036. int n_past) {
  2037. GGML_ASSERT((!tokens && embd) || (tokens && !embd)); // NOLINT
  2038. const int N = n_tokens;
  2039. const auto & model = lctx.model;
  2040. const auto & hparams = model.hparams;
  2041. const auto & kv_self = lctx.kv_self;
  2042. GGML_ASSERT(!!kv_self.ctx);
  2043. const int64_t n_embd = hparams.n_embd;
  2044. const int64_t n_layer = hparams.n_layer;
  2045. const int64_t n_ctx = hparams.n_ctx;
  2046. const int64_t n_head = hparams.n_head;
  2047. const int64_t n_head_kv = hparams.n_head_kv;
  2048. const int64_t n_embd_head = hparams.n_embd_head();
  2049. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  2050. GGML_ASSERT(n_embd_head == hparams.n_rot);
  2051. const float freq_base = hparams.rope_freq_base;
  2052. const float freq_scale = hparams.rope_freq_scale;
  2053. const float norm_eps = hparams.f_norm_eps;
  2054. const int n_gpu_layers = model.n_gpu_layers;
  2055. auto & buf_compute = lctx.buf_compute;
  2056. struct ggml_init_params params = {
  2057. /*.mem_size =*/ buf_compute.size,
  2058. /*.mem_buffer =*/ buf_compute.data,
  2059. /*.no_alloc =*/ false,
  2060. };
  2061. params.no_alloc = true;
  2062. struct ggml_context * ctx0 = ggml_init(params);
  2063. ggml_cgraph * gf = ggml_new_graph(ctx0);
  2064. struct ggml_tensor * cur;
  2065. struct ggml_tensor * inpL;
  2066. if (tokens) {
  2067. struct ggml_tensor * inp_tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  2068. ggml_allocr_alloc(lctx.alloc, inp_tokens);
  2069. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2070. memcpy(inp_tokens->data, tokens, N*ggml_element_size(inp_tokens));
  2071. }
  2072. ggml_set_name(inp_tokens, "inp_tokens");
  2073. inpL = ggml_get_rows(ctx0, model.tok_embeddings, inp_tokens);
  2074. } else {
  2075. #ifdef GGML_USE_MPI
  2076. GGML_ASSERT(false && "not implemented");
  2077. #endif
  2078. inpL = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N);
  2079. ggml_allocr_alloc(lctx.alloc, inpL);
  2080. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2081. memcpy(inpL->data, embd, N * n_embd * ggml_element_size(inpL));
  2082. }
  2083. }
  2084. const int i_gpu_start = n_layer - n_gpu_layers;
  2085. (void) i_gpu_start;
  2086. // offload functions set the tensor output backend to GPU
  2087. // tensors are GPU-accelerated if any input or the output has been offloaded
  2088. //
  2089. // with the low VRAM option VRAM scratch is disabled in llama_load_model_internal
  2090. // in that case ggml_cuda_assign_buffers has no effect
  2091. offload_func_t offload_func_nr = llama_nop; // nr = non-repeating
  2092. offload_func_t offload_func_kq = llama_nop;
  2093. offload_func_t offload_func_v = llama_nop;
  2094. #ifdef GGML_USE_CUBLAS
  2095. if (n_gpu_layers > n_layer) {
  2096. offload_func_nr = ggml_cuda_assign_buffers_no_alloc;
  2097. }
  2098. if (n_gpu_layers > n_layer + 1) {
  2099. offload_func_v = ggml_cuda_assign_buffers_no_alloc;
  2100. }
  2101. if (n_gpu_layers > n_layer + 2) {
  2102. offload_func_kq = ggml_cuda_assign_buffers_no_alloc;
  2103. }
  2104. #endif // GGML_USE_CUBLAS
  2105. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  2106. ggml_allocr_alloc(lctx.alloc, KQ_scale);
  2107. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2108. ggml_set_f32(KQ_scale, 1.0f/sqrtf(float(n_embd)/n_head));
  2109. }
  2110. ggml_set_name(KQ_scale, "1/sqrt(n_embd_head)");
  2111. for (int il = 0; il < n_layer; ++il) {
  2112. struct ggml_tensor * attn_norm;
  2113. offload_func_t offload_func = llama_nop;
  2114. #ifdef GGML_USE_CUBLAS
  2115. if (il >= i_gpu_start) {
  2116. offload_func = ggml_cuda_assign_buffers_no_alloc;
  2117. }
  2118. #endif // GGML_USE_CUBLAS
  2119. // self-attention
  2120. // TODO: refactor into common function (shared with LLaMA)
  2121. {
  2122. attn_norm = ggml_norm(ctx0, inpL, norm_eps);
  2123. offload_func(attn_norm);
  2124. attn_norm = ggml_add(ctx0,
  2125. ggml_mul(ctx0, attn_norm, model.layers[il].attn_norm),
  2126. model.layers[il].attn_norm_b);
  2127. offload_func(attn_norm->src[0]);
  2128. offload_func(attn_norm);
  2129. if (model.layers[il].attn_norm_2) { // Falcon-40B
  2130. cur = ggml_norm(ctx0, inpL, norm_eps);
  2131. offload_func(cur);
  2132. cur = ggml_add(ctx0,
  2133. ggml_mul(ctx0, cur, model.layers[il].attn_norm_2),
  2134. model.layers[il].attn_norm_2_b);
  2135. offload_func(cur->src[0]);
  2136. offload_func(cur);
  2137. } else { // Falcon 7B
  2138. cur = attn_norm;
  2139. }
  2140. // compute QKV
  2141. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  2142. offload_func_kq(cur);
  2143. // Note that the strides for Kcur, Vcur are set up so that the
  2144. // resulting views are misaligned with the tensor's storage
  2145. // (by applying the K/V offset we shift the tensor's original
  2146. // view to stick out behind the viewed QKV tensor's allocated
  2147. // memory, so to say). This is ok because no actual accesses
  2148. // happen to that out-of-range memory, but it can require some
  2149. // trickery when trying to accurately dump these views for
  2150. // debugging.
  2151. const size_t wsize = ggml_type_size(cur->type);
  2152. struct ggml_tensor * tmpq = ggml_view_3d(
  2153. ctx0, cur, n_embd_head, n_head, N,
  2154. wsize * n_embd_head,
  2155. wsize * n_embd_head * (n_head + 2 * n_head_kv),
  2156. 0);
  2157. offload_func_kq(tmpq);
  2158. struct ggml_tensor * tmpk = ggml_view_3d(
  2159. ctx0, cur, n_embd_head, n_head_kv, N,
  2160. wsize * n_embd_head,
  2161. wsize * n_embd_head * (n_head + 2 * n_head_kv),
  2162. wsize * n_embd_head * n_head);
  2163. offload_func_kq(tmpk);
  2164. struct ggml_tensor * tmpv = ggml_view_3d(
  2165. ctx0, cur, n_embd_head, n_head_kv, N,
  2166. wsize * n_embd_head,
  2167. wsize * n_embd_head * (n_head + 2 * n_head_kv),
  2168. wsize * n_embd_head * (n_head + n_head_kv));
  2169. offload_func_v(tmpv);
  2170. // using mode = 2 for neox mode
  2171. struct ggml_tensor * Qcur = ggml_rope_custom_inplace(ctx0, tmpq, n_past, n_embd_head, 2, 0, freq_base, freq_scale);
  2172. offload_func_kq(Qcur);
  2173. struct ggml_tensor * Kcur = ggml_rope_custom_inplace(ctx0, tmpk, n_past, n_embd_head, 2, 0, freq_base, freq_scale);
  2174. offload_func_kq(Kcur);
  2175. {
  2176. struct ggml_tensor * Vcur = ggml_transpose(ctx0, ggml_reshape_2d(ctx0, ggml_cont(ctx0, tmpv), n_embd_gqa, N));
  2177. offload_func_v(Vcur);
  2178. offload_func_v(Vcur->src[0]->src[0]);
  2179. ggml_set_name(Vcur, "Vcur");
  2180. struct ggml_tensor * k = ggml_view_1d(ctx0, kv_self.k, N*n_embd_gqa, (ggml_element_size(kv_self.k)*n_embd_gqa)*(il*n_ctx + n_past));
  2181. offload_func_kq(k);
  2182. ggml_set_name(k, "k");
  2183. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd_gqa,
  2184. ( n_ctx)*ggml_element_size(kv_self.v),
  2185. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd_gqa + n_past*ggml_element_size(kv_self.v));
  2186. offload_func_v(v);
  2187. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
  2188. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
  2189. }
  2190. struct ggml_tensor * Q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  2191. offload_func_kq(Q);
  2192. ggml_set_name(Q, "Q");
  2193. struct ggml_tensor * K =
  2194. ggml_view_3d(ctx0, kv_self.k,
  2195. n_embd_head, n_past + N, n_head_kv,
  2196. ggml_element_size(kv_self.k)*n_embd_gqa,
  2197. ggml_element_size(kv_self.k)*n_embd_head,
  2198. ggml_element_size(kv_self.k)*n_embd_gqa*n_ctx*il);
  2199. offload_func_kq(K);
  2200. ggml_set_name(K, "K");
  2201. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  2202. offload_func_kq(KQ);
  2203. ggml_set_name(KQ, "KQ");
  2204. struct ggml_tensor * KQ_scaled = ggml_scale_inplace(ctx0, KQ, KQ_scale);
  2205. offload_func_kq(KQ_scaled);
  2206. ggml_set_name(KQ_scaled, "KQ_scaled");
  2207. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf_inplace(ctx0, KQ_scaled, n_past);
  2208. offload_func_kq(KQ_masked);
  2209. ggml_set_name(KQ_masked, "KQ_masked");
  2210. struct ggml_tensor * KQ_soft_max = ggml_soft_max_inplace(ctx0, KQ_masked);
  2211. offload_func_v(KQ_soft_max);
  2212. ggml_set_name(KQ_soft_max, "KQ_soft_max");
  2213. struct ggml_tensor * V =
  2214. ggml_view_3d(ctx0, kv_self.v,
  2215. n_past + N, n_embd_head, n_head_kv,
  2216. ggml_element_size(kv_self.v)*n_ctx,
  2217. ggml_element_size(kv_self.v)*n_ctx*n_embd_head,
  2218. ggml_element_size(kv_self.v)*n_ctx*n_embd_gqa*il);
  2219. offload_func_v(V);
  2220. ggml_set_name(V, "V");
  2221. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  2222. offload_func_v(KQV);
  2223. ggml_set_name(KQV, "KQV");
  2224. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  2225. offload_func_v(KQV_merged);
  2226. ggml_set_name(KQV_merged, "KQV_merged");
  2227. cur = ggml_cpy(ctx0, KQV_merged, ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  2228. offload_func_v(cur);
  2229. ggml_set_name(cur, "KQV_merged_contiguous");
  2230. cur = ggml_mul_mat(ctx0, model.layers[il].wo, cur);
  2231. offload_func(cur);
  2232. ggml_set_name(cur, "result_wo");
  2233. }
  2234. struct ggml_tensor * attn_out = cur;
  2235. // feed forward
  2236. {
  2237. struct ggml_tensor * inpFF = attn_norm;
  2238. cur = ggml_mul_mat(ctx0, model.layers[il].w3, inpFF);
  2239. offload_func(cur);
  2240. cur = ggml_gelu(ctx0, cur);
  2241. offload_func(cur);
  2242. cur = ggml_mul_mat(ctx0, model.layers[il].w2, cur);
  2243. offload_func(cur);
  2244. }
  2245. cur = ggml_add(ctx0, cur, attn_out);
  2246. offload_func(cur);
  2247. cur = ggml_add(ctx0, cur, inpL);
  2248. offload_func(cur);
  2249. // input for next layer
  2250. inpL = cur;
  2251. }
  2252. cur = inpL;
  2253. // norm
  2254. {
  2255. cur = ggml_norm(ctx0, cur, norm_eps);
  2256. offload_func_nr(cur);
  2257. cur = ggml_add(ctx0,
  2258. ggml_mul(ctx0, cur, model.output_norm),
  2259. model.output_norm_b);
  2260. ggml_set_name(cur, "result_norm");
  2261. }
  2262. cur = ggml_mul_mat(ctx0, model.output, cur);
  2263. ggml_set_name(cur, "result_output");
  2264. ggml_build_forward_expand(gf, cur);
  2265. ggml_free(ctx0);
  2266. return gf;
  2267. }
  2268. static struct ggml_cgraph * llama_build_graph(
  2269. llama_context & lctx,
  2270. const llama_token * tokens,
  2271. const float * embd,
  2272. int n_tokens,
  2273. int n_past) {
  2274. const auto & model = lctx.model;
  2275. struct ggml_cgraph * result = NULL;
  2276. switch (model.arch) {
  2277. case LLM_ARCH_LLAMA:
  2278. {
  2279. result = llm_build_llama(lctx, tokens, embd, n_tokens, n_past);
  2280. } break;
  2281. case LLM_ARCH_FALCON:
  2282. {
  2283. result = llm_build_falcon(lctx, tokens, embd, n_tokens, n_past);
  2284. } break;
  2285. default:
  2286. GGML_ASSERT(false);
  2287. };
  2288. return result;
  2289. }
  2290. // evaluate the transformer
  2291. //
  2292. // - lctx: llama context
  2293. // - tokens: new batch of tokens to process
  2294. // - embd embeddings input
  2295. // - n_tokens number of tokens
  2296. // - n_past: the context size so far
  2297. // - n_threads: number of threads to use
  2298. //
  2299. static bool llama_eval_internal(
  2300. llama_context & lctx,
  2301. const llama_token * tokens,
  2302. const float * embd,
  2303. int n_tokens,
  2304. int n_past,
  2305. int n_threads,
  2306. const char * cgraph_fname) {
  2307. GGML_ASSERT((!tokens && embd) || (tokens && !embd)); // NOLINT
  2308. GGML_ASSERT(n_tokens > 0);
  2309. GGML_ASSERT(n_past >= 0);
  2310. GGML_ASSERT(n_threads > 0);
  2311. // TODO: keep the values of n_batch and n_ctx
  2312. // GGML_ASSERT(n_tokens <= n_batch);
  2313. // GGML_ASSERT(n_past + n_tokens <= n_ctx);
  2314. const int64_t t_start_us = ggml_time_us();
  2315. #ifdef GGML_USE_MPI
  2316. ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  2317. #endif
  2318. const int N = n_tokens;
  2319. const auto & model = lctx.model;
  2320. const auto & hparams = model.hparams;
  2321. const auto & kv_self = lctx.kv_self;
  2322. GGML_ASSERT(!!kv_self.ctx);
  2323. const int64_t n_embd = hparams.n_embd;
  2324. const int64_t n_vocab = hparams.n_vocab;
  2325. ggml_allocr_reset(lctx.alloc);
  2326. ggml_cgraph * gf = llama_build_graph(lctx, tokens, embd, n_tokens, n_past);
  2327. ggml_allocr_alloc_graph(lctx.alloc, gf);
  2328. #ifdef GGML_USE_CUBLAS
  2329. for (int i = 0; i < gf->n_leafs; i++) {
  2330. ggml_tensor * node = gf->leafs[i];
  2331. if (node->backend == GGML_BACKEND_GPU && node->extra == NULL) {
  2332. ggml_cuda_assign_scratch_offset(node, (char*)node->data - (char *) lctx.buf_alloc.data);
  2333. }
  2334. }
  2335. for (int i = 0; i < gf->n_nodes; i++) {
  2336. ggml_tensor * node = gf->nodes[i];
  2337. if (node->backend == GGML_BACKEND_GPU && node->extra == NULL) {
  2338. ggml_cuda_assign_scratch_offset(node, (char*)node->data - (char *) lctx.buf_alloc.data);
  2339. }
  2340. }
  2341. #endif
  2342. // 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);
  2343. // for big prompts, if BLAS is enabled, it is better to use only one thread
  2344. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  2345. n_threads = N >= 32 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas() ? 1 : n_threads;
  2346. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  2347. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 2];
  2348. GGML_ASSERT(strcmp(res->name, "result_output") == 0);
  2349. GGML_ASSERT(strcmp(embeddings->name, "result_norm") == 0);
  2350. #if GGML_USE_MPI
  2351. const int64_t n_layer = hparams.n_layer;
  2352. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  2353. #endif
  2354. #ifdef GGML_USE_METAL
  2355. if (lctx.ctx_metal) {
  2356. ggml_metal_set_n_cb (lctx.ctx_metal, n_threads);
  2357. ggml_metal_graph_compute(lctx.ctx_metal, gf);
  2358. ggml_metal_get_tensor (lctx.ctx_metal, res);
  2359. if (!lctx.embedding.empty()) {
  2360. ggml_metal_get_tensor(lctx.ctx_metal, embeddings);
  2361. }
  2362. } else {
  2363. ggml_graph_compute_helper(lctx.work_buffer, gf, n_threads);
  2364. }
  2365. #else
  2366. ggml_graph_compute_helper(lctx.work_buffer, gf, n_threads);
  2367. #endif
  2368. #if GGML_USE_MPI
  2369. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  2370. #endif
  2371. // update kv token count
  2372. lctx.kv_self.n = n_past + N;
  2373. if (cgraph_fname) {
  2374. ggml_graph_export(gf, cgraph_fname);
  2375. }
  2376. #ifdef GGML_PERF
  2377. // print timing information per ggml operation (for debugging purposes)
  2378. // requires GGML_PERF to be defined
  2379. ggml_graph_print(gf);
  2380. #endif
  2381. // plot the computation graph in dot format (for debugging purposes)
  2382. //if (n_past%100 == 0) {
  2383. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  2384. //}
  2385. // extract logits
  2386. {
  2387. auto & logits_out = lctx.logits;
  2388. if (lctx.logits_all) {
  2389. logits_out.resize(n_vocab * N);
  2390. memcpy(logits_out.data(), (float *) ggml_get_data(res), sizeof(float)*n_vocab*N);
  2391. } else {
  2392. // return result for just the last token
  2393. logits_out.resize(n_vocab);
  2394. memcpy(logits_out.data(), (float *) ggml_get_data(res) + (n_vocab*(N-1)), sizeof(float)*n_vocab);
  2395. }
  2396. }
  2397. // extract embeddings
  2398. if (!lctx.embedding.empty()) {
  2399. auto & embedding_out = lctx.embedding;
  2400. embedding_out.resize(n_embd);
  2401. memcpy(embedding_out.data(), (float *) ggml_get_data(embeddings) + (n_embd*(N - 1)), sizeof(float)*n_embd);
  2402. }
  2403. // measure the performance only for the single-token evals
  2404. if (N == 1) {
  2405. lctx.t_eval_us += ggml_time_us() - t_start_us;
  2406. lctx.n_eval++;
  2407. }
  2408. else if (N > 1) {
  2409. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  2410. lctx.n_p_eval += N;
  2411. }
  2412. return true;
  2413. }
  2414. //
  2415. // tokenizer
  2416. //
  2417. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  2418. return vocab.type;
  2419. }
  2420. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  2421. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  2422. }
  2423. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  2424. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  2425. }
  2426. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  2427. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  2428. }
  2429. static bool llama_is_user_defined_token(const llama_vocab & vocab, llama_token id) {
  2430. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  2431. }
  2432. static bool llama_is_unused_token(const llama_vocab & vocab, llama_token id) {
  2433. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNUSED;
  2434. }
  2435. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  2436. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  2437. }
  2438. static bool llama_is_bos_token(const llama_vocab & vocab, llama_token id) {
  2439. GGML_ASSERT(llama_is_control_token(vocab, id));
  2440. return id == vocab.special_bos_id;
  2441. }
  2442. static bool llama_is_eos_token(const llama_vocab & vocab, llama_token id ) {
  2443. GGML_ASSERT(llama_is_control_token(vocab, id));
  2444. return id == vocab.special_eos_id;
  2445. }
  2446. static bool llama_is_pad_token(const llama_vocab & vocab, llama_token id ) {
  2447. GGML_ASSERT(id < 0 || llama_is_control_token(vocab, id));
  2448. return id == vocab.special_pad_id;
  2449. }
  2450. static uint8_t llama_token_to_byte(const llama_vocab & vocab, llama_token id) {
  2451. GGML_ASSERT(llama_is_byte_token(vocab, id));
  2452. const auto& token_data = vocab.id_to_token.at(id);
  2453. auto buf = token_data.text.substr(3, 2);
  2454. return strtol(buf.c_str(), NULL, 16);
  2455. }
  2456. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  2457. char buf[7];
  2458. int result = snprintf(buf, sizeof(buf), "<0x%02X>", ch);
  2459. GGML_ASSERT(0 <= result && result < 7);
  2460. return vocab.token_to_id.at(buf);
  2461. }
  2462. static std::string llama_escape_whitespace(const std::string& text) {
  2463. std::string result = "\xe2\x96\x81";
  2464. for (size_t offs = 0; offs < text.length(); ++offs) {
  2465. if (text[offs] == ' ') {
  2466. result += "\xe2\x96\x81";
  2467. } else {
  2468. result += text[offs];
  2469. }
  2470. }
  2471. return result;
  2472. }
  2473. static void llama_unescape_whitespace(std::string & word) {
  2474. replace_all(word, "\xe2\x96\x81", " ");
  2475. }
  2476. struct llm_symbol {
  2477. using index = int;
  2478. index prev;
  2479. index next;
  2480. const char * text;
  2481. size_t n;
  2482. };
  2483. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  2484. // SPM tokenizer
  2485. // original implementation:
  2486. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  2487. struct llm_bigram_spm {
  2488. struct comparator {
  2489. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  2490. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  2491. }
  2492. };
  2493. using queue_storage = std::vector<llm_bigram_spm>;
  2494. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  2495. llm_symbol::index left;
  2496. llm_symbol::index right;
  2497. float score;
  2498. size_t size;
  2499. };
  2500. struct llm_tokenizer_spm {
  2501. llm_tokenizer_spm(const llama_vocab & vocab): vocab(vocab) {}
  2502. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  2503. // split string into utf8 chars
  2504. int index = 0;
  2505. size_t offs = 0;
  2506. while (offs < text.size()) {
  2507. llm_symbol sym;
  2508. size_t len = utf8_len(text[offs]);
  2509. GGML_ASSERT(offs + len <= text.size());
  2510. sym.text = text.c_str() + offs;
  2511. sym.n = len;
  2512. offs += len;
  2513. sym.prev = index - 1;
  2514. sym.next = offs == text.size() ? -1 : index + 1;
  2515. index++;
  2516. symbols.emplace_back(sym);
  2517. }
  2518. // seed the work queue with all possible 2-character tokens.
  2519. for (size_t i = 1; i < symbols.size(); ++i) {
  2520. try_add_bigram(i - 1, i);
  2521. }
  2522. // keep substituting the highest frequency pairs for as long as we can.
  2523. while (!work_queue.empty()) {
  2524. auto bigram = work_queue.top();
  2525. work_queue.pop();
  2526. auto & left_sym = symbols[bigram.left];
  2527. auto & right_sym = symbols[bigram.right];
  2528. // if one of the symbols already got merged, skip it.
  2529. if (left_sym.n == 0 || right_sym.n == 0 ||
  2530. left_sym.n + right_sym.n != bigram.size) {
  2531. continue;
  2532. }
  2533. // merge the right sym into the left one
  2534. left_sym.n += right_sym.n;
  2535. right_sym.n = 0;
  2536. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  2537. // remove the right sym from the chain
  2538. left_sym.next = right_sym.next;
  2539. if (right_sym.next >= 0) {
  2540. symbols[right_sym.next].prev = bigram.left;
  2541. }
  2542. // find more substitutions
  2543. try_add_bigram(left_sym.prev, bigram.left);
  2544. try_add_bigram(bigram.left, left_sym.next);
  2545. }
  2546. for (int i = 0; i != -1; i = symbols[i].next) {
  2547. auto & symbol = symbols[i];
  2548. resegment(symbol, output);
  2549. }
  2550. }
  2551. private:
  2552. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  2553. auto text = std::string(symbol.text, symbol.n);
  2554. auto token = vocab.token_to_id.find(text);
  2555. // Do we need to support is_unused?
  2556. if (token != vocab.token_to_id.end()) {
  2557. output.push_back((*token).second);
  2558. return;
  2559. }
  2560. const auto p = rev_merge.find(text);
  2561. if (p == rev_merge.end()) {
  2562. // output any symbols that did not form tokens as bytes.
  2563. for (int j = 0; j < (int)symbol.n; ++j) {
  2564. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  2565. output.push_back(token_id);
  2566. }
  2567. return;
  2568. }
  2569. resegment(symbols[p->second.first], output);
  2570. resegment(symbols[p->second.second], output);
  2571. }
  2572. void try_add_bigram(int left, int right) {
  2573. if (left == -1 || right == -1) {
  2574. return;
  2575. }
  2576. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  2577. auto token = vocab.token_to_id.find(text);
  2578. if (token == vocab.token_to_id.end()) {
  2579. return;
  2580. }
  2581. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  2582. return;
  2583. }
  2584. const auto & tok_data = vocab.id_to_token[(*token).second];
  2585. llm_bigram_spm bigram;
  2586. bigram.left = left;
  2587. bigram.right = right;
  2588. bigram.score = tok_data.score;
  2589. bigram.size = text.size();
  2590. work_queue.push(bigram);
  2591. // Do we need to support is_unused?
  2592. rev_merge[text] = std::make_pair(left, right);
  2593. }
  2594. const llama_vocab & vocab;
  2595. std::vector<llm_symbol> symbols;
  2596. llm_bigram_spm::queue work_queue;
  2597. std::map<std::string, std::pair<int, int>> rev_merge;
  2598. };
  2599. // BPE tokenizer
  2600. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  2601. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  2602. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  2603. struct llm_bigram_bpe {
  2604. struct comparator {
  2605. bool operator()(llm_bigram_bpe & l, llm_bigram_bpe & r) {
  2606. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  2607. }
  2608. };
  2609. using queue_storage = std::vector<llm_bigram_bpe>;
  2610. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  2611. llm_symbol::index left;
  2612. llm_symbol::index right;
  2613. std::string text;
  2614. int rank;
  2615. size_t size;
  2616. };
  2617. struct llm_tokenizer_bpe {
  2618. llm_tokenizer_bpe(const llama_vocab & vocab, bool g2ws): vocab(vocab) { flag_g2ws = g2ws; }
  2619. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  2620. int final_prev_index = -1;
  2621. auto word_collection = bpe_gpt2_preprocess(text);
  2622. symbols_final.clear();
  2623. for (auto & word : word_collection) {
  2624. work_queue = llm_bigram_bpe::queue();
  2625. symbols.clear();
  2626. int index = 0;
  2627. size_t offset = 0;
  2628. while (offset < word.size()) {
  2629. llm_symbol sym;
  2630. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  2631. sym.text = word.c_str() + offset;
  2632. sym.n = 1;
  2633. sym.n = char_len;
  2634. offset += sym.n;
  2635. sym.prev = index - 1;
  2636. sym.next = offset == word.size() ? -1 : index + 1;
  2637. index++;
  2638. symbols.emplace_back(sym);
  2639. }
  2640. for (size_t i = 1; i < symbols.size(); ++i) {
  2641. add_new_bigram(i - 1, i);
  2642. }
  2643. // build token(s)
  2644. while (!work_queue.empty()) {
  2645. auto bigram = work_queue.top();
  2646. work_queue.pop();
  2647. auto & left_symbol = symbols[bigram.left];
  2648. auto & right_symbol = symbols[bigram.right];
  2649. if (left_symbol.n == 0 || right_symbol.n == 0) {
  2650. continue;
  2651. }
  2652. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  2653. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  2654. if (left_token + right_token != bigram.text) {
  2655. continue; // Skip this bigram if it's outdated
  2656. }
  2657. // merge the right sym into the left one
  2658. left_symbol.n += right_symbol.n;
  2659. right_symbol.n = 0;
  2660. // remove the right sym from the chain
  2661. left_symbol.next = right_symbol.next;
  2662. if (right_symbol.next >= 0) {
  2663. symbols[right_symbol.next].prev = bigram.left;
  2664. }
  2665. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  2666. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  2667. }
  2668. // add the fnished tokens to the final list keeping correct order for next and prev
  2669. for (auto & sym : symbols) {
  2670. if (sym.n > 0) {
  2671. sym.prev = final_prev_index;
  2672. sym.next = -1;
  2673. if (final_prev_index != -1) {
  2674. symbols_final[final_prev_index].next = symbols_final.size();
  2675. }
  2676. symbols_final.emplace_back(sym);
  2677. final_prev_index = symbols_final.size() - 1;
  2678. }
  2679. }
  2680. }
  2681. symbols = symbols_final;
  2682. if (!symbols.empty()) {
  2683. for (int i = 0; i != -1; i = symbols[i].next) {
  2684. auto & symbol = symbols[i];
  2685. if (symbol.n == 0) {
  2686. continue;
  2687. }
  2688. const std::string str = std::string(symbol.text, symbol.n);
  2689. const auto token = vocab.token_to_id.find(str);
  2690. if (token == vocab.token_to_id.end()) {
  2691. for (auto j = str.begin(); j != str.end(); ++j) {
  2692. std::string byte_str(1, *j);
  2693. auto token_multibyte = vocab.token_to_id.find(byte_str);
  2694. if (token_multibyte == vocab.token_to_id.end()) {
  2695. fprintf(stderr,"ERROR: byte not found in vocab: '%s'\n", byte_str.c_str());
  2696. }
  2697. output.push_back((*token_multibyte).second);
  2698. }
  2699. } else {
  2700. output.push_back((*token).second);
  2701. }
  2702. }
  2703. }
  2704. }
  2705. private:
  2706. void add_new_bigram(int left, int right) {
  2707. if (left == -1 || right == -1) {
  2708. return;
  2709. }
  2710. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  2711. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  2712. int rank_found = -1;
  2713. rank_found = vocab.find_bpe_rank(left_token, right_token);
  2714. if (rank_found < 0) {
  2715. return;
  2716. }
  2717. llm_bigram_bpe bigram;
  2718. bigram.left = left;
  2719. bigram.right = right;
  2720. bigram.text = left_token + right_token;
  2721. bigram.size = left_token.size() + right_token.size();
  2722. bigram.rank = rank_found;
  2723. work_queue.push(bigram);
  2724. }
  2725. // probably not 100% correct
  2726. // TODO: this is quite slow - how to make it more efficient?
  2727. static std::vector<std::string> bpe_gpt2_preprocess(std::string text) {
  2728. std::vector<std::string> words;
  2729. // ref: https://github.com/openai/gpt-2/blob/a74da5d99abaaba920de8131d64da2862a8f213b/src/encoder.py#L53
  2730. const std::string pattern = R"('s|'t|'re|'ve|'m|'ll|'d| ?[[:alpha:]]+| ?[[:digit:]]+| ?[^\s[:alpha:][:digit:]]+|\s+(?!\S)|\s+)";
  2731. const std::regex re(pattern);
  2732. std::smatch m;
  2733. while (std::regex_search(text, m, re)) {
  2734. for (auto x : m) {
  2735. words.push_back(x);
  2736. }
  2737. text = m.suffix();
  2738. }
  2739. return words;
  2740. }
  2741. bool flag_g2ws = false;
  2742. const llama_vocab & vocab;
  2743. std::vector<llm_symbol> symbols;
  2744. std::vector<llm_symbol> symbols_final;
  2745. llm_bigram_bpe::queue work_queue;
  2746. };
  2747. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, const std::string & raw_text, bool bos, bool escape) {
  2748. std::vector<llama_vocab::id> output;
  2749. if (raw_text.empty()) {
  2750. return output;
  2751. }
  2752. switch (vocab.type) {
  2753. case LLAMA_VOCAB_TYPE_SPM:
  2754. {
  2755. llm_tokenizer_spm tokenizer(vocab);
  2756. if (bos) {
  2757. output.push_back(vocab.special_bos_id);
  2758. }
  2759. std::string text;
  2760. if (escape) {
  2761. text = llama_escape_whitespace(raw_text);
  2762. } else {
  2763. text = raw_text;
  2764. }
  2765. tokenizer.tokenize(text, output);
  2766. } break;
  2767. case LLAMA_VOCAB_TYPE_BPE:
  2768. {
  2769. llm_tokenizer_bpe tokenizer(vocab, escape);
  2770. if (bos && vocab.special_bos_id != -1) {
  2771. output.push_back(vocab.special_bos_id);
  2772. }
  2773. tokenizer.tokenize(raw_text, output);
  2774. } break;
  2775. };
  2776. return output;
  2777. }
  2778. //
  2779. // grammar - internal
  2780. //
  2781. struct llama_partial_utf8 {
  2782. uint32_t value; // bit value so far (unshifted)
  2783. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  2784. };
  2785. struct llama_grammar {
  2786. const std::vector<std::vector<llama_grammar_element>> rules;
  2787. std::vector<std::vector<const llama_grammar_element *>> stacks;
  2788. // buffer for partially generated UTF-8 sequence from accepted tokens
  2789. llama_partial_utf8 partial_utf8;
  2790. };
  2791. struct llama_grammar_candidate {
  2792. size_t index;
  2793. const uint32_t * code_points;
  2794. llama_partial_utf8 partial_utf8;
  2795. };
  2796. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  2797. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  2798. std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  2799. const char * src,
  2800. llama_partial_utf8 partial_start) {
  2801. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  2802. const char * pos = src;
  2803. std::vector<uint32_t> code_points;
  2804. uint32_t value = partial_start.value;
  2805. int n_remain = partial_start.n_remain;
  2806. // continue previous decode, if applicable
  2807. while (*pos != 0 && n_remain > 0) {
  2808. uint8_t next_byte = static_cast<uint8_t>(*pos);
  2809. if ((next_byte >> 6) != 2) {
  2810. // invalid sequence, abort
  2811. code_points.push_back(0);
  2812. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  2813. }
  2814. value = (value << 6) + (next_byte & 0x3F);
  2815. ++pos;
  2816. --n_remain;
  2817. }
  2818. if (partial_start.n_remain > 0 && n_remain == 0) {
  2819. code_points.push_back(value);
  2820. }
  2821. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  2822. while (*pos != 0) {
  2823. uint8_t first_byte = static_cast<uint8_t>(*pos);
  2824. uint8_t highbits = first_byte >> 4;
  2825. n_remain = lookup[highbits] - 1;
  2826. if (n_remain < 0) {
  2827. // invalid sequence, abort
  2828. code_points.clear();
  2829. code_points.push_back(0);
  2830. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  2831. }
  2832. uint8_t mask = (1 << (7 - n_remain)) - 1;
  2833. value = first_byte & mask;
  2834. ++pos;
  2835. while (*pos != 0 && n_remain > 0) {
  2836. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  2837. ++pos;
  2838. --n_remain;
  2839. }
  2840. if (n_remain == 0) {
  2841. code_points.push_back(value);
  2842. }
  2843. }
  2844. code_points.push_back(0);
  2845. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  2846. }
  2847. // returns true iff pos points to the end of one of the definitions of a rule
  2848. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  2849. switch (pos->type) {
  2850. case LLAMA_GRETYPE_END: return true; // NOLINT
  2851. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  2852. default: return false;
  2853. }
  2854. }
  2855. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  2856. // asserts that pos is pointing to a char range element
  2857. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  2858. const llama_grammar_element * pos,
  2859. const uint32_t chr) {
  2860. bool found = false;
  2861. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  2862. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  2863. do {
  2864. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  2865. // inclusive range, e.g. [a-z]
  2866. found = found || (pos->value <= chr && chr <= pos[1].value);
  2867. pos += 2;
  2868. } else {
  2869. // exact char match, e.g. [a] or "a"
  2870. found = found || pos->value == chr;
  2871. pos += 1;
  2872. }
  2873. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  2874. return std::make_pair(found == is_positive_char, pos);
  2875. }
  2876. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  2877. // range at pos (regular or inverse range)
  2878. // asserts that pos is pointing to a char range element
  2879. static bool llama_grammar_match_partial_char(
  2880. const llama_grammar_element * pos,
  2881. const llama_partial_utf8 partial_utf8) {
  2882. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  2883. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  2884. uint32_t partial_value = partial_utf8.value;
  2885. int n_remain = partial_utf8.n_remain;
  2886. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  2887. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  2888. return false;
  2889. }
  2890. // range of possible code points this partial UTF-8 sequence could complete to
  2891. uint32_t low = partial_value << (n_remain * 6);
  2892. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  2893. if (low == 0) {
  2894. if (n_remain == 2) {
  2895. low = 1 << 11;
  2896. } else if (n_remain == 3) {
  2897. low = 1 << 16;
  2898. }
  2899. }
  2900. do {
  2901. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  2902. // inclusive range, e.g. [a-z]
  2903. if (pos->value <= high && low <= pos[1].value) {
  2904. return is_positive_char;
  2905. }
  2906. pos += 2;
  2907. } else {
  2908. // exact char match, e.g. [a] or "a"
  2909. if (low <= pos->value && pos->value <= high) {
  2910. return is_positive_char;
  2911. }
  2912. pos += 1;
  2913. }
  2914. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  2915. return !is_positive_char;
  2916. }
  2917. // transforms a grammar pushdown stack into N possible stacks, all ending
  2918. // at a character range (terminal element)
  2919. static void llama_grammar_advance_stack(
  2920. const std::vector<std::vector<llama_grammar_element>> & rules,
  2921. const std::vector<const llama_grammar_element *> & stack,
  2922. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  2923. if (stack.empty()) {
  2924. new_stacks.push_back(stack);
  2925. return;
  2926. }
  2927. const llama_grammar_element * pos = stack.back();
  2928. switch (pos->type) {
  2929. case LLAMA_GRETYPE_RULE_REF: {
  2930. const size_t rule_id = static_cast<size_t>(pos->value);
  2931. const llama_grammar_element * subpos = rules[rule_id].data();
  2932. do {
  2933. // init new stack without the top (pos)
  2934. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  2935. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  2936. // if this rule ref is followed by another element, add that to stack
  2937. new_stack.push_back(pos + 1);
  2938. }
  2939. if (!llama_grammar_is_end_of_sequence(subpos)) {
  2940. // if alternate is nonempty, add to stack
  2941. new_stack.push_back(subpos);
  2942. }
  2943. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  2944. while (!llama_grammar_is_end_of_sequence(subpos)) {
  2945. // scan to end of alternate def
  2946. subpos++;
  2947. }
  2948. if (subpos->type == LLAMA_GRETYPE_ALT) {
  2949. // there's another alternate def of this rule to process
  2950. subpos++;
  2951. } else {
  2952. break;
  2953. }
  2954. } while (true);
  2955. break;
  2956. }
  2957. case LLAMA_GRETYPE_CHAR:
  2958. case LLAMA_GRETYPE_CHAR_NOT:
  2959. new_stacks.push_back(stack);
  2960. break;
  2961. default:
  2962. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  2963. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  2964. // those
  2965. GGML_ASSERT(false);
  2966. }
  2967. }
  2968. // takes a set of possible pushdown stacks on a grammar, which are required to
  2969. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  2970. // produces the N possible stacks if the given char is accepted at those
  2971. // positions
  2972. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  2973. const std::vector<std::vector<llama_grammar_element>> & rules,
  2974. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  2975. const uint32_t chr) {
  2976. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  2977. for (const auto & stack : stacks) {
  2978. if (stack.empty()) {
  2979. continue;
  2980. }
  2981. auto match = llama_grammar_match_char(stack.back(), chr);
  2982. if (match.first) {
  2983. const llama_grammar_element * pos = match.second;
  2984. // update top of stack to next element, if any
  2985. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  2986. if (!llama_grammar_is_end_of_sequence(pos)) {
  2987. new_stack.push_back(pos);
  2988. }
  2989. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  2990. }
  2991. }
  2992. return new_stacks;
  2993. }
  2994. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  2995. const std::vector<std::vector<llama_grammar_element>> & rules,
  2996. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  2997. const std::vector<llama_grammar_candidate> & candidates);
  2998. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  2999. const std::vector<std::vector<llama_grammar_element>> & rules,
  3000. const std::vector<const llama_grammar_element *> & stack,
  3001. const std::vector<llama_grammar_candidate> & candidates) {
  3002. std::vector<llama_grammar_candidate> rejects;
  3003. if (stack.empty()) {
  3004. for (auto tok : candidates) {
  3005. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  3006. rejects.push_back(tok);
  3007. }
  3008. }
  3009. return rejects;
  3010. }
  3011. const llama_grammar_element * stack_pos = stack.back();
  3012. std::vector<llama_grammar_candidate> next_candidates;
  3013. for (auto tok : candidates) {
  3014. if (*tok.code_points == 0) {
  3015. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  3016. // that cannot satisfy this position in grammar
  3017. if (tok.partial_utf8.n_remain != 0 &&
  3018. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  3019. rejects.push_back(tok);
  3020. }
  3021. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  3022. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  3023. } else {
  3024. rejects.push_back(tok);
  3025. }
  3026. }
  3027. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  3028. // update top of stack to next element, if any
  3029. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  3030. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  3031. stack_after.push_back(stack_pos_after);
  3032. }
  3033. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  3034. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  3035. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  3036. for (auto tok : next_rejects) {
  3037. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  3038. }
  3039. return rejects;
  3040. }
  3041. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  3042. const std::vector<std::vector<llama_grammar_element>> & rules,
  3043. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  3044. const std::vector<llama_grammar_candidate> & candidates) {
  3045. GGML_ASSERT(!stacks.empty()); // REVIEW
  3046. if (candidates.empty()) {
  3047. return std::vector<llama_grammar_candidate>();
  3048. }
  3049. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  3050. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  3051. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  3052. }
  3053. return rejects;
  3054. }
  3055. //
  3056. // grammar - external
  3057. //
  3058. struct llama_grammar * llama_grammar_init(
  3059. const llama_grammar_element ** rules,
  3060. size_t n_rules,
  3061. size_t start_rule_index) {
  3062. const llama_grammar_element * pos;
  3063. // copy rule definitions into vectors
  3064. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  3065. for (size_t i = 0; i < n_rules; i++) {
  3066. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  3067. vec_rules[i].push_back(*pos);
  3068. }
  3069. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  3070. }
  3071. // loop over alternates of start rule to build initial stacks
  3072. std::vector<std::vector<const llama_grammar_element *>> stacks;
  3073. pos = rules[start_rule_index];
  3074. do {
  3075. std::vector<const llama_grammar_element *> stack;
  3076. if (!llama_grammar_is_end_of_sequence(pos)) {
  3077. // if alternate is nonempty, add to stack
  3078. stack.push_back(pos);
  3079. }
  3080. llama_grammar_advance_stack(vec_rules, stack, stacks);
  3081. while (!llama_grammar_is_end_of_sequence(pos)) {
  3082. // scan to end of alternate def
  3083. pos++;
  3084. }
  3085. if (pos->type == LLAMA_GRETYPE_ALT) {
  3086. // there's another alternate def of this rule to process
  3087. pos++;
  3088. } else {
  3089. break;
  3090. }
  3091. } while (true);
  3092. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  3093. }
  3094. void llama_grammar_free(struct llama_grammar * grammar) {
  3095. delete grammar;
  3096. }
  3097. //
  3098. // sampling
  3099. //
  3100. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  3101. GGML_ASSERT(candidates->size > 0);
  3102. const int64_t t_start_sample_us = ggml_time_us();
  3103. // Sort the logits in descending order
  3104. if (!candidates->sorted) {
  3105. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  3106. return a.logit > b.logit;
  3107. });
  3108. candidates->sorted = true;
  3109. }
  3110. float max_l = candidates->data[0].logit;
  3111. float cum_sum = 0.0f;
  3112. for (size_t i = 0; i < candidates->size; ++i) {
  3113. float p = expf(candidates->data[i].logit - max_l);
  3114. candidates->data[i].p = p;
  3115. cum_sum += p;
  3116. }
  3117. for (size_t i = 0; i < candidates->size; ++i) {
  3118. candidates->data[i].p /= cum_sum;
  3119. }
  3120. if (ctx) {
  3121. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3122. }
  3123. }
  3124. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int k, size_t min_keep) {
  3125. const int64_t t_start_sample_us = ggml_time_us();
  3126. k = std::max(k, (int) min_keep);
  3127. k = std::min(k, (int) candidates->size);
  3128. // Sort scores in descending order
  3129. if (!candidates->sorted) {
  3130. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  3131. return a.logit > b.logit;
  3132. };
  3133. if (k == (int) candidates->size) {
  3134. std::sort(candidates->data, candidates->data + candidates->size, comp);
  3135. } else {
  3136. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  3137. }
  3138. candidates->sorted = true;
  3139. }
  3140. candidates->size = k;
  3141. if (ctx) {
  3142. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3143. }
  3144. }
  3145. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  3146. if (p >= 1.0f) {
  3147. return;
  3148. }
  3149. llama_sample_softmax(ctx, candidates);
  3150. const int64_t t_start_sample_us = ggml_time_us();
  3151. // Compute the cumulative probabilities
  3152. float cum_sum = 0.0f;
  3153. size_t last_idx = candidates->size;
  3154. for (size_t i = 0; i < candidates->size; ++i) {
  3155. cum_sum += candidates->data[i].p;
  3156. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  3157. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  3158. if (cum_sum >= p && i + 1 >= min_keep) {
  3159. last_idx = i + 1;
  3160. break;
  3161. }
  3162. }
  3163. // Resize the output vector to keep only the top-p tokens
  3164. candidates->size = last_idx;
  3165. if (ctx) {
  3166. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3167. }
  3168. }
  3169. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  3170. if (z >= 1.0f || candidates->size <= 2) {
  3171. return;
  3172. }
  3173. llama_sample_softmax(nullptr, candidates);
  3174. const int64_t t_start_sample_us = ggml_time_us();
  3175. // Compute the first and second derivatives
  3176. std::vector<float> first_derivatives(candidates->size - 1);
  3177. std::vector<float> second_derivatives(candidates->size - 2);
  3178. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  3179. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  3180. }
  3181. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  3182. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  3183. }
  3184. // Calculate absolute value of second derivatives
  3185. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  3186. second_derivatives[i] = abs(second_derivatives[i]);
  3187. }
  3188. // Normalize the second derivatives
  3189. {
  3190. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  3191. if (second_derivatives_sum > 1e-6f) {
  3192. for (float & value : second_derivatives) {
  3193. value /= second_derivatives_sum;
  3194. }
  3195. } else {
  3196. for (float & value : second_derivatives) {
  3197. value = 1.0f / second_derivatives.size();
  3198. }
  3199. }
  3200. }
  3201. float cum_sum = 0.0f;
  3202. size_t last_idx = candidates->size;
  3203. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  3204. cum_sum += second_derivatives[i];
  3205. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  3206. if (cum_sum > z && i >= min_keep) {
  3207. last_idx = i;
  3208. break;
  3209. }
  3210. }
  3211. // Resize the output vector to keep only the tokens above the tail location
  3212. candidates->size = last_idx;
  3213. if (ctx) {
  3214. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3215. }
  3216. }
  3217. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  3218. // Reference implementation:
  3219. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  3220. if (p >= 1.0f) {
  3221. return;
  3222. }
  3223. // Compute the softmax of logits and calculate entropy
  3224. llama_sample_softmax(nullptr, candidates);
  3225. const int64_t t_start_sample_us = ggml_time_us();
  3226. float entropy = 0.0f;
  3227. for (size_t i = 0; i < candidates->size; ++i) {
  3228. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  3229. }
  3230. // Compute the absolute difference between negative log probability and entropy for each candidate
  3231. std::vector<float> shifted_scores;
  3232. for (size_t i = 0; i < candidates->size; ++i) {
  3233. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  3234. shifted_scores.push_back(shifted_score);
  3235. }
  3236. // Sort tokens based on the shifted_scores and their corresponding indices
  3237. std::vector<size_t> indices(candidates->size);
  3238. std::iota(indices.begin(), indices.end(), 0);
  3239. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  3240. return shifted_scores[a] < shifted_scores[b];
  3241. });
  3242. // Compute the cumulative probabilities
  3243. float cum_sum = 0.0f;
  3244. size_t last_idx = indices.size();
  3245. for (size_t i = 0; i < indices.size(); ++i) {
  3246. size_t idx = indices[i];
  3247. cum_sum += candidates->data[idx].p;
  3248. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  3249. if (cum_sum > p && i >= min_keep - 1) {
  3250. last_idx = i + 1;
  3251. break;
  3252. }
  3253. }
  3254. // Resize the output vector to keep only the locally typical tokens
  3255. std::vector<llama_token_data> new_candidates;
  3256. for (size_t i = 0; i < last_idx; ++i) {
  3257. size_t idx = indices[i];
  3258. new_candidates.push_back(candidates->data[idx]);
  3259. }
  3260. // Replace the data in candidates with the new_candidates data
  3261. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  3262. candidates->size = new_candidates.size();
  3263. if (ctx) {
  3264. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3265. }
  3266. }
  3267. void llama_sample_temperature(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  3268. const int64_t t_start_sample_us = ggml_time_us();
  3269. for (size_t i = 0; i < candidates_p->size; ++i) {
  3270. candidates_p->data[i].logit /= temp;
  3271. }
  3272. if (ctx) {
  3273. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3274. }
  3275. }
  3276. void llama_sample_repetition_penalty(struct llama_context * ctx, llama_token_data_array * candidates, const llama_token * last_tokens, size_t last_tokens_size, float penalty) {
  3277. if (last_tokens_size == 0 || penalty == 1.0f) {
  3278. return;
  3279. }
  3280. const int64_t t_start_sample_us = ggml_time_us();
  3281. for (size_t i = 0; i < candidates->size; ++i) {
  3282. const auto * token_iter = std::find(last_tokens, last_tokens + last_tokens_size, candidates->data[i].id);
  3283. if (token_iter == last_tokens + last_tokens_size) {
  3284. continue;
  3285. }
  3286. // 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.
  3287. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  3288. if (candidates->data[i].logit <= 0) {
  3289. candidates->data[i].logit *= penalty;
  3290. } else {
  3291. candidates->data[i].logit /= penalty;
  3292. }
  3293. }
  3294. candidates->sorted = false;
  3295. if (ctx) {
  3296. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3297. }
  3298. }
  3299. void llama_sample_frequency_and_presence_penalties(struct llama_context * ctx, llama_token_data_array * candidates, const llama_token * last_tokens_p, size_t last_tokens_size, float alpha_frequency, float alpha_presence) {
  3300. if (last_tokens_size == 0 || (alpha_frequency == 0.0f && alpha_presence == 0.0f)) {
  3301. return;
  3302. }
  3303. const int64_t t_start_sample_us = ggml_time_us();
  3304. // Create a frequency map to count occurrences of each token in last_tokens
  3305. std::unordered_map<llama_token, int> token_count;
  3306. for (size_t i = 0; i < last_tokens_size; ++i) {
  3307. token_count[last_tokens_p[i]]++;
  3308. }
  3309. // Apply frequency and presence penalties to the candidates
  3310. for (size_t i = 0; i < candidates->size; ++i) {
  3311. auto token_iter = token_count.find(candidates->data[i].id);
  3312. if (token_iter == token_count.end()) {
  3313. continue;
  3314. }
  3315. int count = token_iter->second;
  3316. candidates->data[i].logit -= float(count) * alpha_frequency + float(count > 0) * alpha_presence;
  3317. }
  3318. candidates->sorted = false;
  3319. if (ctx) {
  3320. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3321. }
  3322. }
  3323. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  3324. GGML_ASSERT(ctx);
  3325. const int64_t t_start_sample_us = ggml_time_us();
  3326. bool allow_eos = false;
  3327. for (const auto & stack : grammar->stacks) {
  3328. if (stack.empty()) {
  3329. allow_eos = true;
  3330. break;
  3331. }
  3332. }
  3333. const llama_token eos = llama_token_eos(ctx);
  3334. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  3335. std::vector<llama_grammar_candidate> candidates_grammar;
  3336. for (size_t i = 0; i < candidates->size; ++i) {
  3337. const llama_token id = candidates->data[i].id;
  3338. const std::string text = llama_token_to_text(ctx, id);
  3339. if (id == eos) {
  3340. if (!allow_eos) {
  3341. candidates->data[i].logit = -INFINITY;
  3342. }
  3343. } else if (text.empty() || text[0] == 0) {
  3344. candidates->data[i].logit = -INFINITY;
  3345. } else {
  3346. candidates_decoded.push_back(decode_utf8(text.c_str(), grammar->partial_utf8));
  3347. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  3348. }
  3349. }
  3350. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  3351. for (const auto & reject : rejects) {
  3352. candidates->data[reject.index].logit = -INFINITY;
  3353. }
  3354. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3355. }
  3356. static void llama_log_softmax(float * array, size_t size) {
  3357. float max_l = *std::max_element(array, array + size);
  3358. float sum = 0.f;
  3359. for (size_t i = 0; i < size; ++i) {
  3360. float p = expf(array[i] - max_l);
  3361. sum += p;
  3362. array[i] = p;
  3363. }
  3364. for (size_t i = 0; i < size; ++i) {
  3365. array[i] = logf(array[i] / sum);
  3366. }
  3367. }
  3368. void llama_sample_classifier_free_guidance(
  3369. struct llama_context * ctx,
  3370. llama_token_data_array * candidates,
  3371. struct llama_context * guidance_ctx,
  3372. float scale) {
  3373. int64_t t_start_sample_us = ggml_time_us();
  3374. GGML_ASSERT(ctx);
  3375. auto n_vocab = llama_n_vocab(ctx);
  3376. GGML_ASSERT(n_vocab == (int)candidates->size);
  3377. GGML_ASSERT(!candidates->sorted);
  3378. std::vector<float> logits_base;
  3379. logits_base.reserve(candidates->size);
  3380. for (size_t i = 0; i < candidates->size; ++i) {
  3381. logits_base.push_back(candidates->data[i].logit);
  3382. }
  3383. llama_log_softmax(logits_base.data(), candidates->size);
  3384. float* logits_guidance = llama_get_logits(guidance_ctx);
  3385. llama_log_softmax(logits_guidance, n_vocab);
  3386. for (int i = 0; i < n_vocab; ++i) {
  3387. float logit_guidance = logits_guidance[i];
  3388. float logit_base = logits_base[i];
  3389. candidates->data[i].logit = scale * (logit_base - logit_guidance) + logit_guidance;
  3390. }
  3391. if (ctx) {
  3392. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3393. }
  3394. }
  3395. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int m, float * mu) {
  3396. GGML_ASSERT(ctx);
  3397. auto N = float(llama_n_vocab(ctx));
  3398. int64_t t_start_sample_us;
  3399. t_start_sample_us = ggml_time_us();
  3400. llama_sample_softmax(nullptr, candidates);
  3401. // Estimate s_hat using the most probable m tokens
  3402. float s_hat = 0.0;
  3403. float sum_ti_bi = 0.0;
  3404. float sum_ti_sq = 0.0;
  3405. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  3406. float t_i = logf(float(i + 2) / float(i + 1));
  3407. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  3408. sum_ti_bi += t_i * b_i;
  3409. sum_ti_sq += t_i * t_i;
  3410. }
  3411. s_hat = sum_ti_bi / sum_ti_sq;
  3412. // Compute k from the estimated s_hat and target surprise value
  3413. float epsilon_hat = s_hat - 1;
  3414. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  3415. // Sample the next word X using top-k sampling
  3416. llama_sample_top_k(nullptr, candidates, int(k), 1);
  3417. if (ctx) {
  3418. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3419. }
  3420. llama_token X = llama_sample_token(ctx, candidates);
  3421. t_start_sample_us = ggml_time_us();
  3422. // Compute error as the difference between observed surprise and target surprise value
  3423. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  3424. return candidate.id == X;
  3425. }));
  3426. float observed_surprise = -log2f(candidates->data[X_idx].p);
  3427. float e = observed_surprise - tau;
  3428. // Update mu using the learning rate and error
  3429. *mu = *mu - eta * e;
  3430. if (ctx) {
  3431. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3432. }
  3433. return X;
  3434. }
  3435. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  3436. int64_t t_start_sample_us;
  3437. t_start_sample_us = ggml_time_us();
  3438. llama_sample_softmax(ctx, candidates);
  3439. // Truncate the words with surprise values greater than mu
  3440. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  3441. return -log2f(candidate.p) > *mu;
  3442. }));
  3443. if (candidates->size == 0) {
  3444. candidates->size = 1;
  3445. }
  3446. if (ctx) {
  3447. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3448. }
  3449. // Normalize the probabilities of the remaining words
  3450. llama_sample_softmax(ctx, candidates);
  3451. // Sample the next word X from the remaining words
  3452. llama_token X = llama_sample_token(ctx, candidates);
  3453. t_start_sample_us = ggml_time_us();
  3454. // Compute error as the difference between observed surprise and target surprise value
  3455. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  3456. return candidate.id == X;
  3457. }));
  3458. float observed_surprise = -log2f(candidates->data[X_idx].p);
  3459. float e = observed_surprise - tau;
  3460. // Update mu using the learning rate and error
  3461. *mu = *mu - eta * e;
  3462. if (ctx) {
  3463. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3464. }
  3465. return X;
  3466. }
  3467. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  3468. const int64_t t_start_sample_us = ggml_time_us();
  3469. // Find max element
  3470. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  3471. return a.logit < b.logit;
  3472. });
  3473. llama_token result = max_iter->id;
  3474. if (ctx) {
  3475. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3476. ctx->n_sample++;
  3477. }
  3478. return result;
  3479. }
  3480. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  3481. GGML_ASSERT(ctx);
  3482. const int64_t t_start_sample_us = ggml_time_us();
  3483. llama_sample_softmax(nullptr, candidates);
  3484. std::vector<float> probs;
  3485. probs.reserve(candidates->size);
  3486. for (size_t i = 0; i < candidates->size; ++i) {
  3487. probs.push_back(candidates->data[i].p);
  3488. }
  3489. std::discrete_distribution<> dist(probs.begin(), probs.end());
  3490. auto & rng = ctx->rng;
  3491. int idx = dist(rng);
  3492. llama_token result = candidates->data[idx].id;
  3493. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3494. ctx->n_sample++;
  3495. return result;
  3496. }
  3497. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  3498. const int64_t t_start_sample_us = ggml_time_us();
  3499. if (token == llama_token_eos(ctx)) {
  3500. for (const auto & stack : grammar->stacks) {
  3501. if (stack.empty()) {
  3502. return;
  3503. }
  3504. }
  3505. GGML_ASSERT(false);
  3506. }
  3507. const std::string text = llama_token_to_text(ctx, token);
  3508. // Note terminating 0 in decoded string
  3509. const auto decoded = decode_utf8(text.c_str(), grammar->partial_utf8);
  3510. const auto & code_points = decoded.first;
  3511. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  3512. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  3513. }
  3514. grammar->partial_utf8 = decoded.second;
  3515. GGML_ASSERT(!grammar->stacks.empty());
  3516. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3517. }
  3518. //
  3519. // Beam search
  3520. //
  3521. struct llama_beam {
  3522. std::vector<llama_token> tokens;
  3523. float p; // Cumulative beam probability (renormalized relative to all beams)
  3524. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  3525. // Sort beams by probability. In case of ties, prefer beams at eob.
  3526. bool operator<(const llama_beam & rhs) const {
  3527. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  3528. }
  3529. // Shift off first n tokens and discard them.
  3530. void shift_tokens(const size_t n) {
  3531. if (n) {
  3532. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  3533. tokens.resize(tokens.size() - n);
  3534. }
  3535. }
  3536. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  3537. };
  3538. // A struct for calculating logit-related info.
  3539. struct llama_logit_info {
  3540. const float * const logits;
  3541. const int n_vocab;
  3542. const float max_l;
  3543. const float normalizer;
  3544. struct sum_exp {
  3545. float max_l;
  3546. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  3547. };
  3548. llama_logit_info(llama_context * ctx)
  3549. : logits(llama_get_logits(ctx))
  3550. , n_vocab(llama_n_vocab(ctx))
  3551. , max_l(*std::max_element(logits, logits + n_vocab))
  3552. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  3553. { }
  3554. llama_token_data get_token_data(const llama_token token_id) const {
  3555. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  3556. return {token_id, logits[token_id], p};
  3557. }
  3558. // Return top k token_data by logit.
  3559. std::vector<llama_token_data> top_k(size_t k) {
  3560. std::vector<llama_token_data> min_heap; // min-heap by logit
  3561. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  3562. min_heap.reserve(k_min);
  3563. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  3564. min_heap.push_back(get_token_data(token_id));
  3565. }
  3566. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  3567. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  3568. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  3569. if (min_heap.front().logit < logits[token_id]) {
  3570. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  3571. min_heap.back().id = token_id;
  3572. min_heap.back().logit = logits[token_id];
  3573. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  3574. }
  3575. }
  3576. return min_heap;
  3577. }
  3578. float probability_from_logit(float logit) {
  3579. return normalizer * std::exp(logit - max_l);
  3580. }
  3581. };
  3582. struct llama_beam_search_data {
  3583. llama_context * ctx;
  3584. size_t n_beams;
  3585. int n_past;
  3586. int n_predict;
  3587. int n_threads;
  3588. std::vector<llama_beam> beams;
  3589. std::vector<llama_beam> next_beams;
  3590. // Re-calculated on each loop iteration
  3591. size_t common_prefix_length;
  3592. // Used to communicate to/from callback on beams state.
  3593. std::vector<llama_beam_view> beam_views;
  3594. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict, int n_threads)
  3595. : ctx(ctx)
  3596. , n_beams(n_beams)
  3597. , n_past(n_past)
  3598. , n_predict(n_predict)
  3599. , n_threads(n_threads)
  3600. , beam_views(n_beams) {
  3601. beams.reserve(n_beams);
  3602. next_beams.reserve(n_beams);
  3603. }
  3604. // Collapse beams to a single beam given by index.
  3605. void collapse_beams(const size_t beam_idx) {
  3606. if (0u < beam_idx) {
  3607. std::swap(beams[0], beams[beam_idx]);
  3608. }
  3609. beams.resize(1);
  3610. }
  3611. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  3612. // The repetative patterns below reflect the 2 stages of heaps:
  3613. // * Gather elements until the vector is full, then call std::make_heap() on it.
  3614. // * If the heap is full and a new element is found that should be included, pop the
  3615. // least element to the back(), replace it with the new, then push it into the heap.
  3616. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  3617. // Min-heaps use a greater-than comparator.
  3618. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  3619. if (beam.eob) {
  3620. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  3621. if (next_beams.size() < n_beams) {
  3622. next_beams.push_back(std::move(beam));
  3623. if (next_beams.size() == n_beams) {
  3624. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  3625. }
  3626. } else if (next_beams.front().p < beam.p) {
  3627. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  3628. next_beams.back() = std::move(beam);
  3629. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  3630. }
  3631. } else {
  3632. // beam is not at end-of-sentence, so branch with next top_k tokens.
  3633. if (!beam.tokens.empty()) {
  3634. llama_eval(ctx, beam.tokens.data(), beam.tokens.size(), n_past, n_threads);
  3635. }
  3636. llama_logit_info logit_info(ctx);
  3637. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  3638. size_t i=0;
  3639. if (next_beams.size() < n_beams) {
  3640. for (; next_beams.size() < n_beams ; ++i) {
  3641. llama_beam next_beam = beam;
  3642. next_beam.tokens.push_back(next_tokens[i].id);
  3643. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  3644. next_beams.push_back(std::move(next_beam));
  3645. }
  3646. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  3647. } else {
  3648. for (; next_beams.front().p == 0.0f ; ++i) {
  3649. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  3650. next_beams.back() = beam;
  3651. next_beams.back().tokens.push_back(next_tokens[i].id);
  3652. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  3653. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  3654. }
  3655. }
  3656. for (; i < n_beams ; ++i) {
  3657. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  3658. if (next_beams.front().p < next_p) {
  3659. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  3660. next_beams.back() = beam;
  3661. next_beams.back().tokens.push_back(next_tokens[i].id);
  3662. next_beams.back().p = next_p;
  3663. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  3664. }
  3665. }
  3666. }
  3667. }
  3668. // Find common_prefix_length based on beams.
  3669. // Requires beams is not empty.
  3670. size_t find_common_prefix_length() {
  3671. size_t common_prefix_length = beams[0].tokens.size();
  3672. for (size_t i = 1 ; i < beams.size() ; ++i) {
  3673. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  3674. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  3675. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  3676. common_prefix_length = j;
  3677. break;
  3678. }
  3679. }
  3680. }
  3681. return common_prefix_length;
  3682. }
  3683. // Construct beams_state to send back to caller via the callback function.
  3684. // Side effect: set common_prefix_length = find_common_prefix_length();
  3685. llama_beams_state get_beams_state(const bool last_call) {
  3686. for (size_t i = 0 ; i < beams.size() ; ++i) {
  3687. beam_views[i] = beams[i].view();
  3688. }
  3689. common_prefix_length = find_common_prefix_length();
  3690. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  3691. }
  3692. // Loop:
  3693. // * while i < n_predict, AND
  3694. // * any of the beams have not yet reached end-of-beam (eob), AND
  3695. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  3696. // (since all other beam probabilities can only decrease)
  3697. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  3698. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  3699. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  3700. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  3701. !beams[top_beam_index()].eob ; ++i) {
  3702. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  3703. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  3704. if (common_prefix_length) {
  3705. llama_eval(ctx, beams[0].tokens.data(), common_prefix_length, n_past, n_threads);
  3706. n_past += common_prefix_length;
  3707. }
  3708. // Zero-out next_beam probabilities to place them last in following min-heap.
  3709. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  3710. for (llama_beam & beam : beams) {
  3711. beam.shift_tokens(common_prefix_length);
  3712. fill_next_beams_by_top_probabilities(beam);
  3713. }
  3714. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  3715. beams.swap(next_beams);
  3716. renormalize_beam_probabilities(beams);
  3717. }
  3718. collapse_beams(top_beam_index());
  3719. callback(callback_data, get_beams_state(true));
  3720. }
  3721. // As beams grow, the cumulative probabilities decrease.
  3722. // Renormalize them to avoid floating point underflow.
  3723. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  3724. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  3725. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  3726. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  3727. }
  3728. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  3729. size_t top_beam_index() {
  3730. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  3731. }
  3732. // Copy (p,eob) for each beam which may have been changed by the callback.
  3733. void update_beams_from_beam_views() {
  3734. for (size_t i = 0 ; i < beams.size() ; ++i) {
  3735. beams[i].p = beam_views[i].p;
  3736. beams[i].eob = beam_views[i].eob;
  3737. }
  3738. }
  3739. };
  3740. void llama_beam_search(llama_context * ctx,
  3741. llama_beam_search_callback_fn_t callback, void * callback_data,
  3742. size_t n_beams, int n_past, int n_predict, int n_threads) {
  3743. assert(ctx);
  3744. const int64_t t_start_sample_us = ggml_time_us();
  3745. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict, n_threads);
  3746. beam_search_data.loop(callback, callback_data);
  3747. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3748. ctx->n_sample++;
  3749. }
  3750. //
  3751. // quantization
  3752. //
  3753. static void llama_convert_tensor_internal(struct ggml_tensor * tensor, std::vector<float> & output, const size_t nelements, const int nthread) {
  3754. if (output.size() < nelements) {
  3755. output.resize(nelements);
  3756. }
  3757. float * f32_output = (float *) output.data();
  3758. ggml_type_traits_t qtype;
  3759. if (ggml_is_quantized(tensor->type)) {
  3760. qtype = ggml_internal_get_type_traits(tensor->type);
  3761. if (qtype.to_float == NULL) {
  3762. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  3763. }
  3764. } else if (tensor->type != GGML_TYPE_F16) {
  3765. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  3766. }
  3767. if (nthread < 2) {
  3768. if (tensor->type == GGML_TYPE_F16) {
  3769. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  3770. } else if (ggml_is_quantized(tensor->type)) {
  3771. qtype.to_float(tensor->data, f32_output, nelements);
  3772. } else {
  3773. GGML_ASSERT(false); // unreachable
  3774. }
  3775. return;
  3776. }
  3777. auto block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  3778. auto block_size_bytes = ggml_type_size(tensor->type);
  3779. GGML_ASSERT(nelements % block_size == 0);
  3780. auto nblocks = nelements / block_size;
  3781. auto blocks_per_thread = nblocks / nthread;
  3782. auto spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  3783. std::vector<std::thread> workers;
  3784. for (auto tnum = 0, in_buff_offs = 0, out_buff_offs = 0; tnum < nthread; tnum++) {
  3785. auto thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  3786. auto thr_elems = thr_blocks * block_size; // number of elements for this thread
  3787. auto thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  3788. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  3789. if (typ == GGML_TYPE_F16) {
  3790. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  3791. } else {
  3792. qtype.to_float(inbuf, outbuf, nels);
  3793. }
  3794. };
  3795. workers.push_back(std::thread(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems));
  3796. in_buff_offs += thr_block_bytes;
  3797. out_buff_offs += thr_elems;
  3798. }
  3799. for (auto & worker : workers) {
  3800. worker.join();
  3801. }
  3802. }
  3803. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  3804. ggml_type quantized_type;
  3805. llama_ftype ftype = params->ftype;
  3806. switch (params->ftype) {
  3807. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  3808. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  3809. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  3810. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  3811. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  3812. case LLAMA_FTYPE_MOSTLY_F16: quantized_type = GGML_TYPE_F16; break;
  3813. case LLAMA_FTYPE_ALL_F32: quantized_type = GGML_TYPE_F32; break;
  3814. #ifdef GGML_USE_K_QUANTS
  3815. // K-quants
  3816. case LLAMA_FTYPE_MOSTLY_Q2_K: quantized_type = GGML_TYPE_Q2_K; break;
  3817. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  3818. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  3819. case LLAMA_FTYPE_MOSTLY_Q3_K_L: quantized_type = GGML_TYPE_Q3_K; break;
  3820. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  3821. case LLAMA_FTYPE_MOSTLY_Q4_K_M: quantized_type = GGML_TYPE_Q4_K; break;
  3822. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  3823. case LLAMA_FTYPE_MOSTLY_Q5_K_M: quantized_type = GGML_TYPE_Q5_K; break;
  3824. case LLAMA_FTYPE_MOSTLY_Q6_K: quantized_type = GGML_TYPE_Q6_K; break;
  3825. #endif
  3826. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  3827. }
  3828. int nthread = params->nthread;
  3829. if (nthread <= 0) {
  3830. nthread = std::thread::hardware_concurrency();
  3831. }
  3832. std::unique_ptr<llama_model_loader> ml(new llama_model_loader(fname_inp, /*use_mmap*/ false));
  3833. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  3834. struct gguf_context * ctx_out = gguf_init_empty();
  3835. // copy the KV pairs from the input file
  3836. gguf_set_kv (ctx_out, ml->ctx_gguf);
  3837. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  3838. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  3839. #ifdef GGML_USE_K_QUANTS
  3840. int n_attention_wv = 0;
  3841. int n_feed_forward_w2 = 0;
  3842. for (int i = 0; i < ml->n_tensors; ++i) {
  3843. struct ggml_tensor * meta = ml->get_tensor_meta(i);
  3844. const std::string name = ggml_get_name(meta);
  3845. // TODO: avoid hardcoded tensor names - use the TN_* constants
  3846. if (name.find("attn_v.weight") != std::string::npos) {
  3847. ++n_attention_wv;
  3848. }
  3849. else if (name.find("ffn_down.weight") != std::string::npos) {
  3850. ++n_feed_forward_w2;
  3851. }
  3852. }
  3853. int i_attention_wv = 0;
  3854. int i_feed_forward_w2 = 0;
  3855. #endif
  3856. size_t total_size_org = 0;
  3857. size_t total_size_new = 0;
  3858. std::vector<int64_t> hist_all(1 << 4, 0);
  3859. std::vector<std::thread> workers;
  3860. std::mutex mutex;
  3861. auto use_more_bits = [] (int i_layer, int num_layers) -> bool {
  3862. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  3863. };
  3864. int idx = 0;
  3865. std::vector<uint8_t> read_data;
  3866. std::vector<uint8_t> work;
  3867. // populate the original tensors so we get an initial meta data
  3868. for (int i = 0; i < ml->n_tensors; ++i) {
  3869. struct ggml_tensor * meta = ml->get_tensor_meta(i);
  3870. gguf_add_tensor(ctx_out, meta);
  3871. }
  3872. std::ofstream fout(fname_out, std::ios::binary);
  3873. const size_t meta_size = gguf_get_meta_size(ctx_out);
  3874. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  3875. // placeholder for the meta data
  3876. ::zeros(fout, meta_size);
  3877. for (int i = 0; i < ml->n_tensors; ++i) {
  3878. struct ggml_tensor * tensor = ml->get_tensor_meta(i);
  3879. const std::string name = ggml_get_name(tensor);
  3880. read_data.resize(ggml_nbytes(tensor));
  3881. tensor->data = read_data.data();
  3882. ml->load_data_for(tensor);
  3883. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  3884. ++idx, ml->n_tensors,
  3885. ggml_get_name(tensor),
  3886. llama_format_tensor_shape(tensor).c_str(),
  3887. ggml_type_name(tensor->type));
  3888. // This used to be a regex, but <regex> has an extreme cost to compile times.
  3889. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  3890. // quantize only 2D tensors
  3891. quantize &= (tensor->n_dims == 2);
  3892. quantize &= params->quantize_output_tensor || name != "output.weight";
  3893. quantize &= quantized_type != tensor->type;
  3894. enum ggml_type new_type;
  3895. void * new_data;
  3896. size_t new_size;
  3897. if (!quantize) {
  3898. new_type = tensor->type;
  3899. new_data = tensor->data;
  3900. new_size = ggml_nbytes(tensor);
  3901. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  3902. } else {
  3903. new_type = quantized_type;
  3904. #ifdef GGML_USE_K_QUANTS
  3905. // TODO: avoid hardcoded tensor names - use the TN_* constants
  3906. const auto tn = LLM_TN(ml->get_arch());
  3907. if (name == tn(LLM_TENSOR_OUTPUT, "weight")) {
  3908. int nx = tensor->ne[0];
  3909. int ny = tensor->ne[1];
  3910. if (nx % QK_K == 0 && ny % QK_K == 0) {
  3911. new_type = GGML_TYPE_Q6_K;
  3912. }
  3913. } else if (name.find("attn_v.weight") != std::string::npos) {
  3914. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  3915. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  3916. new_type = i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  3917. }
  3918. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  3919. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  3920. use_more_bits(i_attention_wv, n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  3921. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  3922. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  3923. (i_attention_wv < n_attention_wv/8 || i_attention_wv >= 7*n_attention_wv/8)) new_type = GGML_TYPE_Q6_K;
  3924. ++i_attention_wv;
  3925. } else if (name.find("ffn_down.weight") != std::string::npos) {
  3926. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  3927. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  3928. new_type = i_feed_forward_w2 < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  3929. }
  3930. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  3931. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  3932. use_more_bits(i_feed_forward_w2, n_feed_forward_w2)) new_type = GGML_TYPE_Q6_K;
  3933. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && i_feed_forward_w2 < 4) new_type = GGML_TYPE_Q5_K;
  3934. ++i_feed_forward_w2;
  3935. } else if (name.find("attn_output.weight") != std::string::npos) {
  3936. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  3937. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) new_type = GGML_TYPE_Q4_K;
  3938. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  3939. }
  3940. else if (name.find("ffn_gate.weight") != std::string::npos || name.find("ffn_up.weight") != std::string::npos) {
  3941. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  3942. }
  3943. // This can be used to reduce the size of the Q5_K_S model.
  3944. // The associated PPL increase is fully in line with the size reduction
  3945. //else {
  3946. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  3947. //}
  3948. bool convert_incompatible_tensor = false;
  3949. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  3950. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K) {
  3951. int nx = tensor->ne[0];
  3952. int ny = tensor->ne[1];
  3953. if (nx % QK_K != 0 || ny % QK_K != 0) {
  3954. LLAMA_LOG_INFO("\n\nTensor sizes %d x %d are not divisible by %d, required for k-quants.\n",nx,ny,QK_K);
  3955. convert_incompatible_tensor = true;
  3956. }
  3957. }
  3958. if (convert_incompatible_tensor) {
  3959. if (name == tn(LLM_TENSOR_OUTPUT, "weight")) {
  3960. new_type = GGML_TYPE_F16; //fall back to F16 instead of just failing.
  3961. LLAMA_LOG_WARN("F16 will be used for this tensor instead.\n");
  3962. } else if (name == tn(LLM_TENSOR_TOKEN_EMBD, "weight")) {
  3963. new_type = GGML_TYPE_Q4_0; //fall back to Q4_0 instead of just failing.
  3964. LLAMA_LOG_WARN("Q4_0 will be used for this tensor instead.\n");
  3965. } else {
  3966. throw std::runtime_error("Unsupported tensor size encountered\n");
  3967. }
  3968. }
  3969. #endif
  3970. const size_t nelements = ggml_nelements(tensor);
  3971. float * f32_data;
  3972. std::vector<float> f32_conv_buf;
  3973. if (tensor->type == GGML_TYPE_F32) {
  3974. f32_data = (float *) tensor->data;
  3975. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  3976. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  3977. } else {
  3978. llama_convert_tensor_internal(tensor, f32_conv_buf, nelements, nthread);
  3979. f32_data = (float *) f32_conv_buf.data();
  3980. }
  3981. LLAMA_LOG_INFO("quantizing to %s .. ", ggml_type_name(new_type));
  3982. fflush(stdout);
  3983. work.resize(nelements * 4); // upper bound on size
  3984. new_data = work.data();
  3985. std::vector<int64_t> hist_cur(1 << 4, 0);
  3986. static const int chunk_size = 32 * 512;
  3987. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  3988. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  3989. if (nthread_use < 2) {
  3990. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nelements, hist_cur.data());
  3991. } else {
  3992. size_t counter = 0;
  3993. new_size = 0;
  3994. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, nelements]() {
  3995. std::vector<int64_t> local_hist;
  3996. size_t local_size = 0;
  3997. while (true) {
  3998. std::unique_lock<std::mutex> lock(mutex);
  3999. size_t first = counter; counter += chunk_size;
  4000. if (first >= nelements) {
  4001. if (!local_hist.empty()) {
  4002. for (int j=0; j<int(local_hist.size()); ++j) {
  4003. hist_cur[j] += local_hist[j];
  4004. }
  4005. new_size += local_size;
  4006. }
  4007. break;
  4008. }
  4009. lock.unlock();
  4010. size_t last = std::min(nelements, first + chunk_size);
  4011. if (local_hist.empty()) {
  4012. local_hist.resize(hist_cur.size(), 0);
  4013. }
  4014. local_size += ggml_quantize_chunk(new_type, f32_data, new_data, first, last - first, local_hist.data());
  4015. }
  4016. };
  4017. if ((int) workers.size() < nthread_use - 1) {
  4018. workers.resize(nthread_use - 1);
  4019. }
  4020. for (int it = 0; it < nthread_use - 1; ++it) {
  4021. workers[it] = std::thread(compute);
  4022. }
  4023. compute();
  4024. for (int it = 0; it < nthread_use - 1; ++it) {
  4025. workers[it].join();
  4026. }
  4027. }
  4028. LLAMA_LOG_INFO("size = %8.2f MB -> %8.2f MB | hist: ", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  4029. int64_t tot_count = 0;
  4030. for (size_t i = 0; i < hist_cur.size(); i++) {
  4031. hist_all[i] += hist_cur[i];
  4032. tot_count += hist_cur[i];
  4033. }
  4034. if (tot_count > 0) {
  4035. for (size_t i = 0; i < hist_cur.size(); i++) {
  4036. LLAMA_LOG_INFO("%5.3f ", hist_cur[i] / float(nelements));
  4037. }
  4038. }
  4039. LLAMA_LOG_INFO("\n");
  4040. }
  4041. total_size_org += ggml_nbytes(tensor);
  4042. total_size_new += new_size;
  4043. // update the gguf meta data as we go
  4044. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  4045. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  4046. // write tensor data + padding
  4047. fout.write((const char *) new_data, new_size);
  4048. zeros(fout, GGML_PAD(new_size, align) - new_size);
  4049. }
  4050. // go back to beginning of file and write the updated meta data
  4051. {
  4052. fout.seekp(0);
  4053. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  4054. gguf_get_meta_data(ctx_out, data.data());
  4055. fout.write((const char *) data.data(), data.size());
  4056. }
  4057. fout.close();
  4058. gguf_free(ctx_out);
  4059. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  4060. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  4061. // print histogram for all tensors
  4062. {
  4063. int64_t sum_all = 0;
  4064. for (size_t i = 0; i < hist_all.size(); i++) {
  4065. sum_all += hist_all[i];
  4066. }
  4067. if (sum_all > 0) {
  4068. LLAMA_LOG_INFO("%s: hist: ", __func__);
  4069. for (size_t i = 0; i < hist_all.size(); i++) {
  4070. LLAMA_LOG_INFO("%5.3f ", hist_all[i] / float(sum_all));
  4071. }
  4072. LLAMA_LOG_INFO("\n");
  4073. }
  4074. }
  4075. }
  4076. // TODO: after the GGUF PR, this likely won't work and needs to be updated
  4077. int llama_apply_lora_from_file_internal(const struct llama_model & model, const char * path_lora, const char * path_base_model, int n_threads) {
  4078. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  4079. const int64_t t_start_lora_us = ggml_time_us();
  4080. auto fin = std::ifstream(path_lora, std::ios::binary);
  4081. if (!fin) {
  4082. LLAMA_LOG_ERROR("%s: failed to open '%s'\n", __func__, path_lora);
  4083. return 1;
  4084. }
  4085. // verify magic and version
  4086. {
  4087. uint32_t magic;
  4088. fin.read((char *) &magic, sizeof(magic));
  4089. uint32_t format_version;
  4090. fin.read((char *) &format_version, sizeof(format_version));
  4091. if (format_version != 1) {
  4092. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  4093. return 1;
  4094. }
  4095. }
  4096. int32_t lora_r;
  4097. int32_t lora_alpha;
  4098. fin.read((char *) &lora_r, sizeof(lora_r));
  4099. fin.read((char *) &lora_alpha, sizeof(lora_alpha));
  4100. float scaling = (float)lora_alpha / (float)lora_r;
  4101. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  4102. // create a temporary ggml context to store the lora tensors
  4103. // todo: calculate size from biggest possible tensor
  4104. std::vector<uint8_t> lora_buf(1024ull * 1024ull * 1024ull);
  4105. struct ggml_init_params params;
  4106. params.mem_size = lora_buf.size();
  4107. params.mem_buffer = lora_buf.data();
  4108. params.no_alloc = false;
  4109. ggml_context * lora_ctx = ggml_init(params);
  4110. std::unordered_map<std::string, struct ggml_tensor *> lora_tensors;
  4111. // create a name -> tensor map of the model to accelerate lookups
  4112. std::unordered_map<std::string, struct ggml_tensor*> model_tensors;
  4113. for (const auto & kv : model.tensors_by_name) {
  4114. model_tensors.insert(kv);
  4115. }
  4116. // load base model
  4117. std::unique_ptr<llama_model_loader> ml;
  4118. ggml_context * base_ctx = NULL;
  4119. std::vector<uint8_t> base_buf;
  4120. if (path_base_model) {
  4121. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  4122. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true));
  4123. size_t ctx_size;
  4124. size_t mmapped_size;
  4125. ml->calc_sizes(ctx_size, mmapped_size);
  4126. base_buf.resize(ctx_size);
  4127. ggml_init_params base_params;
  4128. base_params.mem_size = base_buf.size();
  4129. base_params.mem_buffer = base_buf.data();
  4130. base_params.no_alloc = ml->use_mmap;
  4131. base_ctx = ggml_init(base_params);
  4132. // maybe this should in llama_model_loader
  4133. if (ml->use_mmap) {
  4134. ml->mapping.reset(new llama_mmap(&ml->file, /* prefetch */ 0, ggml_is_numa()));
  4135. }
  4136. }
  4137. // read tensors and apply
  4138. bool warned = false;
  4139. int n_tensors = 0;
  4140. std::vector<uint8_t> work_buffer;
  4141. while (true) {
  4142. int32_t n_dims;
  4143. int32_t length;
  4144. int32_t ftype;
  4145. fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  4146. fin.read(reinterpret_cast<char *>(&length), sizeof(length));
  4147. fin.read(reinterpret_cast<char *>(&ftype), sizeof(ftype));
  4148. if (fin.eof()) {
  4149. break;
  4150. }
  4151. int32_t ne[2] = { 1, 1 };
  4152. for (int i = 0; i < n_dims; ++i) {
  4153. fin.read(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  4154. }
  4155. std::string name;
  4156. {
  4157. char buf[1024];
  4158. fin.read(buf, length);
  4159. name = std::string(buf, length);
  4160. }
  4161. // check for lora suffix and get the type of tensor
  4162. const std::string lora_suffix = ".lora";
  4163. size_t pos = name.rfind(lora_suffix);
  4164. if (pos == std::string::npos) {
  4165. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  4166. return 1;
  4167. }
  4168. std::string lora_type = name.substr(pos + lora_suffix.length());
  4169. std::string base_name = name;
  4170. base_name.erase(pos);
  4171. // LLAMA_LOG_INFO("%s: %s => %s (lora type %s) \n", __func__, name.c_str(),base_name.c_str(), lora_type.c_str());
  4172. if (model_tensors.find(base_name) == model_tensors.end()) {
  4173. LLAMA_LOG_ERROR("%s: unknown tensor '%s' in lora adapter\n", __func__, name.data());
  4174. return 1;
  4175. }
  4176. // create ggml tensor
  4177. ggml_type wtype;
  4178. switch (ftype) {
  4179. case 0: wtype = GGML_TYPE_F32; break;
  4180. case 1: wtype = GGML_TYPE_F16; break;
  4181. default:
  4182. {
  4183. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  4184. __func__, ftype);
  4185. return false;
  4186. }
  4187. }
  4188. ggml_tensor * lora_tensor;
  4189. if (n_dims == 2) {
  4190. lora_tensor = ggml_new_tensor_2d(lora_ctx, wtype, ne[0], ne[1]);
  4191. }
  4192. else {
  4193. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  4194. return 1;
  4195. }
  4196. ggml_set_name(lora_tensor, "lora_tensor");
  4197. // load tensor data
  4198. size_t offset = fin.tellg();
  4199. size_t tensor_data_size = ggml_nbytes(lora_tensor);
  4200. offset = (offset + 31) & -32;
  4201. fin.seekg(offset);
  4202. fin.read((char*)lora_tensor->data, tensor_data_size);
  4203. lora_tensors[name] = lora_tensor;
  4204. // check if we have both A and B tensors and apply
  4205. if (lora_tensors.find(base_name + ".loraA") != lora_tensors.end() &&
  4206. lora_tensors.find(base_name + ".loraB") != lora_tensors.end()) {
  4207. ggml_tensor * dest_t = model_tensors[base_name];
  4208. offload_func_t offload_func = llama_nop;
  4209. offload_func_t offload_func_force_inplace = llama_nop;
  4210. #ifdef GGML_USE_CUBLAS
  4211. if (dest_t->backend == GGML_BACKEND_GPU || dest_t->backend == GGML_BACKEND_GPU_SPLIT) {
  4212. if (dest_t->type != GGML_TYPE_F16) {
  4213. throw std::runtime_error(format(
  4214. "%s: error: the simultaneous use of LoRAs and GPU acceleration is only supported for f16 models", __func__));
  4215. }
  4216. offload_func = ggml_cuda_assign_buffers;
  4217. offload_func_force_inplace = ggml_cuda_assign_buffers_force_inplace;
  4218. }
  4219. #endif // GGML_USE_CUBLAS
  4220. ggml_tensor * base_t;
  4221. if (ml) {
  4222. struct gguf_context * ctx_gguf = ml->ctx_gguf;
  4223. // load from base model
  4224. if (gguf_find_tensor(ctx_gguf, base_name.c_str()) < 0) {
  4225. // TODO: throw
  4226. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  4227. return 1;
  4228. }
  4229. // TODO: not tested!! maybe not working!
  4230. base_t = ml->create_tensor(base_ctx, base_name, { (uint32_t)dest_t->ne[0], (uint32_t)dest_t->ne[1] }, GGML_BACKEND_CPU);
  4231. ml->load_data_for(base_t);
  4232. } else {
  4233. base_t = dest_t;
  4234. }
  4235. if (ggml_is_quantized(base_t->type)) {
  4236. if (!warned) {
  4237. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  4238. "use a f16 or f32 base model with --lora-base\n", __func__);
  4239. warned = true;
  4240. }
  4241. }
  4242. ggml_tensor * loraA = lora_tensors[base_name + ".loraA"];
  4243. GGML_ASSERT(loraA->type == GGML_TYPE_F32);
  4244. ggml_set_name(loraA, "loraA");
  4245. ggml_tensor * loraB = lora_tensors[base_name + ".loraB"];
  4246. GGML_ASSERT(loraB->type == GGML_TYPE_F32);
  4247. ggml_set_name(loraB, "loraB");
  4248. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  4249. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  4250. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  4251. return 1;
  4252. }
  4253. // w = w + BA*s
  4254. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  4255. offload_func(BA);
  4256. ggml_set_name(BA, "BA");
  4257. if (scaling != 1.0f) {
  4258. ggml_tensor * scale_tensor = ggml_new_f32(lora_ctx, scaling);
  4259. ggml_set_name(scale_tensor, "scale_tensor");
  4260. BA = ggml_scale_inplace(lora_ctx, BA, scale_tensor);
  4261. offload_func(BA);
  4262. ggml_set_name(BA, "BA_scaled");
  4263. }
  4264. ggml_tensor * r;
  4265. if (base_t == dest_t) {
  4266. r = ggml_add_inplace(lora_ctx, dest_t, BA);
  4267. offload_func_force_inplace(r);
  4268. ggml_set_name(r, "r_add_inplace");
  4269. }
  4270. else {
  4271. r = ggml_add(lora_ctx, base_t, BA);
  4272. offload_func(r);
  4273. ggml_set_name(r, "r_add");
  4274. r = ggml_cpy(lora_ctx, r, dest_t);
  4275. offload_func(r);
  4276. ggml_set_name(r, "r_cpy");
  4277. }
  4278. struct ggml_cgraph gf = ggml_build_forward(r);
  4279. ggml_graph_compute_helper(work_buffer, &gf, n_threads);
  4280. // we won't need these tensors again, reset the context to save memory
  4281. ggml_free(lora_ctx);
  4282. lora_ctx = ggml_init(params);
  4283. lora_tensors.clear();
  4284. n_tensors++;
  4285. if (n_tensors % 4 == 0) {
  4286. LLAMA_LOG_INFO(".");
  4287. }
  4288. }
  4289. }
  4290. // TODO: this should be in a destructor, it will leak on failure
  4291. ggml_free(lora_ctx);
  4292. if (base_ctx) {
  4293. ggml_free(base_ctx);
  4294. }
  4295. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  4296. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  4297. return 0;
  4298. }
  4299. //
  4300. // interface implementation
  4301. //
  4302. struct llama_context_params llama_context_default_params() {
  4303. struct llama_context_params result = {
  4304. /*.seed =*/ LLAMA_DEFAULT_SEED,
  4305. /*.n_ctx =*/ 512,
  4306. /*.n_batch =*/ 512,
  4307. /*.gpu_layers =*/ 0,
  4308. /*.main_gpu =*/ 0,
  4309. /*.tensor_split =*/ nullptr,
  4310. /*.rope_freq_base =*/ 10000.0f,
  4311. /*.rope_freq_scale =*/ 1.0f,
  4312. /*.progress_callback =*/ nullptr,
  4313. /*.progress_callback_user_data =*/ nullptr,
  4314. /*.low_vram =*/ false,
  4315. /*.mul_mat_q =*/ false,
  4316. /*.f16_kv =*/ true,
  4317. /*.logits_all =*/ false,
  4318. /*.vocab_only =*/ false,
  4319. /*.use_mmap =*/ true,
  4320. /*.use_mlock =*/ false,
  4321. /*.embedding =*/ false,
  4322. };
  4323. return result;
  4324. }
  4325. struct llama_model_quantize_params llama_model_quantize_default_params() {
  4326. struct llama_model_quantize_params result = {
  4327. /*.nthread =*/ 0,
  4328. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  4329. /*.allow_requantize =*/ false,
  4330. /*.quantize_output_tensor =*/ true,
  4331. };
  4332. return result;
  4333. }
  4334. int llama_max_devices(void) {
  4335. return LLAMA_MAX_DEVICES;
  4336. }
  4337. bool llama_mmap_supported(void) {
  4338. return llama_mmap::SUPPORTED;
  4339. }
  4340. bool llama_mlock_supported(void) {
  4341. return llama_mlock::SUPPORTED;
  4342. }
  4343. void llama_backend_init(bool numa) {
  4344. ggml_time_init();
  4345. // needed to initialize f16 tables
  4346. {
  4347. struct ggml_init_params params = { 0, NULL, false };
  4348. struct ggml_context * ctx = ggml_init(params);
  4349. ggml_free(ctx);
  4350. }
  4351. if (numa) {
  4352. ggml_numa_init();
  4353. }
  4354. #ifdef GGML_USE_MPI
  4355. ggml_mpi_backend_init();
  4356. #endif
  4357. }
  4358. void llama_backend_free(void) {
  4359. #ifdef GGML_USE_MPI
  4360. ggml_mpi_backend_free();
  4361. #endif
  4362. }
  4363. int64_t llama_time_us(void) {
  4364. return ggml_time_us();
  4365. }
  4366. struct llama_model * llama_load_model_from_file(
  4367. const char * path_model,
  4368. struct llama_context_params params) {
  4369. ggml_time_init();
  4370. llama_model * model = new llama_model;
  4371. ggml_type memory_type = params.f16_kv ? GGML_TYPE_F16 : GGML_TYPE_F32;
  4372. unsigned cur_percentage = 0;
  4373. if (params.progress_callback == NULL) {
  4374. params.progress_callback_user_data = &cur_percentage;
  4375. params.progress_callback = [](float progress, void * ctx) {
  4376. unsigned * cur_percentage_p = (unsigned *) ctx;
  4377. unsigned percentage = (unsigned) (100 * progress);
  4378. while (percentage > *cur_percentage_p) {
  4379. *cur_percentage_p = percentage;
  4380. LLAMA_LOG_INFO(".");
  4381. if (percentage >= 100) {
  4382. LLAMA_LOG_INFO("\n");
  4383. }
  4384. }
  4385. };
  4386. }
  4387. if (!llama_model_load(path_model, *model, params.n_ctx, params.n_batch, params.n_gpu_layers,
  4388. params.main_gpu, params.tensor_split, params.mul_mat_q, params.rope_freq_base, params.rope_freq_scale,
  4389. params.low_vram, memory_type, params.use_mmap, params.use_mlock, params.vocab_only,
  4390. params.progress_callback, params.progress_callback_user_data)) {
  4391. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  4392. delete model;
  4393. return nullptr;
  4394. }
  4395. return model;
  4396. }
  4397. void llama_free_model(struct llama_model * model) {
  4398. delete model;
  4399. }
  4400. struct llama_context * llama_new_context_with_model(
  4401. struct llama_model * model,
  4402. struct llama_context_params params) {
  4403. if (!model) {
  4404. return nullptr;
  4405. }
  4406. llama_context * ctx = new llama_context(*model);
  4407. if (params.seed == LLAMA_DEFAULT_SEED) {
  4408. params.seed = time(NULL);
  4409. }
  4410. ctx->rng = std::mt19937(params.seed);
  4411. ctx->logits_all = params.logits_all;
  4412. ggml_type memory_type = params.f16_kv ? GGML_TYPE_F16 : GGML_TYPE_F32;
  4413. // reserve memory for context buffers
  4414. if (!params.vocab_only) {
  4415. if (!llama_kv_cache_init(ctx->model.hparams, ctx->kv_self, memory_type, ctx->model.hparams.n_ctx, params.n_gpu_layers)) {
  4416. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  4417. llama_free(ctx);
  4418. return nullptr;
  4419. }
  4420. {
  4421. const size_t memory_size = ggml_nbytes(ctx->kv_self.k) + ggml_nbytes(ctx->kv_self.v);
  4422. LLAMA_LOG_INFO("%s: kv self size = %7.2f MB\n", __func__, memory_size / 1024.0 / 1024.0);
  4423. }
  4424. const auto & hparams = ctx->model.hparams;
  4425. // resized during inference
  4426. if (params.logits_all) {
  4427. ctx->logits.reserve(hparams.n_ctx*hparams.n_vocab);
  4428. } else {
  4429. ctx->logits.reserve(hparams.n_vocab);
  4430. }
  4431. if (params.embedding){
  4432. ctx->embedding.resize(hparams.n_embd);
  4433. }
  4434. {
  4435. static const size_t tensor_alignment = 32;
  4436. // the compute buffer is used to store the tensor and graph structs, while the allocator buffer is used for the tensor data
  4437. ctx->buf_compute.resize(ggml_tensor_overhead()*GGML_MAX_NODES + ggml_graph_overhead());
  4438. // create measure allocator
  4439. ctx->alloc = ggml_allocr_new_measure(tensor_alignment);
  4440. // build worst-case graph
  4441. int n_tokens = std::min((int)hparams.n_ctx, params.n_batch);
  4442. int n_past = hparams.n_ctx - n_tokens;
  4443. llama_token token = llama_token_bos(ctx); // not actually used by llama_build_graph, but required to choose between token and embedding inputs graph
  4444. ggml_cgraph * gf = llama_build_graph(*ctx, &token, NULL, n_tokens, n_past);
  4445. #ifdef GGML_USE_METAL
  4446. if (params.n_gpu_layers > 0) {
  4447. ctx->ctx_metal = ggml_metal_init(1);
  4448. if (!ctx->ctx_metal) {
  4449. LLAMA_LOG_ERROR("%s: ggml_metal_init() failed\n", __func__);
  4450. llama_free(ctx);
  4451. return NULL;
  4452. }
  4453. ggml_metal_graph_find_concurrency(ctx->ctx_metal, gf, false);
  4454. ggml_allocr_set_parse_seq(ctx->alloc, ggml_metal_get_concur_list(ctx->ctx_metal), ggml_metal_if_optimized(ctx->ctx_metal));
  4455. }
  4456. #endif
  4457. // measure memory requirements for the graph
  4458. size_t alloc_size = ggml_allocr_alloc_graph(ctx->alloc, gf) + tensor_alignment;
  4459. LLAMA_LOG_INFO("%s: compute buffer total size = %7.2f MB\n", __func__, (ctx->buf_compute.size + alloc_size) / 1024.0 / 1024.0);
  4460. // recreate allocator with exact memory requirements
  4461. ggml_allocr_free(ctx->alloc);
  4462. ctx->buf_alloc.resize(alloc_size);
  4463. ctx->alloc = ggml_allocr_new(ctx->buf_alloc.data, ctx->buf_alloc.size, tensor_alignment);
  4464. #ifdef GGML_USE_METAL
  4465. if (ctx->ctx_metal) {
  4466. ggml_allocr_set_parse_seq(ctx->alloc, ggml_metal_get_concur_list(ctx->ctx_metal), ggml_metal_if_optimized(ctx->ctx_metal));
  4467. }
  4468. #endif
  4469. #ifdef GGML_USE_CUBLAS
  4470. if (params.low_vram) {
  4471. LLAMA_LOG_INFO("%s: not allocating a VRAM scratch buffer due to low VRAM option\n", __func__);
  4472. ggml_cuda_set_scratch_size(0); // disable scratch
  4473. } else {
  4474. ggml_cuda_set_scratch_size(alloc_size);
  4475. LLAMA_LOG_INFO("%s: VRAM scratch buffer: %.2f MB\n", __func__, alloc_size / 1024.0 / 1024.0);
  4476. }
  4477. #endif
  4478. }
  4479. }
  4480. #ifdef GGML_USE_METAL
  4481. if (params.n_gpu_layers > 0) {
  4482. // this allocates all Metal resources and memory buffers
  4483. void * data_ptr = NULL;
  4484. size_t data_size = 0;
  4485. if (params.use_mmap) {
  4486. data_ptr = ctx->model.mapping->addr;
  4487. data_size = ctx->model.mapping->size;
  4488. } else {
  4489. data_ptr = ggml_get_mem_buffer(ctx->model.ctx);
  4490. data_size = ggml_get_mem_size (ctx->model.ctx);
  4491. }
  4492. const size_t max_size = ggml_get_max_tensor_size(ctx->model.ctx);
  4493. LLAMA_LOG_INFO("%s: max tensor size = %8.2f MB\n", __func__, max_size/1024.0/1024.0);
  4494. #define LLAMA_METAL_CHECK_BUF(result) \
  4495. if (!(result)) { \
  4496. LLAMA_LOG_ERROR("%s: failed to add buffer\n", __func__); \
  4497. llama_free(ctx); \
  4498. return NULL; \
  4499. }
  4500. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "data", data_ptr, data_size, max_size));
  4501. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "eval", ctx->buf_compute.data, ctx->buf_compute.size, 0));
  4502. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "kv", ctx->kv_self.buf.data, ctx->kv_self.buf.size, 0));
  4503. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "alloc", ctx->buf_alloc.data, ctx->buf_alloc.size, 0));
  4504. #undef LLAMA_METAL_CHECK_BUF
  4505. }
  4506. #endif
  4507. #ifdef GGML_USE_MPI
  4508. ctx->ctx_mpi = ggml_mpi_init();
  4509. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  4510. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  4511. const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  4512. while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  4513. llama_backend_free();
  4514. exit(1);
  4515. }
  4516. #endif
  4517. return ctx;
  4518. }
  4519. struct llama_context * llama_init_from_file(
  4520. const char * path_model,
  4521. struct llama_context_params params) {
  4522. struct llama_model * model = llama_load_model_from_file(path_model, params);
  4523. if (!model) {
  4524. return nullptr;
  4525. }
  4526. struct llama_context * ctx = llama_new_context_with_model(model, params);
  4527. ctx->model_owner = true;
  4528. return ctx;
  4529. }
  4530. void llama_free(struct llama_context * ctx) {
  4531. delete ctx;
  4532. }
  4533. int llama_n_vocab(const struct llama_context * ctx) {
  4534. return ctx->model.vocab.id_to_token.size();
  4535. }
  4536. int llama_n_ctx(const struct llama_context * ctx) {
  4537. return ctx->model.hparams.n_ctx;
  4538. }
  4539. int llama_n_embd(const struct llama_context * ctx) {
  4540. return ctx->model.hparams.n_embd;
  4541. }
  4542. enum llama_vocab_type llama_vocab_type(const struct llama_context * ctx) {
  4543. return ctx->model.vocab.type;
  4544. }
  4545. int llama_model_n_vocab(const struct llama_model * model) {
  4546. return model->vocab.id_to_token.size();
  4547. }
  4548. int llama_model_n_ctx(const struct llama_model * model) {
  4549. return model->hparams.n_ctx;
  4550. }
  4551. int llama_model_n_embd(const struct llama_model * model) {
  4552. return model->hparams.n_embd;
  4553. }
  4554. int llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  4555. return snprintf(buf, buf_size, "%s %s %s",
  4556. model->name.c_str(),
  4557. llama_model_type_name(model->type),
  4558. llama_model_ftype_name(model->ftype).c_str());
  4559. }
  4560. uint64_t llama_model_size(const struct llama_model * model) {
  4561. uint64_t size = 0;
  4562. for (const auto & it : model->tensors_by_name) {
  4563. size += ggml_nbytes(it.second);
  4564. }
  4565. return size;
  4566. }
  4567. uint64_t llama_model_n_params(const struct llama_model * model) {
  4568. uint64_t nparams = 0;
  4569. for (const auto & it : model->tensors_by_name) {
  4570. nparams += ggml_nelements(it.second);
  4571. }
  4572. return nparams;
  4573. }
  4574. int llama_model_quantize(
  4575. const char * fname_inp,
  4576. const char * fname_out,
  4577. const llama_model_quantize_params * params) {
  4578. try {
  4579. llama_model_quantize_internal(fname_inp, fname_out, params);
  4580. return 0;
  4581. } catch (const std::exception & err) {
  4582. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  4583. return 1;
  4584. }
  4585. }
  4586. int llama_apply_lora_from_file(struct llama_context * ctx, const char * path_lora, const char * path_base_model, int n_threads) {
  4587. try {
  4588. return llama_apply_lora_from_file_internal(ctx->model, path_lora, path_base_model, n_threads);
  4589. } catch (const std::exception & err) {
  4590. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  4591. return 1;
  4592. }
  4593. }
  4594. int llama_model_apply_lora_from_file(const struct llama_model * model, const char * path_lora, const char * path_base_model, int n_threads) {
  4595. try {
  4596. return llama_apply_lora_from_file_internal(*model, path_lora, path_base_model, n_threads);
  4597. } catch (const std::exception & err) {
  4598. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  4599. return 1;
  4600. }
  4601. }
  4602. int llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  4603. return ctx->kv_self.n;
  4604. }
  4605. #define LLAMA_MAX_RNG_STATE (64*1024)
  4606. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  4607. if (seed == LLAMA_DEFAULT_SEED) {
  4608. seed = time(NULL);
  4609. }
  4610. ctx->rng.seed(seed);
  4611. }
  4612. // Returns the *maximum* size of the state
  4613. size_t llama_get_state_size(const struct llama_context * ctx) {
  4614. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  4615. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  4616. const size_t s_rng_size = sizeof(size_t);
  4617. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  4618. const size_t s_logits_capacity = sizeof(size_t);
  4619. const size_t s_logits_size = sizeof(size_t);
  4620. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  4621. const size_t s_embedding_size = sizeof(size_t);
  4622. const size_t s_embedding = ctx->embedding.size() * sizeof(float);
  4623. const size_t s_kv_size = sizeof(size_t);
  4624. const size_t s_kv_ntok = sizeof(int);
  4625. const size_t s_kv = ctx->kv_self.buf.size;
  4626. const size_t s_total = (
  4627. + s_rng_size
  4628. + s_rng
  4629. + s_logits_capacity
  4630. + s_logits_size
  4631. + s_logits
  4632. + s_embedding_size
  4633. + s_embedding
  4634. + s_kv_size
  4635. + s_kv_ntok
  4636. + s_kv
  4637. );
  4638. return s_total;
  4639. }
  4640. // llama_context_data
  4641. struct llama_data_context {
  4642. virtual void write(const void * src, size_t size) = 0;
  4643. virtual size_t get_size_written() = 0;
  4644. virtual ~llama_data_context() = default;
  4645. };
  4646. struct llama_data_buffer_context : llama_data_context {
  4647. uint8_t * ptr;
  4648. size_t size_written = 0;
  4649. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  4650. void write(const void * src, size_t size) override {
  4651. memcpy(ptr, src, size);
  4652. ptr += size;
  4653. size_written += size;
  4654. }
  4655. size_t get_size_written() override {
  4656. return size_written;
  4657. }
  4658. };
  4659. struct llama_data_file_context : llama_data_context {
  4660. llama_file * file;
  4661. size_t size_written = 0;
  4662. llama_data_file_context(llama_file * f) : file(f) {}
  4663. void write(const void * src, size_t size) override {
  4664. file->write_raw(src, size);
  4665. size_written += size;
  4666. }
  4667. size_t get_size_written() override {
  4668. return size_written;
  4669. }
  4670. };
  4671. /** copy state data into either a buffer or file depending on the passed in context
  4672. *
  4673. * file context:
  4674. * llama_file file("/path", "wb");
  4675. * llama_data_file_context data_ctx(&file);
  4676. * llama_copy_state_data(ctx, &data_ctx);
  4677. *
  4678. * buffer context:
  4679. * std::vector<uint8_t> buf(max_size, 0);
  4680. * llama_data_buffer_context data_ctx(&buf.data());
  4681. * llama_copy_state_data(ctx, &data_ctx);
  4682. *
  4683. */
  4684. void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  4685. // copy rng
  4686. {
  4687. std::stringstream rng_ss;
  4688. rng_ss << ctx->rng;
  4689. const size_t rng_size = rng_ss.str().size();
  4690. char rng_buf[LLAMA_MAX_RNG_STATE];
  4691. memset(&rng_buf[0], 0, LLAMA_MAX_RNG_STATE);
  4692. memcpy(&rng_buf[0], rng_ss.str().data(), rng_ss.str().size());
  4693. data_ctx->write(&rng_size, sizeof(rng_size));
  4694. data_ctx->write(&rng_buf[0], LLAMA_MAX_RNG_STATE);
  4695. }
  4696. // copy logits
  4697. {
  4698. const size_t logits_cap = ctx->logits.capacity();
  4699. const size_t logits_size = ctx->logits.size();
  4700. data_ctx->write(&logits_cap, sizeof(logits_cap));
  4701. data_ctx->write(&logits_size, sizeof(logits_size));
  4702. if (logits_size) {
  4703. data_ctx->write(ctx->logits.data(), logits_size * sizeof(float));
  4704. }
  4705. // If there is a gap between the size and the capacity, write padding
  4706. size_t padding_size = (logits_cap - logits_size) * sizeof(float);
  4707. if (padding_size > 0) {
  4708. std::vector<uint8_t> padding(padding_size, 0); // Create a buffer filled with zeros
  4709. data_ctx->write(padding.data(), padding_size);
  4710. }
  4711. }
  4712. // copy embeddings
  4713. {
  4714. const size_t embedding_size = ctx->embedding.size();
  4715. data_ctx->write(&embedding_size, sizeof(embedding_size));
  4716. if (embedding_size) {
  4717. data_ctx->write(ctx->embedding.data(), embedding_size * sizeof(float));
  4718. }
  4719. }
  4720. // copy kv cache
  4721. {
  4722. const auto & kv_self = ctx->kv_self;
  4723. const auto & hparams = ctx->model.hparams;
  4724. const int n_layer = hparams.n_layer;
  4725. const int n_embd = hparams.n_embd_gqa();
  4726. const int n_ctx = hparams.n_ctx;
  4727. const size_t kv_size = kv_self.buf.size;
  4728. const int kv_ntok = llama_get_kv_cache_token_count(ctx);
  4729. data_ctx->write(&kv_size, sizeof(kv_size));
  4730. data_ctx->write(&kv_ntok, sizeof(kv_ntok));
  4731. if (kv_size) {
  4732. const size_t elt_size = ggml_element_size(kv_self.k);
  4733. ggml_context * cpy_ctx = ggml_init({ 4096, NULL, /* no_alloc */ true });
  4734. ggml_cgraph gf{};
  4735. ggml_tensor * kout3d = ggml_new_tensor_3d(cpy_ctx, kv_self.k->type, n_embd, kv_ntok, n_layer);
  4736. std::vector<uint8_t> kout3d_data(ggml_nbytes(kout3d), 0);
  4737. kout3d->data = kout3d_data.data();
  4738. ggml_tensor * vout3d = ggml_new_tensor_3d(cpy_ctx, kv_self.v->type, kv_ntok, n_embd, n_layer);
  4739. std::vector<uint8_t> vout3d_data(ggml_nbytes(vout3d), 0);
  4740. vout3d->data = vout3d_data.data();
  4741. ggml_tensor * k3d = ggml_view_3d(cpy_ctx, kv_self.k,
  4742. n_embd, kv_ntok, n_layer,
  4743. elt_size*n_embd, elt_size*n_embd*n_ctx, 0);
  4744. ggml_tensor * v3d = ggml_view_3d(cpy_ctx, kv_self.v,
  4745. kv_ntok, n_embd, n_layer,
  4746. elt_size*n_ctx, elt_size*n_ctx*n_embd, 0);
  4747. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, k3d, kout3d));
  4748. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, v3d, vout3d));
  4749. ggml_graph_compute_helper(ctx->work_buffer, &gf, /*n_threads*/ 1);
  4750. ggml_free(cpy_ctx);
  4751. // our data is now in the kout3d_data and vout3d_data buffers
  4752. // write them to file
  4753. data_ctx->write(kout3d_data.data(), kout3d_data.size());
  4754. data_ctx->write(vout3d_data.data(), vout3d_data.size());
  4755. }
  4756. }
  4757. }
  4758. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  4759. llama_data_buffer_context data_ctx(dst);
  4760. llama_copy_state_data_internal(ctx, &data_ctx);
  4761. return data_ctx.get_size_written();
  4762. }
  4763. // Sets the state reading from the specified source address
  4764. size_t llama_set_state_data(struct llama_context * ctx, uint8_t * src) {
  4765. uint8_t * inp = src;
  4766. // set rng
  4767. {
  4768. size_t rng_size;
  4769. char rng_buf[LLAMA_MAX_RNG_STATE];
  4770. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  4771. memcpy(&rng_buf[0], inp, LLAMA_MAX_RNG_STATE); inp += LLAMA_MAX_RNG_STATE;
  4772. std::stringstream rng_ss;
  4773. rng_ss.str(std::string(&rng_buf[0], rng_size));
  4774. rng_ss >> ctx->rng;
  4775. GGML_ASSERT(rng_ss.fail() == false);
  4776. }
  4777. // set logits
  4778. {
  4779. size_t logits_cap;
  4780. size_t logits_size;
  4781. memcpy(&logits_cap, inp, sizeof(logits_cap)); inp += sizeof(logits_cap);
  4782. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  4783. GGML_ASSERT(ctx->logits.capacity() == logits_cap);
  4784. if (logits_size) {
  4785. ctx->logits.resize(logits_size);
  4786. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  4787. }
  4788. inp += logits_cap * sizeof(float);
  4789. }
  4790. // set embeddings
  4791. {
  4792. size_t embedding_size;
  4793. memcpy(&embedding_size, inp, sizeof(embedding_size)); inp += sizeof(embedding_size);
  4794. GGML_ASSERT(ctx->embedding.capacity() == embedding_size);
  4795. if (embedding_size) {
  4796. memcpy(ctx->embedding.data(), inp, embedding_size * sizeof(float));
  4797. inp += embedding_size * sizeof(float);
  4798. }
  4799. }
  4800. // set kv cache
  4801. {
  4802. const auto & kv_self = ctx->kv_self;
  4803. const auto & hparams = ctx->model.hparams;
  4804. const int n_layer = hparams.n_layer;
  4805. const int n_embd = hparams.n_embd_gqa();
  4806. const int n_ctx = hparams.n_ctx;
  4807. size_t kv_size;
  4808. int kv_ntok;
  4809. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  4810. memcpy(&kv_ntok, inp, sizeof(kv_ntok)); inp += sizeof(kv_ntok);
  4811. if (kv_size) {
  4812. GGML_ASSERT(kv_self.buf.size == kv_size);
  4813. const size_t elt_size = ggml_element_size(kv_self.k);
  4814. ggml_context * cpy_ctx = ggml_init({ 4096, NULL, /* no_alloc */ true });
  4815. ggml_cgraph gf{};
  4816. ggml_tensor * kin3d = ggml_new_tensor_3d(cpy_ctx, kv_self.k->type, n_embd, kv_ntok, n_layer);
  4817. kin3d->data = (void *) inp;
  4818. inp += ggml_nbytes(kin3d);
  4819. ggml_tensor * vin3d = ggml_new_tensor_3d(cpy_ctx, kv_self.v->type, kv_ntok, n_embd, n_layer);
  4820. vin3d->data = (void *) inp;
  4821. inp += ggml_nbytes(vin3d);
  4822. ggml_tensor * k3d = ggml_view_3d(cpy_ctx, kv_self.k,
  4823. n_embd, kv_ntok, n_layer,
  4824. elt_size*n_embd, elt_size*n_embd*n_ctx, 0);
  4825. ggml_tensor * v3d = ggml_view_3d(cpy_ctx, kv_self.v,
  4826. kv_ntok, n_embd, n_layer,
  4827. elt_size*n_ctx, elt_size*n_ctx*n_embd, 0);
  4828. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, kin3d, k3d));
  4829. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, vin3d, v3d));
  4830. ggml_graph_compute_helper(ctx->work_buffer, &gf, /*n_threads*/ 1);
  4831. ggml_free(cpy_ctx);
  4832. }
  4833. ctx->kv_self.n = kv_ntok;
  4834. }
  4835. const size_t nread = inp - src;
  4836. const size_t max_size = llama_get_state_size(ctx);
  4837. GGML_ASSERT(nread <= max_size);
  4838. return nread;
  4839. }
  4840. 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) {
  4841. llama_file file(path_session, "rb");
  4842. // sanity checks
  4843. {
  4844. const uint32_t magic = file.read_u32();
  4845. const uint32_t version = file.read_u32();
  4846. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  4847. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  4848. return false;
  4849. }
  4850. llama_hparams session_hparams;
  4851. file.read_raw(&session_hparams, sizeof(llama_hparams));
  4852. if (session_hparams != ctx->model.hparams) {
  4853. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  4854. return false;
  4855. }
  4856. }
  4857. // load the prompt
  4858. {
  4859. const uint32_t n_token_count = file.read_u32();
  4860. if (n_token_count > n_token_capacity) {
  4861. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  4862. return false;
  4863. }
  4864. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  4865. *n_token_count_out = n_token_count;
  4866. }
  4867. // restore the context state
  4868. {
  4869. const size_t n_state_size_cur = file.size - file.tell();
  4870. const size_t n_state_size_max = llama_get_state_size(ctx);
  4871. if (n_state_size_cur > n_state_size_max) {
  4872. 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);
  4873. return false;
  4874. }
  4875. std::vector<uint8_t> state_data(n_state_size_max);
  4876. file.read_raw(state_data.data(), n_state_size_cur);
  4877. llama_set_state_data(ctx, state_data.data());
  4878. }
  4879. return true;
  4880. }
  4881. 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) {
  4882. try {
  4883. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  4884. } catch (const std::exception & err) {
  4885. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  4886. return false;
  4887. }
  4888. }
  4889. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  4890. llama_file file(path_session, "wb");
  4891. file.write_u32(LLAMA_SESSION_MAGIC);
  4892. file.write_u32(LLAMA_SESSION_VERSION);
  4893. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  4894. // save the prompt
  4895. file.write_u32((uint32_t) n_token_count);
  4896. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  4897. // save the context state using stream saving
  4898. llama_data_file_context data_ctx(&file);
  4899. llama_copy_state_data_internal(ctx, &data_ctx);
  4900. return true;
  4901. }
  4902. int llama_eval(
  4903. struct llama_context * ctx,
  4904. const llama_token * tokens,
  4905. int n_tokens,
  4906. int n_past,
  4907. int n_threads) {
  4908. if (!llama_eval_internal(*ctx, tokens, nullptr, n_tokens, n_past, n_threads, nullptr)) {
  4909. LLAMA_LOG_ERROR("%s: failed to eval\n", __func__);
  4910. return 1;
  4911. }
  4912. // get a more accurate load time, upon first eval
  4913. // TODO: fix this
  4914. if (!ctx->has_evaluated_once) {
  4915. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  4916. ctx->has_evaluated_once = true;
  4917. }
  4918. return 0;
  4919. }
  4920. int llama_eval_embd(
  4921. struct llama_context * ctx,
  4922. const float * embd,
  4923. int n_tokens,
  4924. int n_past,
  4925. int n_threads) {
  4926. if (!llama_eval_internal(*ctx, nullptr, embd, n_tokens, n_past, n_threads, nullptr)) {
  4927. LLAMA_LOG_ERROR("%s: failed to eval\n", __func__);
  4928. return 1;
  4929. }
  4930. // get a more accurate load time, upon first eval
  4931. // TODO: fix this
  4932. if (!ctx->has_evaluated_once) {
  4933. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  4934. ctx->has_evaluated_once = true;
  4935. }
  4936. return 0;
  4937. }
  4938. int llama_eval_export(struct llama_context * ctx, const char * fname) {
  4939. const int n_batch = 1;
  4940. const int n_ctx = 512 - n_batch;
  4941. const std::vector<llama_token> tmp(n_batch, llama_token_bos(ctx));
  4942. if (!llama_eval_internal(*ctx, tmp.data(), nullptr, tmp.size(), n_ctx, 1, fname)) {
  4943. LLAMA_LOG_ERROR("%s: failed to eval\n", __func__);
  4944. return 1;
  4945. }
  4946. return 0;
  4947. }
  4948. float * llama_get_logits(struct llama_context * ctx) {
  4949. return ctx->logits.data();
  4950. }
  4951. float * llama_get_embeddings(struct llama_context * ctx) {
  4952. return ctx->embedding.data();
  4953. }
  4954. const char * llama_token_get_text(const struct llama_context * ctx, llama_token token) {
  4955. return ctx->model.vocab.id_to_token[token].text.c_str();
  4956. }
  4957. float llama_token_get_score(const struct llama_context * ctx, llama_token token) {
  4958. return ctx->model.vocab.id_to_token[token].score;
  4959. }
  4960. llama_token_type llama_token_get_type(const struct llama_context * ctx, llama_token token) {
  4961. return ctx->model.vocab.id_to_token[token].type;
  4962. }
  4963. llama_token llama_token_bos(const struct llama_context * ctx) {
  4964. return ctx->model.vocab.special_bos_id;
  4965. }
  4966. llama_token llama_token_eos(const struct llama_context * ctx) {
  4967. return ctx->model.vocab.special_eos_id;
  4968. }
  4969. llama_token llama_token_nl(const struct llama_context * ctx) {
  4970. return ctx->model.vocab.linefeed_id;
  4971. }
  4972. int llama_tokenize(
  4973. struct llama_context * ctx,
  4974. const char * text,
  4975. llama_token * tokens,
  4976. int n_max_tokens,
  4977. bool add_bos) {
  4978. return llama_tokenize_with_model(&ctx->model, text, tokens, n_max_tokens, add_bos);
  4979. }
  4980. int llama_tokenize_with_model(
  4981. const struct llama_model * model,
  4982. const char * text,
  4983. llama_token * tokens,
  4984. int n_max_tokens,
  4985. bool add_bos) {
  4986. auto escape = llama_vocab_get_type(model->vocab) == LLAMA_VOCAB_TYPE_SPM;
  4987. auto res = llama_tokenize_internal(model->vocab, text, add_bos, escape);
  4988. if (n_max_tokens < (int) res.size()) {
  4989. LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  4990. return -((int) res.size());
  4991. }
  4992. for (size_t i = 0; i < res.size(); i++) {
  4993. tokens[i] = res[i];
  4994. }
  4995. return res.size();
  4996. }
  4997. int llama_token_to_str(const struct llama_context * ctx, llama_token token, char * buf, int length) {
  4998. return llama_token_to_str_with_model(&ctx->model, token, buf, length);
  4999. }
  5000. // does not write null-terminator to str
  5001. int llama_token_to_str_with_model(const struct llama_model * model, llama_token token, char * buf, int length) {
  5002. if (0 <= token && token < llama_model_n_vocab(model)) {
  5003. if (llama_is_normal_token(model->vocab, token)) {
  5004. std::string result = model->vocab.id_to_token[token].text;
  5005. if (llama_vocab_get_type(model->vocab) == LLAMA_VOCAB_TYPE_SPM) {
  5006. llama_unescape_whitespace(result);
  5007. }
  5008. if (length < (int) result.length()) {
  5009. return -result.length();
  5010. }
  5011. memcpy(buf, result.c_str(), result.length());
  5012. return result.length();
  5013. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  5014. if (length < 3) {
  5015. return -3;
  5016. }
  5017. buf[0] = '\xe2';
  5018. buf[1] = '\x96';
  5019. buf[2] = '\x85';
  5020. return 3;
  5021. } else if (llama_is_control_token(model->vocab, token)) {
  5022. ;
  5023. } else if (llama_is_byte_token(model->vocab, token)) {
  5024. if (length < 1) {
  5025. return -1;
  5026. }
  5027. buf[0] = llama_token_to_byte(model->vocab, token);
  5028. return 1;
  5029. }
  5030. }
  5031. return 0;
  5032. }
  5033. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  5034. struct llama_timings result = {
  5035. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  5036. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  5037. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  5038. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  5039. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  5040. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  5041. /*.n_sample =*/ std::max(1, ctx->n_sample),
  5042. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  5043. /*.n_eval =*/ std::max(1, ctx->n_eval),
  5044. };
  5045. return result;
  5046. }
  5047. void llama_print_timings(struct llama_context * ctx) {
  5048. const llama_timings timings = llama_get_timings(ctx);
  5049. LLAMA_LOG_INFO("\n");
  5050. LLAMA_LOG_INFO("%s: load time = %8.2f ms\n", __func__, timings.t_load_ms);
  5051. LLAMA_LOG_INFO("%s: sample time = %8.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  5052. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  5053. LLAMA_LOG_INFO("%s: prompt eval time = %8.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  5054. __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);
  5055. LLAMA_LOG_INFO("%s: eval time = %8.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  5056. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  5057. LLAMA_LOG_INFO("%s: total time = %8.2f ms\n", __func__, (timings.t_end_ms - timings.t_start_ms));
  5058. }
  5059. void llama_reset_timings(struct llama_context * ctx) {
  5060. ctx->t_start_us = ggml_time_us();
  5061. ctx->t_sample_us = ctx->n_sample = 0;
  5062. ctx->t_eval_us = ctx->n_eval = 0;
  5063. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  5064. }
  5065. const char * llama_print_system_info(void) {
  5066. static std::string s;
  5067. s = "";
  5068. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  5069. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  5070. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  5071. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  5072. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  5073. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  5074. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  5075. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  5076. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  5077. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  5078. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  5079. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  5080. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  5081. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  5082. return s.c_str();
  5083. }
  5084. // For internal test use
  5085. const std::vector<std::pair<std::string, struct ggml_tensor *>>& llama_internal_get_tensor_map(struct llama_context * ctx) {
  5086. return ctx->model.tensors_by_name;
  5087. }
  5088. void llama_log_set(llama_log_callback log_callback, void * user_data) {
  5089. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  5090. g_state.log_callback_user_data = user_data;
  5091. }
  5092. #if defined(_MSC_VER) && !defined(vsnprintf)
  5093. #define vsnprintf _vsnprintf
  5094. #endif
  5095. static void llama_log_internal_v(llama_log_level level, const char * format, va_list args) {
  5096. va_list args_copy;
  5097. va_copy(args_copy, args);
  5098. char buffer[128];
  5099. int len = vsnprintf(buffer, 128, format, args);
  5100. if (len < 128) {
  5101. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  5102. } else {
  5103. char* buffer2 = new char[len+1];
  5104. vsnprintf(buffer2, len+1, format, args_copy);
  5105. buffer2[len] = 0;
  5106. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  5107. delete[] buffer2;
  5108. }
  5109. va_end(args_copy);
  5110. }
  5111. static void llama_log_internal(llama_log_level level, const char * format, ...) {
  5112. va_list args;
  5113. va_start(args, format);
  5114. llama_log_internal_v(level, format, args);
  5115. va_end(args);
  5116. }
  5117. static void llama_log_callback_default(llama_log_level level, const char * text, void * user_data) {
  5118. (void) level;
  5119. (void) user_data;
  5120. fputs(text, stderr);
  5121. fflush(stderr);
  5122. }