llama.cpp 227 KB

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