llama.cpp 223 KB

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