llama.cpp 226 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385
  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 (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  536. fprintf(stderr, "warning: posix_madvise(.., POSIX_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 (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  544. fprintf(stderr, "warning: posix_madvise(.., POSIX_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_byte_token(const llama_vocab & vocab, llama_token id) {
  2494. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  2495. }
  2496. static uint8_t llama_token_to_byte(const llama_vocab & vocab, llama_token id) {
  2497. GGML_ASSERT(llama_is_byte_token(vocab, id));
  2498. const auto& token_data = vocab.id_to_token.at(id);
  2499. auto buf = token_data.text.substr(3, 2);
  2500. return strtol(buf.c_str(), NULL, 16);
  2501. }
  2502. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  2503. char buf[7];
  2504. int result = snprintf(buf, sizeof(buf), "<0x%02X>", ch);
  2505. GGML_ASSERT(0 <= result && result < 7);
  2506. return vocab.token_to_id.at(buf);
  2507. }
  2508. static void llama_escape_whitespace(std::string & text) {
  2509. replace_all(text, " ", "\xe2\x96\x81");
  2510. }
  2511. static void llama_unescape_whitespace(std::string & word) {
  2512. replace_all(word, "\xe2\x96\x81", " ");
  2513. }
  2514. struct llm_symbol {
  2515. using index = int;
  2516. index prev;
  2517. index next;
  2518. const char * text;
  2519. size_t n;
  2520. };
  2521. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  2522. // SPM tokenizer
  2523. // original implementation:
  2524. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  2525. struct llm_bigram_spm {
  2526. struct comparator {
  2527. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  2528. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  2529. }
  2530. };
  2531. using queue_storage = std::vector<llm_bigram_spm>;
  2532. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  2533. llm_symbol::index left;
  2534. llm_symbol::index right;
  2535. float score;
  2536. size_t size;
  2537. };
  2538. struct llm_tokenizer_spm {
  2539. llm_tokenizer_spm(const llama_vocab & vocab): vocab(vocab) {}
  2540. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  2541. // split string into utf8 chars
  2542. int index = 0;
  2543. size_t offs = 0;
  2544. while (offs < text.size()) {
  2545. llm_symbol sym;
  2546. size_t len = utf8_len(text[offs]);
  2547. GGML_ASSERT(offs + len <= text.size());
  2548. sym.text = text.c_str() + offs;
  2549. sym.n = len;
  2550. offs += len;
  2551. sym.prev = index - 1;
  2552. sym.next = offs == text.size() ? -1 : index + 1;
  2553. index++;
  2554. symbols.emplace_back(sym);
  2555. }
  2556. // seed the work queue with all possible 2-character tokens.
  2557. for (size_t i = 1; i < symbols.size(); ++i) {
  2558. try_add_bigram(i - 1, i);
  2559. }
  2560. // keep substituting the highest frequency pairs for as long as we can.
  2561. while (!work_queue.empty()) {
  2562. auto bigram = work_queue.top();
  2563. work_queue.pop();
  2564. auto & left_sym = symbols[bigram.left];
  2565. auto & right_sym = symbols[bigram.right];
  2566. // if one of the symbols already got merged, skip it.
  2567. if (left_sym.n == 0 || right_sym.n == 0 ||
  2568. left_sym.n + right_sym.n != bigram.size) {
  2569. continue;
  2570. }
  2571. // merge the right sym into the left one
  2572. left_sym.n += right_sym.n;
  2573. right_sym.n = 0;
  2574. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  2575. // remove the right sym from the chain
  2576. left_sym.next = right_sym.next;
  2577. if (right_sym.next >= 0) {
  2578. symbols[right_sym.next].prev = bigram.left;
  2579. }
  2580. // find more substitutions
  2581. try_add_bigram(left_sym.prev, bigram.left);
  2582. try_add_bigram(bigram.left, left_sym.next);
  2583. }
  2584. for (int i = 0; i != -1; i = symbols[i].next) {
  2585. auto & symbol = symbols[i];
  2586. resegment(symbol, output);
  2587. }
  2588. }
  2589. private:
  2590. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  2591. auto text = std::string(symbol.text, symbol.n);
  2592. auto token = vocab.token_to_id.find(text);
  2593. // Do we need to support is_unused?
  2594. if (token != vocab.token_to_id.end()) {
  2595. output.push_back((*token).second);
  2596. return;
  2597. }
  2598. const auto p = rev_merge.find(text);
  2599. if (p == rev_merge.end()) {
  2600. // output any symbols that did not form tokens as bytes.
  2601. for (int j = 0; j < (int)symbol.n; ++j) {
  2602. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  2603. output.push_back(token_id);
  2604. }
  2605. return;
  2606. }
  2607. resegment(symbols[p->second.first], output);
  2608. resegment(symbols[p->second.second], output);
  2609. }
  2610. void try_add_bigram(int left, int right) {
  2611. if (left == -1 || right == -1) {
  2612. return;
  2613. }
  2614. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  2615. auto token = vocab.token_to_id.find(text);
  2616. if (token == vocab.token_to_id.end()) {
  2617. return;
  2618. }
  2619. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  2620. return;
  2621. }
  2622. const auto & tok_data = vocab.id_to_token[(*token).second];
  2623. llm_bigram_spm bigram;
  2624. bigram.left = left;
  2625. bigram.right = right;
  2626. bigram.score = tok_data.score;
  2627. bigram.size = text.size();
  2628. work_queue.push(bigram);
  2629. // Do we need to support is_unused?
  2630. rev_merge[text] = std::make_pair(left, right);
  2631. }
  2632. const llama_vocab & vocab;
  2633. std::vector<llm_symbol> symbols;
  2634. llm_bigram_spm::queue work_queue;
  2635. std::map<std::string, std::pair<int, int>> rev_merge;
  2636. };
  2637. // BPE tokenizer
  2638. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  2639. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  2640. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  2641. struct llm_bigram_bpe {
  2642. struct comparator {
  2643. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  2644. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  2645. }
  2646. };
  2647. using queue_storage = std::vector<llm_bigram_bpe>;
  2648. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  2649. llm_symbol::index left;
  2650. llm_symbol::index right;
  2651. std::string text;
  2652. int rank;
  2653. size_t size;
  2654. };
  2655. struct llm_tokenizer_bpe {
  2656. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  2657. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  2658. int final_prev_index = -1;
  2659. auto word_collection = bpe_gpt2_preprocess(text);
  2660. symbols_final.clear();
  2661. for (auto & word : word_collection) {
  2662. work_queue = llm_bigram_bpe::queue();
  2663. symbols.clear();
  2664. int index = 0;
  2665. size_t offset = 0;
  2666. while (offset < word.size()) {
  2667. llm_symbol sym;
  2668. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  2669. sym.text = word.c_str() + offset;
  2670. sym.n = 1;
  2671. sym.n = char_len;
  2672. offset += sym.n;
  2673. sym.prev = index - 1;
  2674. sym.next = offset == word.size() ? -1 : index + 1;
  2675. index++;
  2676. symbols.emplace_back(sym);
  2677. }
  2678. for (size_t i = 1; i < symbols.size(); ++i) {
  2679. add_new_bigram(i - 1, i);
  2680. }
  2681. // build token(s)
  2682. while (!work_queue.empty()) {
  2683. auto bigram = work_queue.top();
  2684. work_queue.pop();
  2685. auto & left_symbol = symbols[bigram.left];
  2686. auto & right_symbol = symbols[bigram.right];
  2687. if (left_symbol.n == 0 || right_symbol.n == 0) {
  2688. continue;
  2689. }
  2690. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  2691. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  2692. if (left_token + right_token != bigram.text) {
  2693. continue; // Skip this bigram if it's outdated
  2694. }
  2695. // merge the right sym into the left one
  2696. left_symbol.n += right_symbol.n;
  2697. right_symbol.n = 0;
  2698. // remove the right sym from the chain
  2699. left_symbol.next = right_symbol.next;
  2700. if (right_symbol.next >= 0) {
  2701. symbols[right_symbol.next].prev = bigram.left;
  2702. }
  2703. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  2704. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  2705. }
  2706. // add the fnished tokens to the final list keeping correct order for next and prev
  2707. for (auto & sym : symbols) {
  2708. if (sym.n > 0) {
  2709. sym.prev = final_prev_index;
  2710. sym.next = -1;
  2711. if (final_prev_index != -1) {
  2712. symbols_final[final_prev_index].next = symbols_final.size();
  2713. }
  2714. symbols_final.emplace_back(sym);
  2715. final_prev_index = symbols_final.size() - 1;
  2716. }
  2717. }
  2718. }
  2719. symbols = symbols_final;
  2720. if (!symbols.empty()) {
  2721. for (int i = 0; i != -1; i = symbols[i].next) {
  2722. auto & symbol = symbols[i];
  2723. if (symbol.n == 0) {
  2724. continue;
  2725. }
  2726. const std::string str = std::string(symbol.text, symbol.n);
  2727. const auto token = vocab.token_to_id.find(str);
  2728. if (token == vocab.token_to_id.end()) {
  2729. for (auto j = str.begin(); j != str.end(); ++j) {
  2730. std::string byte_str(1, *j);
  2731. auto token_multibyte = vocab.token_to_id.find(byte_str);
  2732. if (token_multibyte == vocab.token_to_id.end()) {
  2733. try {
  2734. llama_token token_byte = llama_byte_to_token(vocab, *j);
  2735. output.push_back(token_byte);
  2736. } catch (const std::out_of_range & err) {
  2737. fprintf(stderr,"ERROR: byte not found in vocab: '%s'\n", byte_str.c_str());
  2738. }
  2739. } else {
  2740. output.push_back((*token_multibyte).second);
  2741. }
  2742. }
  2743. } else {
  2744. output.push_back((*token).second);
  2745. }
  2746. }
  2747. }
  2748. }
  2749. private:
  2750. void add_new_bigram(int left, int right) {
  2751. if (left == -1 || right == -1) {
  2752. return;
  2753. }
  2754. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  2755. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  2756. int rank_found = -1;
  2757. rank_found = vocab.find_bpe_rank(left_token, right_token);
  2758. if (rank_found < 0) {
  2759. return;
  2760. }
  2761. llm_bigram_bpe bigram;
  2762. bigram.left = left;
  2763. bigram.right = right;
  2764. bigram.text = left_token + right_token;
  2765. bigram.size = left_token.size() + right_token.size();
  2766. bigram.rank = rank_found;
  2767. work_queue.push(bigram);
  2768. }
  2769. // probably not 100% correct
  2770. static std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  2771. std::vector<std::string> words;
  2772. // ref: https://github.com/openai/gpt-2/blob/a74da5d99abaaba920de8131d64da2862a8f213b/src/encoder.py#L53
  2773. const std::string pattern = R"('s|'t|'re|'ve|'m|'ll|'d| ?[[:alpha:]]+| ?[[:digit:]]+| ?[^\s[:alpha:][:digit:]]+|\s+(?!\S)|\s+)";
  2774. const std::regex re(pattern);
  2775. auto words_begin = std::sregex_iterator(text.begin(), text.end(), re);
  2776. auto words_end = std::sregex_iterator();
  2777. auto n_words = std::distance(words_begin, words_end);
  2778. words.reserve(n_words);
  2779. for (auto it = words_begin; it != words_end; ++it) {
  2780. words.push_back(it->str());
  2781. }
  2782. return words;
  2783. }
  2784. const llama_vocab & vocab;
  2785. std::vector<llm_symbol> symbols;
  2786. std::vector<llm_symbol> symbols_final;
  2787. llm_bigram_bpe::queue work_queue;
  2788. };
  2789. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos) {
  2790. std::vector<llama_vocab::id> output;
  2791. // OG tokenizer behavior:
  2792. //
  2793. // tokenizer.encode('', add_bos=True) returns [1]
  2794. // tokenizer.encode('', add_bos=False) returns []
  2795. if (bos && vocab.special_bos_id != -1) {
  2796. output.push_back(vocab.special_bos_id);
  2797. }
  2798. if (raw_text.empty()) {
  2799. return output;
  2800. }
  2801. switch (vocab.type) {
  2802. case LLAMA_VOCAB_TYPE_SPM:
  2803. {
  2804. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  2805. raw_text = " " + raw_text;
  2806. llm_tokenizer_spm tokenizer(vocab);
  2807. llama_escape_whitespace(raw_text);
  2808. tokenizer.tokenize(raw_text, output);
  2809. } break;
  2810. case LLAMA_VOCAB_TYPE_BPE:
  2811. {
  2812. llm_tokenizer_bpe tokenizer(vocab);
  2813. tokenizer.tokenize(raw_text, output);
  2814. } break;
  2815. };
  2816. return output;
  2817. }
  2818. //
  2819. // grammar - internal
  2820. //
  2821. struct llama_partial_utf8 {
  2822. uint32_t value; // bit value so far (unshifted)
  2823. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  2824. };
  2825. struct llama_grammar {
  2826. const std::vector<std::vector<llama_grammar_element>> rules;
  2827. std::vector<std::vector<const llama_grammar_element *>> stacks;
  2828. // buffer for partially generated UTF-8 sequence from accepted tokens
  2829. llama_partial_utf8 partial_utf8;
  2830. };
  2831. struct llama_grammar_candidate {
  2832. size_t index;
  2833. const uint32_t * code_points;
  2834. llama_partial_utf8 partial_utf8;
  2835. };
  2836. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  2837. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  2838. std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  2839. const char * src,
  2840. llama_partial_utf8 partial_start) {
  2841. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  2842. const char * pos = src;
  2843. std::vector<uint32_t> code_points;
  2844. uint32_t value = partial_start.value;
  2845. int n_remain = partial_start.n_remain;
  2846. // continue previous decode, if applicable
  2847. while (*pos != 0 && n_remain > 0) {
  2848. uint8_t next_byte = static_cast<uint8_t>(*pos);
  2849. if ((next_byte >> 6) != 2) {
  2850. // invalid sequence, abort
  2851. code_points.push_back(0);
  2852. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  2853. }
  2854. value = (value << 6) + (next_byte & 0x3F);
  2855. ++pos;
  2856. --n_remain;
  2857. }
  2858. if (partial_start.n_remain > 0 && n_remain == 0) {
  2859. code_points.push_back(value);
  2860. }
  2861. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  2862. while (*pos != 0) {
  2863. uint8_t first_byte = static_cast<uint8_t>(*pos);
  2864. uint8_t highbits = first_byte >> 4;
  2865. n_remain = lookup[highbits] - 1;
  2866. if (n_remain < 0) {
  2867. // invalid sequence, abort
  2868. code_points.clear();
  2869. code_points.push_back(0);
  2870. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  2871. }
  2872. uint8_t mask = (1 << (7 - n_remain)) - 1;
  2873. value = first_byte & mask;
  2874. ++pos;
  2875. while (*pos != 0 && n_remain > 0) {
  2876. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  2877. ++pos;
  2878. --n_remain;
  2879. }
  2880. if (n_remain == 0) {
  2881. code_points.push_back(value);
  2882. }
  2883. }
  2884. code_points.push_back(0);
  2885. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  2886. }
  2887. // returns true iff pos points to the end of one of the definitions of a rule
  2888. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  2889. switch (pos->type) {
  2890. case LLAMA_GRETYPE_END: return true; // NOLINT
  2891. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  2892. default: return false;
  2893. }
  2894. }
  2895. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  2896. // asserts that pos is pointing to a char range element
  2897. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  2898. const llama_grammar_element * pos,
  2899. const uint32_t chr) {
  2900. bool found = false;
  2901. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  2902. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  2903. do {
  2904. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  2905. // inclusive range, e.g. [a-z]
  2906. found = found || (pos->value <= chr && chr <= pos[1].value);
  2907. pos += 2;
  2908. } else {
  2909. // exact char match, e.g. [a] or "a"
  2910. found = found || pos->value == chr;
  2911. pos += 1;
  2912. }
  2913. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  2914. return std::make_pair(found == is_positive_char, pos);
  2915. }
  2916. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  2917. // range at pos (regular or inverse range)
  2918. // asserts that pos is pointing to a char range element
  2919. static bool llama_grammar_match_partial_char(
  2920. const llama_grammar_element * pos,
  2921. const llama_partial_utf8 partial_utf8) {
  2922. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  2923. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  2924. uint32_t partial_value = partial_utf8.value;
  2925. int n_remain = partial_utf8.n_remain;
  2926. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  2927. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  2928. return false;
  2929. }
  2930. // range of possible code points this partial UTF-8 sequence could complete to
  2931. uint32_t low = partial_value << (n_remain * 6);
  2932. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  2933. if (low == 0) {
  2934. if (n_remain == 2) {
  2935. low = 1 << 11;
  2936. } else if (n_remain == 3) {
  2937. low = 1 << 16;
  2938. }
  2939. }
  2940. do {
  2941. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  2942. // inclusive range, e.g. [a-z]
  2943. if (pos->value <= high && low <= pos[1].value) {
  2944. return is_positive_char;
  2945. }
  2946. pos += 2;
  2947. } else {
  2948. // exact char match, e.g. [a] or "a"
  2949. if (low <= pos->value && pos->value <= high) {
  2950. return is_positive_char;
  2951. }
  2952. pos += 1;
  2953. }
  2954. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  2955. return !is_positive_char;
  2956. }
  2957. // transforms a grammar pushdown stack into N possible stacks, all ending
  2958. // at a character range (terminal element)
  2959. static void llama_grammar_advance_stack(
  2960. const std::vector<std::vector<llama_grammar_element>> & rules,
  2961. const std::vector<const llama_grammar_element *> & stack,
  2962. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  2963. if (stack.empty()) {
  2964. new_stacks.emplace_back(stack);
  2965. return;
  2966. }
  2967. const llama_grammar_element * pos = stack.back();
  2968. switch (pos->type) {
  2969. case LLAMA_GRETYPE_RULE_REF: {
  2970. const size_t rule_id = static_cast<size_t>(pos->value);
  2971. const llama_grammar_element * subpos = rules[rule_id].data();
  2972. do {
  2973. // init new stack without the top (pos)
  2974. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  2975. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  2976. // if this rule ref is followed by another element, add that to stack
  2977. new_stack.push_back(pos + 1);
  2978. }
  2979. if (!llama_grammar_is_end_of_sequence(subpos)) {
  2980. // if alternate is nonempty, add to stack
  2981. new_stack.push_back(subpos);
  2982. }
  2983. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  2984. while (!llama_grammar_is_end_of_sequence(subpos)) {
  2985. // scan to end of alternate def
  2986. subpos++;
  2987. }
  2988. if (subpos->type == LLAMA_GRETYPE_ALT) {
  2989. // there's another alternate def of this rule to process
  2990. subpos++;
  2991. } else {
  2992. break;
  2993. }
  2994. } while (true);
  2995. break;
  2996. }
  2997. case LLAMA_GRETYPE_CHAR:
  2998. case LLAMA_GRETYPE_CHAR_NOT:
  2999. new_stacks.emplace_back(stack);
  3000. break;
  3001. default:
  3002. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  3003. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  3004. // those
  3005. GGML_ASSERT(false);
  3006. }
  3007. }
  3008. // takes a set of possible pushdown stacks on a grammar, which are required to
  3009. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  3010. // produces the N possible stacks if the given char is accepted at those
  3011. // positions
  3012. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  3013. const std::vector<std::vector<llama_grammar_element>> & rules,
  3014. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  3015. const uint32_t chr) {
  3016. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  3017. for (const auto & stack : stacks) {
  3018. if (stack.empty()) {
  3019. continue;
  3020. }
  3021. auto match = llama_grammar_match_char(stack.back(), chr);
  3022. if (match.first) {
  3023. const llama_grammar_element * pos = match.second;
  3024. // update top of stack to next element, if any
  3025. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  3026. if (!llama_grammar_is_end_of_sequence(pos)) {
  3027. new_stack.push_back(pos);
  3028. }
  3029. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  3030. }
  3031. }
  3032. return new_stacks;
  3033. }
  3034. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  3035. const std::vector<std::vector<llama_grammar_element>> & rules,
  3036. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  3037. const std::vector<llama_grammar_candidate> & candidates);
  3038. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  3039. const std::vector<std::vector<llama_grammar_element>> & rules,
  3040. const std::vector<const llama_grammar_element *> & stack,
  3041. const std::vector<llama_grammar_candidate> & candidates) {
  3042. std::vector<llama_grammar_candidate> rejects;
  3043. if (stack.empty()) {
  3044. for (auto tok : candidates) {
  3045. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  3046. rejects.push_back(tok);
  3047. }
  3048. }
  3049. return rejects;
  3050. }
  3051. const llama_grammar_element * stack_pos = stack.back();
  3052. std::vector<llama_grammar_candidate> next_candidates;
  3053. for (auto tok : candidates) {
  3054. if (*tok.code_points == 0) {
  3055. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  3056. // that cannot satisfy this position in grammar
  3057. if (tok.partial_utf8.n_remain != 0 &&
  3058. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  3059. rejects.push_back(tok);
  3060. }
  3061. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  3062. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  3063. } else {
  3064. rejects.push_back(tok);
  3065. }
  3066. }
  3067. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  3068. // update top of stack to next element, if any
  3069. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  3070. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  3071. stack_after.push_back(stack_pos_after);
  3072. }
  3073. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  3074. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  3075. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  3076. for (auto tok : next_rejects) {
  3077. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  3078. }
  3079. return rejects;
  3080. }
  3081. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  3082. const std::vector<std::vector<llama_grammar_element>> & rules,
  3083. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  3084. const std::vector<llama_grammar_candidate> & candidates) {
  3085. GGML_ASSERT(!stacks.empty()); // REVIEW
  3086. if (candidates.empty()) {
  3087. return std::vector<llama_grammar_candidate>();
  3088. }
  3089. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  3090. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  3091. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  3092. }
  3093. return rejects;
  3094. }
  3095. //
  3096. // grammar - external
  3097. //
  3098. struct llama_grammar * llama_grammar_init(
  3099. const llama_grammar_element ** rules,
  3100. size_t n_rules,
  3101. size_t start_rule_index) {
  3102. const llama_grammar_element * pos;
  3103. // copy rule definitions into vectors
  3104. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  3105. for (size_t i = 0; i < n_rules; i++) {
  3106. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  3107. vec_rules[i].push_back(*pos);
  3108. }
  3109. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  3110. }
  3111. // loop over alternates of start rule to build initial stacks
  3112. std::vector<std::vector<const llama_grammar_element *>> stacks;
  3113. pos = rules[start_rule_index];
  3114. do {
  3115. std::vector<const llama_grammar_element *> stack;
  3116. if (!llama_grammar_is_end_of_sequence(pos)) {
  3117. // if alternate is nonempty, add to stack
  3118. stack.push_back(pos);
  3119. }
  3120. llama_grammar_advance_stack(vec_rules, stack, stacks);
  3121. while (!llama_grammar_is_end_of_sequence(pos)) {
  3122. // scan to end of alternate def
  3123. pos++;
  3124. }
  3125. if (pos->type == LLAMA_GRETYPE_ALT) {
  3126. // there's another alternate def of this rule to process
  3127. pos++;
  3128. } else {
  3129. break;
  3130. }
  3131. } while (true);
  3132. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  3133. }
  3134. void llama_grammar_free(struct llama_grammar * grammar) {
  3135. delete grammar;
  3136. }
  3137. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  3138. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  3139. // redirect elements in stacks to point to new rules
  3140. for (size_t is = 0; is < result->stacks.size(); is++) {
  3141. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  3142. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  3143. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  3144. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  3145. result->stacks[is][ie] = &result->rules[ir0][ir1];
  3146. }
  3147. }
  3148. }
  3149. }
  3150. }
  3151. return result;
  3152. }
  3153. //
  3154. // sampling
  3155. //
  3156. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  3157. GGML_ASSERT(candidates->size > 0);
  3158. const int64_t t_start_sample_us = ggml_time_us();
  3159. // Sort the logits in descending order
  3160. if (!candidates->sorted) {
  3161. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  3162. return a.logit > b.logit;
  3163. });
  3164. candidates->sorted = true;
  3165. }
  3166. float max_l = candidates->data[0].logit;
  3167. float cum_sum = 0.0f;
  3168. for (size_t i = 0; i < candidates->size; ++i) {
  3169. float p = expf(candidates->data[i].logit - max_l);
  3170. candidates->data[i].p = p;
  3171. cum_sum += p;
  3172. }
  3173. for (size_t i = 0; i < candidates->size; ++i) {
  3174. candidates->data[i].p /= cum_sum;
  3175. }
  3176. if (ctx) {
  3177. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3178. }
  3179. }
  3180. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int k, size_t min_keep) {
  3181. const int64_t t_start_sample_us = ggml_time_us();
  3182. k = std::max(k, (int) min_keep);
  3183. k = std::min(k, (int) candidates->size);
  3184. // Sort scores in descending order
  3185. if (!candidates->sorted) {
  3186. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  3187. return a.logit > b.logit;
  3188. };
  3189. if (k == (int) candidates->size) {
  3190. std::sort(candidates->data, candidates->data + candidates->size, comp);
  3191. } else {
  3192. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  3193. }
  3194. candidates->sorted = true;
  3195. }
  3196. candidates->size = k;
  3197. if (ctx) {
  3198. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3199. }
  3200. }
  3201. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  3202. if (p >= 1.0f) {
  3203. return;
  3204. }
  3205. llama_sample_softmax(ctx, candidates);
  3206. const int64_t t_start_sample_us = ggml_time_us();
  3207. // Compute the cumulative probabilities
  3208. float cum_sum = 0.0f;
  3209. size_t last_idx = candidates->size;
  3210. for (size_t i = 0; i < candidates->size; ++i) {
  3211. cum_sum += candidates->data[i].p;
  3212. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  3213. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  3214. if (cum_sum >= p && i + 1 >= min_keep) {
  3215. last_idx = i + 1;
  3216. break;
  3217. }
  3218. }
  3219. // Resize the output vector to keep only the top-p tokens
  3220. candidates->size = last_idx;
  3221. if (ctx) {
  3222. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3223. }
  3224. }
  3225. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  3226. if (z >= 1.0f || candidates->size <= 2) {
  3227. return;
  3228. }
  3229. llama_sample_softmax(nullptr, candidates);
  3230. const int64_t t_start_sample_us = ggml_time_us();
  3231. // Compute the first and second derivatives
  3232. std::vector<float> first_derivatives(candidates->size - 1);
  3233. std::vector<float> second_derivatives(candidates->size - 2);
  3234. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  3235. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  3236. }
  3237. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  3238. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  3239. }
  3240. // Calculate absolute value of second derivatives
  3241. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  3242. second_derivatives[i] = std::abs(second_derivatives[i]);
  3243. }
  3244. // Normalize the second derivatives
  3245. {
  3246. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  3247. if (second_derivatives_sum > 1e-6f) {
  3248. for (float & value : second_derivatives) {
  3249. value /= second_derivatives_sum;
  3250. }
  3251. } else {
  3252. for (float & value : second_derivatives) {
  3253. value = 1.0f / second_derivatives.size();
  3254. }
  3255. }
  3256. }
  3257. float cum_sum = 0.0f;
  3258. size_t last_idx = candidates->size;
  3259. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  3260. cum_sum += second_derivatives[i];
  3261. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  3262. if (cum_sum > z && i >= min_keep) {
  3263. last_idx = i;
  3264. break;
  3265. }
  3266. }
  3267. // Resize the output vector to keep only the tokens above the tail location
  3268. candidates->size = last_idx;
  3269. if (ctx) {
  3270. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3271. }
  3272. }
  3273. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  3274. // Reference implementation:
  3275. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  3276. if (p >= 1.0f) {
  3277. return;
  3278. }
  3279. // Compute the softmax of logits and calculate entropy
  3280. llama_sample_softmax(nullptr, candidates);
  3281. const int64_t t_start_sample_us = ggml_time_us();
  3282. float entropy = 0.0f;
  3283. for (size_t i = 0; i < candidates->size; ++i) {
  3284. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  3285. }
  3286. // Compute the absolute difference between negative log probability and entropy for each candidate
  3287. std::vector<float> shifted_scores;
  3288. for (size_t i = 0; i < candidates->size; ++i) {
  3289. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  3290. shifted_scores.push_back(shifted_score);
  3291. }
  3292. // Sort tokens based on the shifted_scores and their corresponding indices
  3293. std::vector<size_t> indices(candidates->size);
  3294. std::iota(indices.begin(), indices.end(), 0);
  3295. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  3296. return shifted_scores[a] < shifted_scores[b];
  3297. });
  3298. // Compute the cumulative probabilities
  3299. float cum_sum = 0.0f;
  3300. size_t last_idx = indices.size();
  3301. for (size_t i = 0; i < indices.size(); ++i) {
  3302. size_t idx = indices[i];
  3303. cum_sum += candidates->data[idx].p;
  3304. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  3305. if (cum_sum > p && i >= min_keep - 1) {
  3306. last_idx = i + 1;
  3307. break;
  3308. }
  3309. }
  3310. // Resize the output vector to keep only the locally typical tokens
  3311. std::vector<llama_token_data> new_candidates;
  3312. for (size_t i = 0; i < last_idx; ++i) {
  3313. size_t idx = indices[i];
  3314. new_candidates.push_back(candidates->data[idx]);
  3315. }
  3316. // Replace the data in candidates with the new_candidates data
  3317. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  3318. candidates->size = new_candidates.size();
  3319. if (ctx) {
  3320. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3321. }
  3322. }
  3323. void llama_sample_temperature(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  3324. const int64_t t_start_sample_us = ggml_time_us();
  3325. for (size_t i = 0; i < candidates_p->size; ++i) {
  3326. candidates_p->data[i].logit /= temp;
  3327. }
  3328. if (ctx) {
  3329. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3330. }
  3331. }
  3332. 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) {
  3333. if (last_tokens_size == 0 || penalty == 1.0f) {
  3334. return;
  3335. }
  3336. const int64_t t_start_sample_us = ggml_time_us();
  3337. for (size_t i = 0; i < candidates->size; ++i) {
  3338. const auto * token_iter = std::find(last_tokens, last_tokens + last_tokens_size, candidates->data[i].id);
  3339. if (token_iter == last_tokens + last_tokens_size) {
  3340. continue;
  3341. }
  3342. // 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.
  3343. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  3344. if (candidates->data[i].logit <= 0) {
  3345. candidates->data[i].logit *= penalty;
  3346. } else {
  3347. candidates->data[i].logit /= penalty;
  3348. }
  3349. }
  3350. candidates->sorted = false;
  3351. if (ctx) {
  3352. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3353. }
  3354. }
  3355. 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) {
  3356. if (last_tokens_size == 0 || (alpha_frequency == 0.0f && alpha_presence == 0.0f)) {
  3357. return;
  3358. }
  3359. const int64_t t_start_sample_us = ggml_time_us();
  3360. // Create a frequency map to count occurrences of each token in last_tokens
  3361. std::unordered_map<llama_token, int> token_count;
  3362. for (size_t i = 0; i < last_tokens_size; ++i) {
  3363. token_count[last_tokens_p[i]]++;
  3364. }
  3365. // Apply frequency and presence penalties to the candidates
  3366. for (size_t i = 0; i < candidates->size; ++i) {
  3367. auto token_iter = token_count.find(candidates->data[i].id);
  3368. if (token_iter == token_count.end()) {
  3369. continue;
  3370. }
  3371. int count = token_iter->second;
  3372. candidates->data[i].logit -= float(count) * alpha_frequency + float(count > 0) * alpha_presence;
  3373. }
  3374. candidates->sorted = false;
  3375. if (ctx) {
  3376. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3377. }
  3378. }
  3379. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  3380. GGML_ASSERT(ctx);
  3381. const int64_t t_start_sample_us = ggml_time_us();
  3382. bool allow_eos = false;
  3383. for (const auto & stack : grammar->stacks) {
  3384. if (stack.empty()) {
  3385. allow_eos = true;
  3386. break;
  3387. }
  3388. }
  3389. const llama_token eos = llama_token_eos(ctx);
  3390. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  3391. std::vector<llama_grammar_candidate> candidates_grammar;
  3392. for (size_t i = 0; i < candidates->size; ++i) {
  3393. const llama_token id = candidates->data[i].id;
  3394. const std::string piece = llama_token_to_str(ctx, id);
  3395. if (id == eos) {
  3396. if (!allow_eos) {
  3397. candidates->data[i].logit = -INFINITY;
  3398. }
  3399. } else if (piece.empty() || piece[0] == 0) {
  3400. candidates->data[i].logit = -INFINITY;
  3401. } else {
  3402. candidates_decoded.push_back(decode_utf8(piece.c_str(), grammar->partial_utf8));
  3403. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  3404. }
  3405. }
  3406. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  3407. for (const auto & reject : rejects) {
  3408. candidates->data[reject.index].logit = -INFINITY;
  3409. }
  3410. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3411. }
  3412. static void llama_log_softmax(float * array, size_t size) {
  3413. float max_l = *std::max_element(array, array + size);
  3414. float sum = 0.f;
  3415. for (size_t i = 0; i < size; ++i) {
  3416. float p = expf(array[i] - max_l);
  3417. sum += p;
  3418. array[i] = p;
  3419. }
  3420. for (size_t i = 0; i < size; ++i) {
  3421. array[i] = logf(array[i] / sum);
  3422. }
  3423. }
  3424. void llama_sample_classifier_free_guidance(
  3425. struct llama_context * ctx,
  3426. llama_token_data_array * candidates,
  3427. struct llama_context * guidance_ctx,
  3428. float scale) {
  3429. int64_t t_start_sample_us = ggml_time_us();
  3430. GGML_ASSERT(ctx);
  3431. auto n_vocab = llama_n_vocab(ctx);
  3432. GGML_ASSERT(n_vocab == (int)candidates->size);
  3433. GGML_ASSERT(!candidates->sorted);
  3434. std::vector<float> logits_base;
  3435. logits_base.reserve(candidates->size);
  3436. for (size_t i = 0; i < candidates->size; ++i) {
  3437. logits_base.push_back(candidates->data[i].logit);
  3438. }
  3439. llama_log_softmax(logits_base.data(), candidates->size);
  3440. float* logits_guidance = llama_get_logits(guidance_ctx);
  3441. llama_log_softmax(logits_guidance, n_vocab);
  3442. for (int i = 0; i < n_vocab; ++i) {
  3443. float logit_guidance = logits_guidance[i];
  3444. float logit_base = logits_base[i];
  3445. candidates->data[i].logit = scale * (logit_base - logit_guidance) + logit_guidance;
  3446. }
  3447. if (ctx) {
  3448. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3449. }
  3450. }
  3451. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int m, float * mu) {
  3452. GGML_ASSERT(ctx);
  3453. auto N = float(llama_n_vocab(ctx));
  3454. int64_t t_start_sample_us;
  3455. t_start_sample_us = ggml_time_us();
  3456. llama_sample_softmax(nullptr, candidates);
  3457. // Estimate s_hat using the most probable m tokens
  3458. float s_hat = 0.0;
  3459. float sum_ti_bi = 0.0;
  3460. float sum_ti_sq = 0.0;
  3461. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  3462. float t_i = logf(float(i + 2) / float(i + 1));
  3463. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  3464. sum_ti_bi += t_i * b_i;
  3465. sum_ti_sq += t_i * t_i;
  3466. }
  3467. s_hat = sum_ti_bi / sum_ti_sq;
  3468. // Compute k from the estimated s_hat and target surprise value
  3469. float epsilon_hat = s_hat - 1;
  3470. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  3471. // Sample the next word X using top-k sampling
  3472. llama_sample_top_k(nullptr, candidates, int(k), 1);
  3473. if (ctx) {
  3474. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3475. }
  3476. llama_token X = llama_sample_token(ctx, candidates);
  3477. t_start_sample_us = ggml_time_us();
  3478. // Compute error as the difference between observed surprise and target surprise value
  3479. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  3480. return candidate.id == X;
  3481. }));
  3482. float observed_surprise = -log2f(candidates->data[X_idx].p);
  3483. float e = observed_surprise - tau;
  3484. // Update mu using the learning rate and error
  3485. *mu = *mu - eta * e;
  3486. if (ctx) {
  3487. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3488. }
  3489. return X;
  3490. }
  3491. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  3492. int64_t t_start_sample_us;
  3493. t_start_sample_us = ggml_time_us();
  3494. llama_sample_softmax(ctx, candidates);
  3495. // Truncate the words with surprise values greater than mu
  3496. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  3497. return -log2f(candidate.p) > *mu;
  3498. }));
  3499. if (candidates->size == 0) {
  3500. candidates->size = 1;
  3501. }
  3502. if (ctx) {
  3503. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3504. }
  3505. // Normalize the probabilities of the remaining words
  3506. llama_sample_softmax(ctx, candidates);
  3507. // Sample the next word X from the remaining words
  3508. llama_token X = llama_sample_token(ctx, candidates);
  3509. t_start_sample_us = ggml_time_us();
  3510. // Compute error as the difference between observed surprise and target surprise value
  3511. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  3512. return candidate.id == X;
  3513. }));
  3514. float observed_surprise = -log2f(candidates->data[X_idx].p);
  3515. float e = observed_surprise - tau;
  3516. // Update mu using the learning rate and error
  3517. *mu = *mu - eta * e;
  3518. if (ctx) {
  3519. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3520. }
  3521. return X;
  3522. }
  3523. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  3524. const int64_t t_start_sample_us = ggml_time_us();
  3525. // Find max element
  3526. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  3527. return a.logit < b.logit;
  3528. });
  3529. llama_token result = max_iter->id;
  3530. if (ctx) {
  3531. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3532. ctx->n_sample++;
  3533. }
  3534. return result;
  3535. }
  3536. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  3537. GGML_ASSERT(ctx);
  3538. const int64_t t_start_sample_us = ggml_time_us();
  3539. llama_sample_softmax(nullptr, candidates);
  3540. std::vector<float> probs;
  3541. probs.reserve(candidates->size);
  3542. for (size_t i = 0; i < candidates->size; ++i) {
  3543. probs.push_back(candidates->data[i].p);
  3544. }
  3545. std::discrete_distribution<> dist(probs.begin(), probs.end());
  3546. auto & rng = ctx->rng;
  3547. int idx = dist(rng);
  3548. llama_token result = candidates->data[idx].id;
  3549. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3550. ctx->n_sample++;
  3551. return result;
  3552. }
  3553. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  3554. const int64_t t_start_sample_us = ggml_time_us();
  3555. if (token == llama_token_eos(ctx)) {
  3556. for (const auto & stack : grammar->stacks) {
  3557. if (stack.empty()) {
  3558. return;
  3559. }
  3560. }
  3561. GGML_ASSERT(false);
  3562. }
  3563. const std::string piece = llama_token_to_str(ctx, token);
  3564. // Note terminating 0 in decoded string
  3565. const auto decoded = decode_utf8(piece.c_str(), grammar->partial_utf8);
  3566. const auto & code_points = decoded.first;
  3567. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  3568. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  3569. }
  3570. grammar->partial_utf8 = decoded.second;
  3571. GGML_ASSERT(!grammar->stacks.empty());
  3572. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3573. }
  3574. //
  3575. // Beam search
  3576. //
  3577. struct llama_beam {
  3578. std::vector<llama_token> tokens;
  3579. float p; // Cumulative beam probability (renormalized relative to all beams)
  3580. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  3581. // Sort beams by probability. In case of ties, prefer beams at eob.
  3582. bool operator<(const llama_beam & rhs) const {
  3583. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  3584. }
  3585. // Shift off first n tokens and discard them.
  3586. void shift_tokens(const size_t n) {
  3587. if (n) {
  3588. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  3589. tokens.resize(tokens.size() - n);
  3590. }
  3591. }
  3592. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  3593. };
  3594. // A struct for calculating logit-related info.
  3595. struct llama_logit_info {
  3596. const float * const logits;
  3597. const int n_vocab;
  3598. const float max_l;
  3599. const float normalizer;
  3600. struct sum_exp {
  3601. float max_l;
  3602. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  3603. };
  3604. llama_logit_info(llama_context * ctx)
  3605. : logits(llama_get_logits(ctx))
  3606. , n_vocab(llama_n_vocab(ctx))
  3607. , max_l(*std::max_element(logits, logits + n_vocab))
  3608. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  3609. { }
  3610. llama_token_data get_token_data(const llama_token token_id) const {
  3611. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  3612. return {token_id, logits[token_id], p};
  3613. }
  3614. // Return top k token_data by logit.
  3615. std::vector<llama_token_data> top_k(size_t k) {
  3616. std::vector<llama_token_data> min_heap; // min-heap by logit
  3617. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  3618. min_heap.reserve(k_min);
  3619. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  3620. min_heap.push_back(get_token_data(token_id));
  3621. }
  3622. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  3623. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  3624. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  3625. if (min_heap.front().logit < logits[token_id]) {
  3626. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  3627. min_heap.back().id = token_id;
  3628. min_heap.back().logit = logits[token_id];
  3629. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  3630. }
  3631. }
  3632. return min_heap;
  3633. }
  3634. float probability_from_logit(float logit) const {
  3635. return normalizer * std::exp(logit - max_l);
  3636. }
  3637. };
  3638. struct llama_beam_search_data {
  3639. llama_context * ctx;
  3640. size_t n_beams;
  3641. int n_past;
  3642. int n_predict;
  3643. int n_threads;
  3644. std::vector<llama_beam> beams;
  3645. std::vector<llama_beam> next_beams;
  3646. // Re-calculated on each loop iteration
  3647. size_t common_prefix_length;
  3648. // Used to communicate to/from callback on beams state.
  3649. std::vector<llama_beam_view> beam_views;
  3650. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict, int n_threads)
  3651. : ctx(ctx)
  3652. , n_beams(n_beams)
  3653. , n_past(n_past)
  3654. , n_predict(n_predict)
  3655. , n_threads(n_threads)
  3656. , beam_views(n_beams) {
  3657. beams.reserve(n_beams);
  3658. next_beams.reserve(n_beams);
  3659. }
  3660. // Collapse beams to a single beam given by index.
  3661. void collapse_beams(const size_t beam_idx) {
  3662. if (0u < beam_idx) {
  3663. std::swap(beams[0], beams[beam_idx]);
  3664. }
  3665. beams.resize(1);
  3666. }
  3667. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  3668. // The repetative patterns below reflect the 2 stages of heaps:
  3669. // * Gather elements until the vector is full, then call std::make_heap() on it.
  3670. // * If the heap is full and a new element is found that should be included, pop the
  3671. // least element to the back(), replace it with the new, then push it into the heap.
  3672. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  3673. // Min-heaps use a greater-than comparator.
  3674. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  3675. if (beam.eob) {
  3676. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  3677. if (next_beams.size() < n_beams) {
  3678. next_beams.push_back(std::move(beam));
  3679. if (next_beams.size() == n_beams) {
  3680. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  3681. }
  3682. } else if (next_beams.front().p < beam.p) {
  3683. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  3684. next_beams.back() = std::move(beam);
  3685. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  3686. }
  3687. } else {
  3688. // beam is not at end-of-sentence, so branch with next top_k tokens.
  3689. if (!beam.tokens.empty()) {
  3690. llama_eval(ctx, beam.tokens.data(), beam.tokens.size(), n_past, n_threads);
  3691. }
  3692. llama_logit_info logit_info(ctx);
  3693. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  3694. size_t i=0;
  3695. if (next_beams.size() < n_beams) {
  3696. for (; next_beams.size() < n_beams ; ++i) {
  3697. llama_beam next_beam = beam;
  3698. next_beam.tokens.push_back(next_tokens[i].id);
  3699. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  3700. next_beams.push_back(std::move(next_beam));
  3701. }
  3702. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  3703. } else {
  3704. for (; next_beams.front().p == 0.0f ; ++i) {
  3705. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  3706. next_beams.back() = beam;
  3707. next_beams.back().tokens.push_back(next_tokens[i].id);
  3708. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  3709. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  3710. }
  3711. }
  3712. for (; i < n_beams ; ++i) {
  3713. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  3714. if (next_beams.front().p < next_p) {
  3715. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  3716. next_beams.back() = beam;
  3717. next_beams.back().tokens.push_back(next_tokens[i].id);
  3718. next_beams.back().p = next_p;
  3719. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  3720. }
  3721. }
  3722. }
  3723. }
  3724. // Find common_prefix_length based on beams.
  3725. // Requires beams is not empty.
  3726. size_t find_common_prefix_length() {
  3727. size_t common_prefix_length = beams[0].tokens.size();
  3728. for (size_t i = 1 ; i < beams.size() ; ++i) {
  3729. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  3730. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  3731. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  3732. common_prefix_length = j;
  3733. break;
  3734. }
  3735. }
  3736. }
  3737. return common_prefix_length;
  3738. }
  3739. // Construct beams_state to send back to caller via the callback function.
  3740. // Side effect: set common_prefix_length = find_common_prefix_length();
  3741. llama_beams_state get_beams_state(const bool last_call) {
  3742. for (size_t i = 0 ; i < beams.size() ; ++i) {
  3743. beam_views[i] = beams[i].view();
  3744. }
  3745. common_prefix_length = find_common_prefix_length();
  3746. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  3747. }
  3748. // Loop:
  3749. // * while i < n_predict, AND
  3750. // * any of the beams have not yet reached end-of-beam (eob), AND
  3751. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  3752. // (since all other beam probabilities can only decrease)
  3753. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  3754. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  3755. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  3756. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  3757. !beams[top_beam_index()].eob ; ++i) {
  3758. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  3759. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  3760. if (common_prefix_length) {
  3761. llama_eval(ctx, beams[0].tokens.data(), common_prefix_length, n_past, n_threads);
  3762. n_past += common_prefix_length;
  3763. }
  3764. // Zero-out next_beam probabilities to place them last in following min-heap.
  3765. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  3766. for (llama_beam & beam : beams) {
  3767. beam.shift_tokens(common_prefix_length);
  3768. fill_next_beams_by_top_probabilities(beam);
  3769. }
  3770. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  3771. beams.swap(next_beams);
  3772. renormalize_beam_probabilities(beams);
  3773. }
  3774. collapse_beams(top_beam_index());
  3775. callback(callback_data, get_beams_state(true));
  3776. }
  3777. // As beams grow, the cumulative probabilities decrease.
  3778. // Renormalize them to avoid floating point underflow.
  3779. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  3780. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  3781. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  3782. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  3783. }
  3784. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  3785. size_t top_beam_index() {
  3786. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  3787. }
  3788. // Copy (p,eob) for each beam which may have been changed by the callback.
  3789. void update_beams_from_beam_views() {
  3790. for (size_t i = 0 ; i < beams.size() ; ++i) {
  3791. beams[i].p = beam_views[i].p;
  3792. beams[i].eob = beam_views[i].eob;
  3793. }
  3794. }
  3795. };
  3796. void llama_beam_search(llama_context * ctx,
  3797. llama_beam_search_callback_fn_t callback, void * callback_data,
  3798. size_t n_beams, int n_past, int n_predict, int n_threads) {
  3799. assert(ctx);
  3800. const int64_t t_start_sample_us = ggml_time_us();
  3801. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict, n_threads);
  3802. beam_search_data.loop(callback, callback_data);
  3803. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3804. ctx->n_sample++;
  3805. }
  3806. //
  3807. // quantization
  3808. //
  3809. static void llama_convert_tensor_internal(struct ggml_tensor * tensor, std::vector<float> & output, const size_t nelements, const int nthread) {
  3810. if (output.size() < nelements) {
  3811. output.resize(nelements);
  3812. }
  3813. float * f32_output = (float *) output.data();
  3814. ggml_type_traits_t qtype;
  3815. if (ggml_is_quantized(tensor->type)) {
  3816. qtype = ggml_internal_get_type_traits(tensor->type);
  3817. if (qtype.to_float == NULL) {
  3818. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  3819. }
  3820. } else if (tensor->type != GGML_TYPE_F16) {
  3821. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  3822. }
  3823. if (nthread < 2) {
  3824. if (tensor->type == GGML_TYPE_F16) {
  3825. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  3826. } else if (ggml_is_quantized(tensor->type)) {
  3827. qtype.to_float(tensor->data, f32_output, nelements);
  3828. } else {
  3829. GGML_ASSERT(false); // unreachable
  3830. }
  3831. return;
  3832. }
  3833. auto block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  3834. auto block_size_bytes = ggml_type_size(tensor->type);
  3835. GGML_ASSERT(nelements % block_size == 0);
  3836. auto nblocks = nelements / block_size;
  3837. auto blocks_per_thread = nblocks / nthread;
  3838. auto spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  3839. std::vector<std::thread> workers;
  3840. for (auto tnum = 0, in_buff_offs = 0, out_buff_offs = 0; tnum < nthread; tnum++) {
  3841. auto thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  3842. auto thr_elems = thr_blocks * block_size; // number of elements for this thread
  3843. auto thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  3844. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  3845. if (typ == GGML_TYPE_F16) {
  3846. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  3847. } else {
  3848. qtype.to_float(inbuf, outbuf, nels);
  3849. }
  3850. };
  3851. workers.push_back(std::thread(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems));
  3852. in_buff_offs += thr_block_bytes;
  3853. out_buff_offs += thr_elems;
  3854. }
  3855. for (auto & worker : workers) {
  3856. worker.join();
  3857. }
  3858. }
  3859. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  3860. ggml_type quantized_type;
  3861. llama_ftype ftype = params->ftype;
  3862. switch (params->ftype) {
  3863. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  3864. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  3865. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  3866. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  3867. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  3868. case LLAMA_FTYPE_MOSTLY_F16: quantized_type = GGML_TYPE_F16; break;
  3869. case LLAMA_FTYPE_ALL_F32: quantized_type = GGML_TYPE_F32; break;
  3870. #ifdef GGML_USE_K_QUANTS
  3871. // K-quants
  3872. case LLAMA_FTYPE_MOSTLY_Q2_K: quantized_type = GGML_TYPE_Q2_K; break;
  3873. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  3874. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  3875. case LLAMA_FTYPE_MOSTLY_Q3_K_L: quantized_type = GGML_TYPE_Q3_K; break;
  3876. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  3877. case LLAMA_FTYPE_MOSTLY_Q4_K_M: quantized_type = GGML_TYPE_Q4_K; break;
  3878. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  3879. case LLAMA_FTYPE_MOSTLY_Q5_K_M: quantized_type = GGML_TYPE_Q5_K; break;
  3880. case LLAMA_FTYPE_MOSTLY_Q6_K: quantized_type = GGML_TYPE_Q6_K; break;
  3881. #endif
  3882. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  3883. }
  3884. int nthread = params->nthread;
  3885. if (nthread <= 0) {
  3886. nthread = std::thread::hardware_concurrency();
  3887. }
  3888. std::unique_ptr<llama_model_loader> ml(new llama_model_loader(fname_inp, /*use_mmap*/ false));
  3889. llama_model model;
  3890. llm_load_arch(*ml, model);
  3891. llm_load_hparams(*ml, model, 0, 0, 0);
  3892. if (params->only_copy) {
  3893. ftype = model.ftype;
  3894. }
  3895. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  3896. struct gguf_context * ctx_out = gguf_init_empty();
  3897. // copy the KV pairs from the input file
  3898. gguf_set_kv (ctx_out, ml->ctx_gguf);
  3899. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  3900. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  3901. #ifdef GGML_USE_K_QUANTS
  3902. int n_attention_wv = 0;
  3903. int n_feed_forward_w2 = 0;
  3904. for (int i = 0; i < ml->n_tensors; ++i) {
  3905. struct ggml_tensor * meta = ml->get_tensor_meta(i);
  3906. const std::string name = ggml_get_name(meta);
  3907. // TODO: avoid hardcoded tensor names - use the TN_* constants
  3908. if (name.find("attn_v.weight") != std::string::npos) {
  3909. ++n_attention_wv;
  3910. }
  3911. else if (name.find("ffn_down.weight") != std::string::npos) {
  3912. ++n_feed_forward_w2;
  3913. }
  3914. }
  3915. if (n_attention_wv != n_feed_forward_w2 || (uint32_t)n_attention_wv != model.hparams.n_layer) {
  3916. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_feed_forward_w2 = %d, hparams.n_layer = %d\n",
  3917. __func__, n_attention_wv, n_feed_forward_w2, model.hparams.n_layer);
  3918. }
  3919. int i_attention_wv = 0;
  3920. int i_feed_forward_w2 = 0;
  3921. #endif
  3922. size_t total_size_org = 0;
  3923. size_t total_size_new = 0;
  3924. std::vector<int64_t> hist_all(1 << 4, 0);
  3925. std::vector<std::thread> workers;
  3926. std::mutex mutex;
  3927. #ifdef GGML_USE_K_QUANTS
  3928. auto use_more_bits = [] (int i_layer, int num_layers) -> bool {
  3929. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  3930. };
  3931. #endif
  3932. int idx = 0;
  3933. std::vector<uint8_t> read_data;
  3934. std::vector<uint8_t> work;
  3935. // populate the original tensors so we get an initial meta data
  3936. for (int i = 0; i < ml->n_tensors; ++i) {
  3937. struct ggml_tensor * meta = ml->get_tensor_meta(i);
  3938. gguf_add_tensor(ctx_out, meta);
  3939. }
  3940. std::ofstream fout(fname_out, std::ios::binary);
  3941. const size_t meta_size = gguf_get_meta_size(ctx_out);
  3942. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  3943. // placeholder for the meta data
  3944. ::zeros(fout, meta_size);
  3945. for (int i = 0; i < ml->n_tensors; ++i) {
  3946. struct ggml_tensor * tensor = ml->get_tensor_meta(i);
  3947. const std::string name = ggml_get_name(tensor);
  3948. read_data.resize(ggml_nbytes(tensor));
  3949. tensor->data = read_data.data();
  3950. ml->load_data_for(tensor);
  3951. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  3952. ++idx, ml->n_tensors,
  3953. ggml_get_name(tensor),
  3954. llama_format_tensor_shape(tensor).c_str(),
  3955. ggml_type_name(tensor->type));
  3956. // This used to be a regex, but <regex> has an extreme cost to compile times.
  3957. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  3958. // quantize only 2D tensors
  3959. quantize &= (tensor->n_dims == 2);
  3960. quantize &= params->quantize_output_tensor || name != "output.weight";
  3961. quantize &= !params->only_copy;
  3962. enum ggml_type new_type;
  3963. void * new_data;
  3964. size_t new_size;
  3965. if (quantize) {
  3966. new_type = quantized_type;
  3967. #ifdef GGML_USE_K_QUANTS
  3968. // TODO: avoid hardcoded tensor names - use the TN_* constants
  3969. const auto tn = LLM_TN(ml->get_arch());
  3970. if (name == tn(LLM_TENSOR_OUTPUT, "weight")) {
  3971. int nx = tensor->ne[0];
  3972. if (model.arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  3973. new_type = GGML_TYPE_Q8_0;
  3974. }
  3975. else if (new_type != GGML_TYPE_Q8_0) {
  3976. new_type = GGML_TYPE_Q6_K;
  3977. }
  3978. } else if (name.find("attn_v.weight") != std::string::npos) {
  3979. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  3980. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  3981. new_type = i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  3982. }
  3983. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  3984. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  3985. use_more_bits(i_attention_wv, n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  3986. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  3987. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  3988. (i_attention_wv < n_attention_wv/8 || i_attention_wv >= 7*n_attention_wv/8)) new_type = GGML_TYPE_Q6_K;
  3989. if (model.type == MODEL_70B) {
  3990. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  3991. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  3992. // nearly negligible increase in model size by quantizing this tensor with more bits:
  3993. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  3994. }
  3995. ++i_attention_wv;
  3996. } else if (name.find("ffn_down.weight") != std::string::npos) {
  3997. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  3998. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  3999. new_type = i_feed_forward_w2 < 2 ? GGML_TYPE_Q5_K
  4000. : model.arch != LLM_ARCH_FALCON || use_more_bits(i_feed_forward_w2, n_feed_forward_w2) ? GGML_TYPE_Q4_K
  4001. : GGML_TYPE_Q3_K;
  4002. }
  4003. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  4004. new_type = model.arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  4005. }
  4006. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  4007. if (model.arch == LLM_ARCH_FALCON) {
  4008. new_type = i_feed_forward_w2 < 2 ? GGML_TYPE_Q6_K :
  4009. use_more_bits(i_feed_forward_w2, n_feed_forward_w2) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  4010. } else {
  4011. if (use_more_bits(i_feed_forward_w2, n_feed_forward_w2)) new_type = GGML_TYPE_Q6_K;
  4012. }
  4013. }
  4014. 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;
  4015. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && model.arch != LLM_ARCH_FALCON && i_feed_forward_w2 < 4) {
  4016. new_type = GGML_TYPE_Q5_K;
  4017. }
  4018. ++i_feed_forward_w2;
  4019. } else if (name.find("attn_output.weight") != std::string::npos) {
  4020. if (model.arch != LLM_ARCH_FALCON) {
  4021. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  4022. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) new_type = GGML_TYPE_Q4_K;
  4023. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  4024. } else {
  4025. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  4026. }
  4027. }
  4028. else if (name.find("attn_qkv.weight") != std::string::npos) {
  4029. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  4030. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  4031. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  4032. }
  4033. else if (name.find("ffn_gate.weight") != std::string::npos || name.find("ffn_up.weight") != std::string::npos) {
  4034. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  4035. }
  4036. // This can be used to reduce the size of the Q5_K_S model.
  4037. // The associated PPL increase is fully in line with the size reduction
  4038. //else {
  4039. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  4040. //}
  4041. bool convert_incompatible_tensor = false;
  4042. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  4043. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K) {
  4044. int nx = tensor->ne[0];
  4045. int ny = tensor->ne[1];
  4046. if (nx % QK_K != 0) {
  4047. 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);
  4048. convert_incompatible_tensor = true;
  4049. }
  4050. }
  4051. if (convert_incompatible_tensor) {
  4052. if (name == tn(LLM_TENSOR_OUTPUT, "weight")) {
  4053. new_type = GGML_TYPE_F16; //fall back to F16 instead of just failing.
  4054. LLAMA_LOG_WARN("F16 will be used for this tensor instead.\n");
  4055. } else if (name == tn(LLM_TENSOR_TOKEN_EMBD, "weight")) {
  4056. new_type = GGML_TYPE_Q4_0; //fall back to Q4_0 instead of just failing.
  4057. LLAMA_LOG_WARN("Q4_0 will be used for this tensor instead.\n");
  4058. } else {
  4059. throw std::runtime_error("Unsupported tensor size encountered\n");
  4060. }
  4061. }
  4062. #endif
  4063. // If we've decided to quantize to the same type the tensor is already
  4064. // in then there's nothing to do.
  4065. quantize = tensor->type != new_type;
  4066. }
  4067. if (!quantize) {
  4068. new_type = tensor->type;
  4069. new_data = tensor->data;
  4070. new_size = ggml_nbytes(tensor);
  4071. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  4072. } else {
  4073. const size_t nelements = ggml_nelements(tensor);
  4074. float * f32_data;
  4075. std::vector<float> f32_conv_buf;
  4076. if (tensor->type == GGML_TYPE_F32) {
  4077. f32_data = (float *) tensor->data;
  4078. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  4079. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  4080. } else {
  4081. llama_convert_tensor_internal(tensor, f32_conv_buf, nelements, nthread);
  4082. f32_data = (float *) f32_conv_buf.data();
  4083. }
  4084. LLAMA_LOG_INFO("quantizing to %s .. ", ggml_type_name(new_type));
  4085. fflush(stdout);
  4086. work.resize(nelements * 4); // upper bound on size
  4087. new_data = work.data();
  4088. std::vector<int64_t> hist_cur(1 << 4, 0);
  4089. static const int chunk_size = 32 * 512;
  4090. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  4091. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  4092. if (nthread_use < 2) {
  4093. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nelements, hist_cur.data());
  4094. } else {
  4095. size_t counter = 0;
  4096. new_size = 0;
  4097. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, nelements]() {
  4098. std::vector<int64_t> local_hist;
  4099. size_t local_size = 0;
  4100. while (true) {
  4101. std::unique_lock<std::mutex> lock(mutex);
  4102. size_t first = counter; counter += chunk_size;
  4103. if (first >= nelements) {
  4104. if (!local_hist.empty()) {
  4105. for (int j=0; j<int(local_hist.size()); ++j) {
  4106. hist_cur[j] += local_hist[j];
  4107. }
  4108. new_size += local_size;
  4109. }
  4110. break;
  4111. }
  4112. lock.unlock();
  4113. size_t last = std::min(nelements, first + chunk_size);
  4114. if (local_hist.empty()) {
  4115. local_hist.resize(hist_cur.size(), 0);
  4116. }
  4117. local_size += ggml_quantize_chunk(new_type, f32_data, new_data, first, last - first, local_hist.data());
  4118. }
  4119. };
  4120. if ((int) workers.size() < nthread_use - 1) {
  4121. workers.resize(nthread_use - 1);
  4122. }
  4123. for (int it = 0; it < nthread_use - 1; ++it) {
  4124. workers[it] = std::thread(compute);
  4125. }
  4126. compute();
  4127. for (int it = 0; it < nthread_use - 1; ++it) {
  4128. workers[it].join();
  4129. }
  4130. }
  4131. LLAMA_LOG_INFO("size = %8.2f MB -> %8.2f MB | hist: ", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  4132. int64_t tot_count = 0;
  4133. for (size_t i = 0; i < hist_cur.size(); i++) {
  4134. hist_all[i] += hist_cur[i];
  4135. tot_count += hist_cur[i];
  4136. }
  4137. if (tot_count > 0) {
  4138. for (size_t i = 0; i < hist_cur.size(); i++) {
  4139. LLAMA_LOG_INFO("%5.3f ", hist_cur[i] / float(nelements));
  4140. }
  4141. }
  4142. LLAMA_LOG_INFO("\n");
  4143. }
  4144. total_size_org += ggml_nbytes(tensor);
  4145. total_size_new += new_size;
  4146. // update the gguf meta data as we go
  4147. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  4148. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  4149. // write tensor data + padding
  4150. fout.write((const char *) new_data, new_size);
  4151. zeros(fout, GGML_PAD(new_size, align) - new_size);
  4152. }
  4153. // go back to beginning of file and write the updated meta data
  4154. {
  4155. fout.seekp(0);
  4156. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  4157. gguf_get_meta_data(ctx_out, data.data());
  4158. fout.write((const char *) data.data(), data.size());
  4159. }
  4160. fout.close();
  4161. gguf_free(ctx_out);
  4162. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  4163. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  4164. // print histogram for all tensors
  4165. {
  4166. int64_t sum_all = 0;
  4167. for (size_t i = 0; i < hist_all.size(); i++) {
  4168. sum_all += hist_all[i];
  4169. }
  4170. if (sum_all > 0) {
  4171. LLAMA_LOG_INFO("%s: hist: ", __func__);
  4172. for (size_t i = 0; i < hist_all.size(); i++) {
  4173. LLAMA_LOG_INFO("%5.3f ", hist_all[i] / float(sum_all));
  4174. }
  4175. LLAMA_LOG_INFO("\n");
  4176. }
  4177. }
  4178. }
  4179. // TODO: after the GGUF PR, this likely won't work and needs to be updated
  4180. int llama_apply_lora_from_file_internal(const struct llama_model & model, const char * path_lora, const char * path_base_model, int n_threads) {
  4181. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  4182. const int64_t t_start_lora_us = ggml_time_us();
  4183. auto fin = std::ifstream(path_lora, std::ios::binary);
  4184. if (!fin) {
  4185. LLAMA_LOG_ERROR("%s: failed to open '%s'\n", __func__, path_lora);
  4186. return 1;
  4187. }
  4188. // verify magic and version
  4189. {
  4190. uint32_t magic;
  4191. fin.read((char *) &magic, sizeof(magic));
  4192. uint32_t format_version;
  4193. fin.read((char *) &format_version, sizeof(format_version));
  4194. if (format_version != 1) {
  4195. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  4196. return 1;
  4197. }
  4198. }
  4199. int32_t lora_r;
  4200. int32_t lora_alpha;
  4201. fin.read((char *) &lora_r, sizeof(lora_r));
  4202. fin.read((char *) &lora_alpha, sizeof(lora_alpha));
  4203. float scaling = (float)lora_alpha / (float)lora_r;
  4204. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  4205. // create a temporary ggml context to store the lora tensors
  4206. // todo: calculate size from biggest possible tensor
  4207. std::vector<uint8_t> lora_buf(1024ull * 1024ull * 1024ull);
  4208. struct ggml_init_params params;
  4209. params.mem_size = lora_buf.size();
  4210. params.mem_buffer = lora_buf.data();
  4211. params.no_alloc = false;
  4212. ggml_context * lora_ctx = ggml_init(params);
  4213. std::unordered_map<std::string, struct ggml_tensor *> lora_tensors;
  4214. // create a name -> tensor map of the model to accelerate lookups
  4215. std::unordered_map<std::string, struct ggml_tensor*> model_tensors;
  4216. for (const auto & kv : model.tensors_by_name) {
  4217. model_tensors.insert(kv);
  4218. }
  4219. // load base model
  4220. std::unique_ptr<llama_model_loader> ml;
  4221. ggml_context * base_ctx = NULL;
  4222. std::vector<uint8_t> base_buf;
  4223. if (path_base_model) {
  4224. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  4225. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true));
  4226. size_t ctx_size;
  4227. size_t mmapped_size;
  4228. ml->calc_sizes(ctx_size, mmapped_size);
  4229. base_buf.resize(ctx_size);
  4230. ggml_init_params base_params;
  4231. base_params.mem_size = base_buf.size();
  4232. base_params.mem_buffer = base_buf.data();
  4233. base_params.no_alloc = ml->use_mmap;
  4234. base_ctx = ggml_init(base_params);
  4235. // maybe this should in llama_model_loader
  4236. if (ml->use_mmap) {
  4237. ml->mapping.reset(new llama_mmap(&ml->file, /* prefetch */ 0, ggml_is_numa()));
  4238. }
  4239. }
  4240. // read tensors and apply
  4241. bool warned = false;
  4242. int n_tensors = 0;
  4243. std::vector<uint8_t> work_buffer;
  4244. while (true) {
  4245. int32_t n_dims;
  4246. int32_t length;
  4247. int32_t ftype;
  4248. fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  4249. fin.read(reinterpret_cast<char *>(&length), sizeof(length));
  4250. fin.read(reinterpret_cast<char *>(&ftype), sizeof(ftype));
  4251. if (fin.eof()) {
  4252. break;
  4253. }
  4254. int32_t ne[2] = { 1, 1 };
  4255. for (int i = 0; i < n_dims; ++i) {
  4256. fin.read(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  4257. }
  4258. std::string name;
  4259. {
  4260. char buf[1024];
  4261. fin.read(buf, length);
  4262. name = std::string(buf, length);
  4263. }
  4264. // check for lora suffix and get the type of tensor
  4265. const std::string lora_suffix = ".lora";
  4266. size_t pos = name.rfind(lora_suffix);
  4267. if (pos == std::string::npos) {
  4268. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  4269. return 1;
  4270. }
  4271. std::string lora_type = name.substr(pos + lora_suffix.length());
  4272. std::string base_name = name;
  4273. base_name.erase(pos);
  4274. // LLAMA_LOG_INFO("%s: %s => %s (lora type %s) \n", __func__, name.c_str(),base_name.c_str(), lora_type.c_str());
  4275. if (model_tensors.find(base_name) == model_tensors.end()) {
  4276. LLAMA_LOG_ERROR("%s: unknown tensor '%s' in lora adapter\n", __func__, name.data());
  4277. return 1;
  4278. }
  4279. // create ggml tensor
  4280. ggml_type wtype;
  4281. switch (ftype) {
  4282. case 0: wtype = GGML_TYPE_F32; break;
  4283. case 1: wtype = GGML_TYPE_F16; break;
  4284. default:
  4285. {
  4286. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  4287. __func__, ftype);
  4288. return false;
  4289. }
  4290. }
  4291. ggml_tensor * lora_tensor;
  4292. if (n_dims == 2) {
  4293. lora_tensor = ggml_new_tensor_2d(lora_ctx, wtype, ne[0], ne[1]);
  4294. }
  4295. else {
  4296. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  4297. return 1;
  4298. }
  4299. ggml_set_name(lora_tensor, "lora_tensor");
  4300. // load tensor data
  4301. size_t offset = fin.tellg();
  4302. size_t tensor_data_size = ggml_nbytes(lora_tensor);
  4303. offset = (offset + 31) & -32;
  4304. fin.seekg(offset);
  4305. fin.read((char*)lora_tensor->data, tensor_data_size);
  4306. lora_tensors[name] = lora_tensor;
  4307. // check if we have both A and B tensors and apply
  4308. if (lora_tensors.find(base_name + ".loraA") != lora_tensors.end() &&
  4309. lora_tensors.find(base_name + ".loraB") != lora_tensors.end()) {
  4310. ggml_tensor * dest_t = model_tensors[base_name];
  4311. offload_func_t offload_func = llama_nop;
  4312. offload_func_t offload_func_force_inplace = llama_nop;
  4313. #ifdef GGML_USE_CUBLAS
  4314. if (dest_t->backend == GGML_BACKEND_GPU || dest_t->backend == GGML_BACKEND_GPU_SPLIT) {
  4315. if (dest_t->type != GGML_TYPE_F16) {
  4316. throw std::runtime_error(format(
  4317. "%s: error: the simultaneous use of LoRAs and GPU acceleration is only supported for f16 models", __func__));
  4318. }
  4319. offload_func = ggml_cuda_assign_buffers;
  4320. offload_func_force_inplace = ggml_cuda_assign_buffers_force_inplace;
  4321. }
  4322. #endif // GGML_USE_CUBLAS
  4323. ggml_tensor * base_t;
  4324. if (ml) {
  4325. struct gguf_context * ctx_gguf = ml->ctx_gguf;
  4326. // load from base model
  4327. if (gguf_find_tensor(ctx_gguf, base_name.c_str()) < 0) {
  4328. // TODO: throw
  4329. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  4330. return 1;
  4331. }
  4332. // TODO: not tested!! maybe not working!
  4333. base_t = ml->create_tensor(base_ctx, base_name, { (uint32_t)dest_t->ne[0], (uint32_t)dest_t->ne[1] }, GGML_BACKEND_CPU);
  4334. ml->load_data_for(base_t);
  4335. } else {
  4336. base_t = dest_t;
  4337. }
  4338. if (ggml_is_quantized(base_t->type)) {
  4339. if (!warned) {
  4340. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  4341. "use a f16 or f32 base model with --lora-base\n", __func__);
  4342. warned = true;
  4343. }
  4344. }
  4345. ggml_tensor * loraA = lora_tensors[base_name + ".loraA"];
  4346. GGML_ASSERT(loraA->type == GGML_TYPE_F32);
  4347. ggml_set_name(loraA, "loraA");
  4348. ggml_tensor * loraB = lora_tensors[base_name + ".loraB"];
  4349. GGML_ASSERT(loraB->type == GGML_TYPE_F32);
  4350. ggml_set_name(loraB, "loraB");
  4351. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  4352. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  4353. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  4354. return 1;
  4355. }
  4356. // w = w + BA*s
  4357. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  4358. offload_func(BA);
  4359. ggml_set_name(BA, "BA");
  4360. if (scaling != 1.0f) {
  4361. ggml_tensor * scale_tensor = ggml_new_f32(lora_ctx, scaling);
  4362. ggml_set_name(scale_tensor, "scale_tensor");
  4363. BA = ggml_scale_inplace(lora_ctx, BA, scale_tensor);
  4364. offload_func(BA);
  4365. ggml_set_name(BA, "BA_scaled");
  4366. }
  4367. ggml_tensor * r;
  4368. if (base_t == dest_t) {
  4369. r = ggml_add_inplace(lora_ctx, dest_t, BA);
  4370. offload_func_force_inplace(r);
  4371. ggml_set_name(r, "r_add_inplace");
  4372. }
  4373. else {
  4374. r = ggml_add(lora_ctx, base_t, BA);
  4375. offload_func(r);
  4376. ggml_set_name(r, "r_add");
  4377. r = ggml_cpy(lora_ctx, r, dest_t);
  4378. offload_func(r);
  4379. ggml_set_name(r, "r_cpy");
  4380. }
  4381. struct ggml_cgraph gf = ggml_build_forward(r);
  4382. ggml_graph_compute_helper(work_buffer, &gf, n_threads);
  4383. // we won't need these tensors again, reset the context to save memory
  4384. ggml_free(lora_ctx);
  4385. lora_ctx = ggml_init(params);
  4386. lora_tensors.clear();
  4387. n_tensors++;
  4388. if (n_tensors % 4 == 0) {
  4389. LLAMA_LOG_INFO(".");
  4390. }
  4391. }
  4392. }
  4393. // TODO: this should be in a destructor, it will leak on failure
  4394. ggml_free(lora_ctx);
  4395. if (base_ctx) {
  4396. ggml_free(base_ctx);
  4397. }
  4398. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  4399. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  4400. return 0;
  4401. }
  4402. //
  4403. // interface implementation
  4404. //
  4405. struct llama_context_params llama_context_default_params() {
  4406. struct llama_context_params result = {
  4407. /*.seed =*/ LLAMA_DEFAULT_SEED,
  4408. /*.n_ctx =*/ 512,
  4409. /*.n_batch =*/ 512,
  4410. /*.n_gpu_layers =*/ 0,
  4411. /*.main_gpu =*/ 0,
  4412. /*.tensor_split =*/ nullptr,
  4413. /*.rope_freq_base =*/ 10000.0f,
  4414. /*.rope_freq_scale =*/ 1.0f,
  4415. /*.progress_callback =*/ nullptr,
  4416. /*.progress_callback_user_data =*/ nullptr,
  4417. /*.low_vram =*/ false,
  4418. /*.mul_mat_q =*/ true,
  4419. /*.f16_kv =*/ true,
  4420. /*.logits_all =*/ false,
  4421. /*.vocab_only =*/ false,
  4422. /*.use_mmap =*/ true,
  4423. /*.use_mlock =*/ false,
  4424. /*.embedding =*/ false,
  4425. };
  4426. #ifdef GGML_USE_METAL
  4427. result.n_gpu_layers = 1;
  4428. #endif
  4429. return result;
  4430. }
  4431. struct llama_model_quantize_params llama_model_quantize_default_params() {
  4432. struct llama_model_quantize_params result = {
  4433. /*.nthread =*/ 0,
  4434. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  4435. /*.allow_requantize =*/ false,
  4436. /*.quantize_output_tensor =*/ true,
  4437. /*.only_copy =*/ false,
  4438. };
  4439. return result;
  4440. }
  4441. int llama_max_devices(void) {
  4442. return LLAMA_MAX_DEVICES;
  4443. }
  4444. bool llama_mmap_supported(void) {
  4445. return llama_mmap::SUPPORTED;
  4446. }
  4447. bool llama_mlock_supported(void) {
  4448. return llama_mlock::SUPPORTED;
  4449. }
  4450. void llama_backend_init(bool numa) {
  4451. ggml_time_init();
  4452. // needed to initialize f16 tables
  4453. {
  4454. struct ggml_init_params params = { 0, NULL, false };
  4455. struct ggml_context * ctx = ggml_init(params);
  4456. ggml_free(ctx);
  4457. }
  4458. if (numa) {
  4459. ggml_numa_init();
  4460. }
  4461. #ifdef GGML_USE_MPI
  4462. ggml_mpi_backend_init();
  4463. #endif
  4464. }
  4465. void llama_backend_free(void) {
  4466. #ifdef GGML_USE_MPI
  4467. ggml_mpi_backend_free();
  4468. #endif
  4469. }
  4470. int64_t llama_time_us(void) {
  4471. return ggml_time_us();
  4472. }
  4473. struct llama_model * llama_load_model_from_file(
  4474. const char * path_model,
  4475. struct llama_context_params params) {
  4476. ggml_time_init();
  4477. llama_model * model = new llama_model;
  4478. ggml_type memory_type = params.f16_kv ? GGML_TYPE_F16 : GGML_TYPE_F32;
  4479. unsigned cur_percentage = 0;
  4480. if (params.progress_callback == NULL) {
  4481. params.progress_callback_user_data = &cur_percentage;
  4482. params.progress_callback = [](float progress, void * ctx) {
  4483. unsigned * cur_percentage_p = (unsigned *) ctx;
  4484. unsigned percentage = (unsigned) (100 * progress);
  4485. while (percentage > *cur_percentage_p) {
  4486. *cur_percentage_p = percentage;
  4487. LLAMA_LOG_INFO(".");
  4488. if (percentage >= 100) {
  4489. LLAMA_LOG_INFO("\n");
  4490. }
  4491. }
  4492. };
  4493. }
  4494. if (!llama_model_load(path_model, *model, params.n_ctx, params.n_batch, params.n_gpu_layers,
  4495. params.main_gpu, params.tensor_split, params.mul_mat_q, params.rope_freq_base, params.rope_freq_scale,
  4496. params.low_vram, memory_type, params.use_mmap, params.use_mlock, params.vocab_only,
  4497. params.progress_callback, params.progress_callback_user_data)) {
  4498. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  4499. delete model;
  4500. return nullptr;
  4501. }
  4502. return model;
  4503. }
  4504. void llama_free_model(struct llama_model * model) {
  4505. delete model;
  4506. }
  4507. struct llama_context * llama_new_context_with_model(
  4508. struct llama_model * model,
  4509. struct llama_context_params params) {
  4510. if (!model) {
  4511. return nullptr;
  4512. }
  4513. llama_context * ctx = new llama_context(*model);
  4514. if (params.seed == LLAMA_DEFAULT_SEED) {
  4515. params.seed = time(NULL);
  4516. }
  4517. ctx->rng = std::mt19937(params.seed);
  4518. ctx->logits_all = params.logits_all;
  4519. ggml_type memory_type = params.f16_kv ? GGML_TYPE_F16 : GGML_TYPE_F32;
  4520. // reserve memory for context buffers
  4521. if (!params.vocab_only) {
  4522. if (!llama_kv_cache_init(ctx->model.hparams, ctx->kv_self, memory_type, ctx->model.hparams.n_ctx, params.n_gpu_layers)) {
  4523. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  4524. llama_free(ctx);
  4525. return nullptr;
  4526. }
  4527. {
  4528. const size_t memory_size = ggml_nbytes(ctx->kv_self.k) + ggml_nbytes(ctx->kv_self.v);
  4529. LLAMA_LOG_INFO("%s: kv self size = %7.2f MB\n", __func__, memory_size / 1024.0 / 1024.0);
  4530. }
  4531. const auto & hparams = ctx->model.hparams;
  4532. // resized during inference
  4533. if (params.logits_all) {
  4534. ctx->logits.reserve(hparams.n_ctx*hparams.n_vocab);
  4535. } else {
  4536. ctx->logits.reserve(hparams.n_vocab);
  4537. }
  4538. if (params.embedding){
  4539. ctx->embedding.resize(hparams.n_embd);
  4540. }
  4541. {
  4542. static const size_t tensor_alignment = 32;
  4543. // the compute buffer is used to store the tensor and graph structs, while the allocator buffer is used for the tensor data
  4544. ctx->buf_compute.resize(ggml_tensor_overhead()*GGML_MAX_NODES + ggml_graph_overhead());
  4545. // create measure allocator
  4546. ctx->alloc = ggml_allocr_new_measure(tensor_alignment);
  4547. // build worst-case graph
  4548. int n_tokens = std::min((int)hparams.n_ctx, params.n_batch);
  4549. int n_past = hparams.n_ctx - n_tokens;
  4550. llama_token token = llama_token_bos(ctx); // not actually used by llama_build_graph, but required to choose between token and embedding inputs graph
  4551. ggml_cgraph * gf = llama_build_graph(*ctx, &token, NULL, n_tokens, n_past);
  4552. #ifdef GGML_USE_METAL
  4553. if (params.n_gpu_layers > 0) {
  4554. ctx->ctx_metal = ggml_metal_init(1);
  4555. if (!ctx->ctx_metal) {
  4556. LLAMA_LOG_ERROR("%s: ggml_metal_init() failed\n", __func__);
  4557. llama_free(ctx);
  4558. return NULL;
  4559. }
  4560. ggml_metal_graph_find_concurrency(ctx->ctx_metal, gf, false);
  4561. ggml_allocr_set_parse_seq(ctx->alloc, ggml_metal_get_concur_list(ctx->ctx_metal), ggml_metal_if_optimized(ctx->ctx_metal));
  4562. }
  4563. #endif
  4564. // measure memory requirements for the graph
  4565. size_t alloc_size = ggml_allocr_alloc_graph(ctx->alloc, gf) + tensor_alignment;
  4566. LLAMA_LOG_INFO("%s: compute buffer total size = %7.2f MB\n", __func__, (ctx->buf_compute.size + alloc_size) / 1024.0 / 1024.0);
  4567. // recreate allocator with exact memory requirements
  4568. ggml_allocr_free(ctx->alloc);
  4569. ctx->buf_alloc.resize(alloc_size);
  4570. ctx->alloc = ggml_allocr_new(ctx->buf_alloc.data, ctx->buf_alloc.size, tensor_alignment);
  4571. #ifdef GGML_USE_METAL
  4572. if (ctx->ctx_metal) {
  4573. ggml_allocr_set_parse_seq(ctx->alloc, ggml_metal_get_concur_list(ctx->ctx_metal), ggml_metal_if_optimized(ctx->ctx_metal));
  4574. }
  4575. #endif
  4576. #ifdef GGML_USE_CUBLAS
  4577. if (params.low_vram) {
  4578. LLAMA_LOG_INFO("%s: not allocating a VRAM scratch buffer due to low VRAM option\n", __func__);
  4579. ggml_cuda_set_scratch_size(0); // disable scratch
  4580. } else {
  4581. ggml_cuda_set_scratch_size(alloc_size);
  4582. LLAMA_LOG_INFO("%s: VRAM scratch buffer: %.2f MB\n", __func__, alloc_size / 1024.0 / 1024.0);
  4583. }
  4584. #endif
  4585. }
  4586. #ifdef GGML_USE_METAL
  4587. if (params.n_gpu_layers > 0) {
  4588. // this allocates all Metal resources and memory buffers
  4589. void * data_ptr = NULL;
  4590. size_t data_size = 0;
  4591. if (params.use_mmap) {
  4592. data_ptr = ctx->model.mapping->addr;
  4593. data_size = ctx->model.mapping->size;
  4594. } else {
  4595. data_ptr = ggml_get_mem_buffer(ctx->model.ctx);
  4596. data_size = ggml_get_mem_size (ctx->model.ctx);
  4597. }
  4598. const size_t max_size = ggml_get_max_tensor_size(ctx->model.ctx);
  4599. LLAMA_LOG_INFO("%s: max tensor size = %8.2f MB\n", __func__, max_size/1024.0/1024.0);
  4600. #define LLAMA_METAL_CHECK_BUF(result) \
  4601. if (!(result)) { \
  4602. LLAMA_LOG_ERROR("%s: failed to add buffer\n", __func__); \
  4603. llama_free(ctx); \
  4604. return NULL; \
  4605. }
  4606. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "data", data_ptr, data_size, max_size));
  4607. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "eval", ctx->buf_compute.data, ctx->buf_compute.size, 0));
  4608. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "kv", ctx->kv_self.buf.data, ctx->kv_self.buf.size, 0));
  4609. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "alloc", ctx->buf_alloc.data, ctx->buf_alloc.size, 0));
  4610. #undef LLAMA_METAL_CHECK_BUF
  4611. }
  4612. #endif
  4613. }
  4614. #ifdef GGML_USE_MPI
  4615. ctx->ctx_mpi = ggml_mpi_init();
  4616. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  4617. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  4618. const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  4619. while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  4620. llama_backend_free();
  4621. exit(1);
  4622. }
  4623. #endif
  4624. return ctx;
  4625. }
  4626. struct llama_context * llama_init_from_file(
  4627. const char * path_model,
  4628. struct llama_context_params params) {
  4629. struct llama_model * model = llama_load_model_from_file(path_model, params);
  4630. if (!model) {
  4631. return nullptr;
  4632. }
  4633. struct llama_context * ctx = llama_new_context_with_model(model, params);
  4634. ctx->model_owner = true;
  4635. return ctx;
  4636. }
  4637. void llama_free(struct llama_context * ctx) {
  4638. delete ctx;
  4639. }
  4640. int llama_n_vocab(const struct llama_context * ctx) {
  4641. return ctx->model.vocab.id_to_token.size();
  4642. }
  4643. int llama_n_ctx(const struct llama_context * ctx) {
  4644. return ctx->model.hparams.n_ctx;
  4645. }
  4646. int llama_n_embd(const struct llama_context * ctx) {
  4647. return ctx->model.hparams.n_embd;
  4648. }
  4649. enum llama_vocab_type llama_vocab_type(const struct llama_context * ctx) {
  4650. return ctx->model.vocab.type;
  4651. }
  4652. int llama_model_n_vocab(const struct llama_model * model) {
  4653. return model->vocab.id_to_token.size();
  4654. }
  4655. int llama_model_n_ctx(const struct llama_model * model) {
  4656. return model->hparams.n_ctx;
  4657. }
  4658. int llama_model_n_embd(const struct llama_model * model) {
  4659. return model->hparams.n_embd;
  4660. }
  4661. int llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  4662. return snprintf(buf, buf_size, "%s %s %s",
  4663. model->name.c_str(),
  4664. llama_model_type_name(model->type),
  4665. llama_model_ftype_name(model->ftype).c_str());
  4666. }
  4667. uint64_t llama_model_size(const struct llama_model * model) {
  4668. uint64_t size = 0;
  4669. for (const auto & it : model->tensors_by_name) {
  4670. size += ggml_nbytes(it.second);
  4671. }
  4672. return size;
  4673. }
  4674. uint64_t llama_model_n_params(const struct llama_model * model) {
  4675. uint64_t nparams = 0;
  4676. for (const auto & it : model->tensors_by_name) {
  4677. nparams += ggml_nelements(it.second);
  4678. }
  4679. return nparams;
  4680. }
  4681. int llama_model_quantize(
  4682. const char * fname_inp,
  4683. const char * fname_out,
  4684. const llama_model_quantize_params * params) {
  4685. try {
  4686. llama_model_quantize_internal(fname_inp, fname_out, params);
  4687. return 0;
  4688. } catch (const std::exception & err) {
  4689. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  4690. return 1;
  4691. }
  4692. }
  4693. int llama_apply_lora_from_file(struct llama_context * ctx, const char * path_lora, const char * path_base_model, int n_threads) {
  4694. try {
  4695. return llama_apply_lora_from_file_internal(ctx->model, path_lora, path_base_model, n_threads);
  4696. } catch (const std::exception & err) {
  4697. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  4698. return 1;
  4699. }
  4700. }
  4701. int llama_model_apply_lora_from_file(const struct llama_model * model, const char * path_lora, const char * path_base_model, int n_threads) {
  4702. try {
  4703. return llama_apply_lora_from_file_internal(*model, path_lora, path_base_model, n_threads);
  4704. } catch (const std::exception & err) {
  4705. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  4706. return 1;
  4707. }
  4708. }
  4709. int llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  4710. return ctx->kv_self.n;
  4711. }
  4712. #define LLAMA_MAX_RNG_STATE (64*1024)
  4713. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  4714. if (seed == LLAMA_DEFAULT_SEED) {
  4715. seed = time(NULL);
  4716. }
  4717. ctx->rng.seed(seed);
  4718. }
  4719. // Returns the *maximum* size of the state
  4720. size_t llama_get_state_size(const struct llama_context * ctx) {
  4721. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  4722. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  4723. const size_t s_rng_size = sizeof(size_t);
  4724. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  4725. const size_t s_logits_capacity = sizeof(size_t);
  4726. const size_t s_logits_size = sizeof(size_t);
  4727. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  4728. const size_t s_embedding_size = sizeof(size_t);
  4729. const size_t s_embedding = ctx->embedding.size() * sizeof(float);
  4730. const size_t s_kv_size = sizeof(size_t);
  4731. const size_t s_kv_ntok = sizeof(int);
  4732. const size_t s_kv = ctx->kv_self.buf.size;
  4733. const size_t s_total = (
  4734. + s_rng_size
  4735. + s_rng
  4736. + s_logits_capacity
  4737. + s_logits_size
  4738. + s_logits
  4739. + s_embedding_size
  4740. + s_embedding
  4741. + s_kv_size
  4742. + s_kv_ntok
  4743. + s_kv
  4744. );
  4745. return s_total;
  4746. }
  4747. // llama_context_data
  4748. struct llama_data_context {
  4749. virtual void write(const void * src, size_t size) = 0;
  4750. virtual size_t get_size_written() = 0;
  4751. virtual ~llama_data_context() = default;
  4752. };
  4753. struct llama_data_buffer_context : llama_data_context {
  4754. uint8_t * ptr;
  4755. size_t size_written = 0;
  4756. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  4757. void write(const void * src, size_t size) override {
  4758. memcpy(ptr, src, size);
  4759. ptr += size;
  4760. size_written += size;
  4761. }
  4762. size_t get_size_written() override {
  4763. return size_written;
  4764. }
  4765. };
  4766. struct llama_data_file_context : llama_data_context {
  4767. llama_file * file;
  4768. size_t size_written = 0;
  4769. llama_data_file_context(llama_file * f) : file(f) {}
  4770. void write(const void * src, size_t size) override {
  4771. file->write_raw(src, size);
  4772. size_written += size;
  4773. }
  4774. size_t get_size_written() override {
  4775. return size_written;
  4776. }
  4777. };
  4778. /** copy state data into either a buffer or file depending on the passed in context
  4779. *
  4780. * file context:
  4781. * llama_file file("/path", "wb");
  4782. * llama_data_file_context data_ctx(&file);
  4783. * llama_copy_state_data(ctx, &data_ctx);
  4784. *
  4785. * buffer context:
  4786. * std::vector<uint8_t> buf(max_size, 0);
  4787. * llama_data_buffer_context data_ctx(&buf.data());
  4788. * llama_copy_state_data(ctx, &data_ctx);
  4789. *
  4790. */
  4791. void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  4792. // copy rng
  4793. {
  4794. std::stringstream rng_ss;
  4795. rng_ss << ctx->rng;
  4796. const size_t rng_size = rng_ss.str().size();
  4797. char rng_buf[LLAMA_MAX_RNG_STATE];
  4798. memset(&rng_buf[0], 0, LLAMA_MAX_RNG_STATE);
  4799. memcpy(&rng_buf[0], rng_ss.str().data(), rng_ss.str().size());
  4800. data_ctx->write(&rng_size, sizeof(rng_size));
  4801. data_ctx->write(&rng_buf[0], LLAMA_MAX_RNG_STATE);
  4802. }
  4803. // copy logits
  4804. {
  4805. const size_t logits_cap = ctx->logits.capacity();
  4806. const size_t logits_size = ctx->logits.size();
  4807. data_ctx->write(&logits_cap, sizeof(logits_cap));
  4808. data_ctx->write(&logits_size, sizeof(logits_size));
  4809. if (logits_size) {
  4810. data_ctx->write(ctx->logits.data(), logits_size * sizeof(float));
  4811. }
  4812. // If there is a gap between the size and the capacity, write padding
  4813. size_t padding_size = (logits_cap - logits_size) * sizeof(float);
  4814. if (padding_size > 0) {
  4815. std::vector<uint8_t> padding(padding_size, 0); // Create a buffer filled with zeros
  4816. data_ctx->write(padding.data(), padding_size);
  4817. }
  4818. }
  4819. // copy embeddings
  4820. {
  4821. const size_t embedding_size = ctx->embedding.size();
  4822. data_ctx->write(&embedding_size, sizeof(embedding_size));
  4823. if (embedding_size) {
  4824. data_ctx->write(ctx->embedding.data(), embedding_size * sizeof(float));
  4825. }
  4826. }
  4827. // copy kv cache
  4828. {
  4829. const auto & kv_self = ctx->kv_self;
  4830. const auto & hparams = ctx->model.hparams;
  4831. const int n_layer = hparams.n_layer;
  4832. const int n_embd = hparams.n_embd_gqa();
  4833. const int n_ctx = hparams.n_ctx;
  4834. const size_t kv_size = kv_self.buf.size;
  4835. const int kv_ntok = llama_get_kv_cache_token_count(ctx);
  4836. data_ctx->write(&kv_size, sizeof(kv_size));
  4837. data_ctx->write(&kv_ntok, sizeof(kv_ntok));
  4838. if (kv_size) {
  4839. const size_t elt_size = ggml_element_size(kv_self.k);
  4840. ggml_context * cpy_ctx = ggml_init({ 4096, NULL, /* no_alloc */ true });
  4841. ggml_cgraph gf{};
  4842. ggml_tensor * kout3d = ggml_new_tensor_3d(cpy_ctx, kv_self.k->type, n_embd, kv_ntok, n_layer);
  4843. std::vector<uint8_t> kout3d_data(ggml_nbytes(kout3d), 0);
  4844. kout3d->data = kout3d_data.data();
  4845. ggml_tensor * vout3d = ggml_new_tensor_3d(cpy_ctx, kv_self.v->type, kv_ntok, n_embd, n_layer);
  4846. std::vector<uint8_t> vout3d_data(ggml_nbytes(vout3d), 0);
  4847. vout3d->data = vout3d_data.data();
  4848. ggml_tensor * k3d = ggml_view_3d(cpy_ctx, kv_self.k,
  4849. n_embd, kv_ntok, n_layer,
  4850. elt_size*n_embd, elt_size*n_embd*n_ctx, 0);
  4851. ggml_tensor * v3d = ggml_view_3d(cpy_ctx, kv_self.v,
  4852. kv_ntok, n_embd, n_layer,
  4853. elt_size*n_ctx, elt_size*n_ctx*n_embd, 0);
  4854. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, k3d, kout3d));
  4855. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, v3d, vout3d));
  4856. ggml_graph_compute_helper(ctx->work_buffer, &gf, /*n_threads*/ 1);
  4857. ggml_free(cpy_ctx);
  4858. // our data is now in the kout3d_data and vout3d_data buffers
  4859. // write them to file
  4860. data_ctx->write(kout3d_data.data(), kout3d_data.size());
  4861. data_ctx->write(vout3d_data.data(), vout3d_data.size());
  4862. }
  4863. }
  4864. }
  4865. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  4866. llama_data_buffer_context data_ctx(dst);
  4867. llama_copy_state_data_internal(ctx, &data_ctx);
  4868. return data_ctx.get_size_written();
  4869. }
  4870. // Sets the state reading from the specified source address
  4871. size_t llama_set_state_data(struct llama_context * ctx, uint8_t * src) {
  4872. uint8_t * inp = src;
  4873. // set rng
  4874. {
  4875. size_t rng_size;
  4876. char rng_buf[LLAMA_MAX_RNG_STATE];
  4877. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  4878. memcpy(&rng_buf[0], inp, LLAMA_MAX_RNG_STATE); inp += LLAMA_MAX_RNG_STATE;
  4879. std::stringstream rng_ss;
  4880. rng_ss.str(std::string(&rng_buf[0], rng_size));
  4881. rng_ss >> ctx->rng;
  4882. GGML_ASSERT(!rng_ss.fail());
  4883. }
  4884. // set logits
  4885. {
  4886. size_t logits_cap;
  4887. size_t logits_size;
  4888. memcpy(&logits_cap, inp, sizeof(logits_cap)); inp += sizeof(logits_cap);
  4889. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  4890. GGML_ASSERT(ctx->logits.capacity() == logits_cap);
  4891. if (logits_size) {
  4892. ctx->logits.resize(logits_size);
  4893. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  4894. }
  4895. inp += logits_cap * sizeof(float);
  4896. }
  4897. // set embeddings
  4898. {
  4899. size_t embedding_size;
  4900. memcpy(&embedding_size, inp, sizeof(embedding_size)); inp += sizeof(embedding_size);
  4901. GGML_ASSERT(ctx->embedding.capacity() == embedding_size);
  4902. if (embedding_size) {
  4903. memcpy(ctx->embedding.data(), inp, embedding_size * sizeof(float));
  4904. inp += embedding_size * sizeof(float);
  4905. }
  4906. }
  4907. // set kv cache
  4908. {
  4909. const auto & kv_self = ctx->kv_self;
  4910. const auto & hparams = ctx->model.hparams;
  4911. const int n_layer = hparams.n_layer;
  4912. const int n_embd = hparams.n_embd_gqa();
  4913. const int n_ctx = hparams.n_ctx;
  4914. size_t kv_size;
  4915. int kv_ntok;
  4916. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  4917. memcpy(&kv_ntok, inp, sizeof(kv_ntok)); inp += sizeof(kv_ntok);
  4918. if (kv_size) {
  4919. GGML_ASSERT(kv_self.buf.size == kv_size);
  4920. const size_t elt_size = ggml_element_size(kv_self.k);
  4921. ggml_context * cpy_ctx = ggml_init({ 4096, NULL, /* no_alloc */ true });
  4922. ggml_cgraph gf{};
  4923. ggml_tensor * kin3d = ggml_new_tensor_3d(cpy_ctx, kv_self.k->type, n_embd, kv_ntok, n_layer);
  4924. kin3d->data = (void *) inp;
  4925. inp += ggml_nbytes(kin3d);
  4926. ggml_tensor * vin3d = ggml_new_tensor_3d(cpy_ctx, kv_self.v->type, kv_ntok, n_embd, n_layer);
  4927. vin3d->data = (void *) inp;
  4928. inp += ggml_nbytes(vin3d);
  4929. ggml_tensor * k3d = ggml_view_3d(cpy_ctx, kv_self.k,
  4930. n_embd, kv_ntok, n_layer,
  4931. elt_size*n_embd, elt_size*n_embd*n_ctx, 0);
  4932. ggml_tensor * v3d = ggml_view_3d(cpy_ctx, kv_self.v,
  4933. kv_ntok, n_embd, n_layer,
  4934. elt_size*n_ctx, elt_size*n_ctx*n_embd, 0);
  4935. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, kin3d, k3d));
  4936. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, vin3d, v3d));
  4937. ggml_graph_compute_helper(ctx->work_buffer, &gf, /*n_threads*/ 1);
  4938. ggml_free(cpy_ctx);
  4939. }
  4940. ctx->kv_self.n = kv_ntok;
  4941. }
  4942. const size_t nread = inp - src;
  4943. const size_t max_size = llama_get_state_size(ctx);
  4944. GGML_ASSERT(nread <= max_size);
  4945. return nread;
  4946. }
  4947. 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) {
  4948. llama_file file(path_session, "rb");
  4949. // sanity checks
  4950. {
  4951. const uint32_t magic = file.read_u32();
  4952. const uint32_t version = file.read_u32();
  4953. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  4954. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  4955. return false;
  4956. }
  4957. llama_hparams session_hparams;
  4958. file.read_raw(&session_hparams, sizeof(llama_hparams));
  4959. if (session_hparams != ctx->model.hparams) {
  4960. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  4961. return false;
  4962. }
  4963. }
  4964. // load the prompt
  4965. {
  4966. const uint32_t n_token_count = file.read_u32();
  4967. if (n_token_count > n_token_capacity) {
  4968. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  4969. return false;
  4970. }
  4971. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  4972. *n_token_count_out = n_token_count;
  4973. }
  4974. // restore the context state
  4975. {
  4976. const size_t n_state_size_cur = file.size - file.tell();
  4977. const size_t n_state_size_max = llama_get_state_size(ctx);
  4978. if (n_state_size_cur > n_state_size_max) {
  4979. 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);
  4980. return false;
  4981. }
  4982. std::vector<uint8_t> state_data(n_state_size_max);
  4983. file.read_raw(state_data.data(), n_state_size_cur);
  4984. llama_set_state_data(ctx, state_data.data());
  4985. }
  4986. return true;
  4987. }
  4988. 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) {
  4989. try {
  4990. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  4991. } catch (const std::exception & err) {
  4992. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  4993. return false;
  4994. }
  4995. }
  4996. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  4997. llama_file file(path_session, "wb");
  4998. file.write_u32(LLAMA_SESSION_MAGIC);
  4999. file.write_u32(LLAMA_SESSION_VERSION);
  5000. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  5001. // save the prompt
  5002. file.write_u32((uint32_t) n_token_count);
  5003. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  5004. // save the context state using stream saving
  5005. llama_data_file_context data_ctx(&file);
  5006. llama_copy_state_data_internal(ctx, &data_ctx);
  5007. return true;
  5008. }
  5009. int llama_eval(
  5010. struct llama_context * ctx,
  5011. const llama_token * tokens,
  5012. int n_tokens,
  5013. int n_past,
  5014. int n_threads) {
  5015. if (!llama_eval_internal(*ctx, tokens, nullptr, n_tokens, n_past, n_threads, nullptr)) {
  5016. LLAMA_LOG_ERROR("%s: failed to eval\n", __func__);
  5017. return 1;
  5018. }
  5019. // get a more accurate load time, upon first eval
  5020. // TODO: fix this
  5021. if (!ctx->has_evaluated_once) {
  5022. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  5023. ctx->has_evaluated_once = true;
  5024. }
  5025. return 0;
  5026. }
  5027. int llama_eval_embd(
  5028. struct llama_context * ctx,
  5029. const float * embd,
  5030. int n_tokens,
  5031. int n_past,
  5032. int n_threads) {
  5033. if (!llama_eval_internal(*ctx, nullptr, embd, n_tokens, n_past, n_threads, nullptr)) {
  5034. LLAMA_LOG_ERROR("%s: failed to eval\n", __func__);
  5035. return 1;
  5036. }
  5037. // get a more accurate load time, upon first eval
  5038. // TODO: fix this
  5039. if (!ctx->has_evaluated_once) {
  5040. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  5041. ctx->has_evaluated_once = true;
  5042. }
  5043. return 0;
  5044. }
  5045. int llama_eval_export(struct llama_context * ctx, const char * fname) {
  5046. const int n_batch = 1;
  5047. const int n_ctx = 512 - n_batch;
  5048. const std::vector<llama_token> tmp(n_batch, llama_token_bos(ctx));
  5049. if (!llama_eval_internal(*ctx, tmp.data(), nullptr, tmp.size(), n_ctx, 1, fname)) {
  5050. LLAMA_LOG_ERROR("%s: failed to eval\n", __func__);
  5051. return 1;
  5052. }
  5053. return 0;
  5054. }
  5055. float * llama_get_logits(struct llama_context * ctx) {
  5056. return ctx->logits.data();
  5057. }
  5058. float * llama_get_embeddings(struct llama_context * ctx) {
  5059. return ctx->embedding.data();
  5060. }
  5061. const char * llama_token_get_text(const struct llama_context * ctx, llama_token token) {
  5062. return ctx->model.vocab.id_to_token[token].text.c_str();
  5063. }
  5064. float llama_token_get_score(const struct llama_context * ctx, llama_token token) {
  5065. return ctx->model.vocab.id_to_token[token].score;
  5066. }
  5067. llama_token_type llama_token_get_type(const struct llama_context * ctx, llama_token token) {
  5068. return ctx->model.vocab.id_to_token[token].type;
  5069. }
  5070. llama_token llama_token_bos(const struct llama_context * ctx) {
  5071. return ctx->model.vocab.special_bos_id;
  5072. }
  5073. llama_token llama_token_eos(const struct llama_context * ctx) {
  5074. return ctx->model.vocab.special_eos_id;
  5075. }
  5076. llama_token llama_token_nl(const struct llama_context * ctx) {
  5077. return ctx->model.vocab.linefeed_id;
  5078. }
  5079. int llama_tokenize(
  5080. struct llama_context * ctx,
  5081. const char * text,
  5082. llama_token * tokens,
  5083. int n_max_tokens,
  5084. bool add_bos) {
  5085. return llama_tokenize_with_model(&ctx->model, text, tokens, n_max_tokens, add_bos);
  5086. }
  5087. int llama_tokenize_with_model(
  5088. const struct llama_model * model,
  5089. const char * text,
  5090. llama_token * tokens,
  5091. int n_max_tokens,
  5092. bool add_bos) {
  5093. auto res = llama_tokenize_internal(model->vocab, text, add_bos);
  5094. if (n_max_tokens < (int) res.size()) {
  5095. LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  5096. return -((int) res.size());
  5097. }
  5098. for (size_t i = 0; i < res.size(); i++) {
  5099. tokens[i] = res[i];
  5100. }
  5101. return res.size();
  5102. }
  5103. int llama_token_to_piece(const struct llama_context * ctx, llama_token token, char * buf, int length) {
  5104. return llama_token_to_piece_with_model(&ctx->model, token, buf, length);
  5105. }
  5106. // does not write null-terminator to buf
  5107. int llama_token_to_piece_with_model(const struct llama_model * model, llama_token token, char * buf, int length) {
  5108. if (0 <= token && token < llama_model_n_vocab(model)) {
  5109. if (llama_is_normal_token(model->vocab, token)) {
  5110. std::string result = model->vocab.id_to_token[token].text;
  5111. if (llama_vocab_get_type(model->vocab) == LLAMA_VOCAB_TYPE_SPM) {
  5112. llama_unescape_whitespace(result);
  5113. }
  5114. if (length < (int) result.length()) {
  5115. return -result.length();
  5116. }
  5117. memcpy(buf, result.c_str(), result.length());
  5118. return result.length();
  5119. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  5120. if (length < 3) {
  5121. return -3;
  5122. }
  5123. buf[0] = '\xe2';
  5124. buf[1] = '\x96';
  5125. buf[2] = '\x85';
  5126. return 3;
  5127. } else if (llama_is_control_token(model->vocab, token)) {
  5128. ;
  5129. } else if (llama_is_byte_token(model->vocab, token)) {
  5130. if (length < 1) {
  5131. return -1;
  5132. }
  5133. buf[0] = llama_token_to_byte(model->vocab, token);
  5134. return 1;
  5135. }
  5136. }
  5137. return 0;
  5138. }
  5139. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  5140. struct llama_timings result = {
  5141. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  5142. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  5143. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  5144. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  5145. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  5146. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  5147. /*.n_sample =*/ std::max(1, ctx->n_sample),
  5148. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  5149. /*.n_eval =*/ std::max(1, ctx->n_eval),
  5150. };
  5151. return result;
  5152. }
  5153. void llama_print_timings(struct llama_context * ctx) {
  5154. const llama_timings timings = llama_get_timings(ctx);
  5155. LLAMA_LOG_INFO("\n");
  5156. LLAMA_LOG_INFO("%s: load time = %8.2f ms\n", __func__, timings.t_load_ms);
  5157. LLAMA_LOG_INFO("%s: sample time = %8.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  5158. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  5159. LLAMA_LOG_INFO("%s: prompt eval time = %8.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  5160. __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);
  5161. LLAMA_LOG_INFO("%s: eval time = %8.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  5162. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  5163. LLAMA_LOG_INFO("%s: total time = %8.2f ms\n", __func__, (timings.t_end_ms - timings.t_start_ms));
  5164. }
  5165. void llama_reset_timings(struct llama_context * ctx) {
  5166. ctx->t_start_us = ggml_time_us();
  5167. ctx->t_sample_us = ctx->n_sample = 0;
  5168. ctx->t_eval_us = ctx->n_eval = 0;
  5169. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  5170. }
  5171. const char * llama_print_system_info(void) {
  5172. static std::string s;
  5173. s = "";
  5174. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  5175. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  5176. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  5177. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  5178. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  5179. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  5180. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  5181. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  5182. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  5183. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  5184. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  5185. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  5186. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  5187. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  5188. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  5189. return s.c_str();
  5190. }
  5191. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  5192. fprintf(stream, "\n");
  5193. fprintf(stream, "###########\n");
  5194. fprintf(stream, "# Timings #\n");
  5195. fprintf(stream, "###########\n");
  5196. fprintf(stream, "\n");
  5197. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  5198. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  5199. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  5200. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  5201. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  5202. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  5203. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  5204. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  5205. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  5206. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  5207. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  5208. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  5209. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  5210. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  5211. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  5212. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  5213. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  5214. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  5215. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  5216. }
  5217. // For internal test use
  5218. const std::vector<std::pair<std::string, struct ggml_tensor *>>& llama_internal_get_tensor_map(struct llama_context * ctx) {
  5219. return ctx->model.tensors_by_name;
  5220. }
  5221. void llama_log_set(llama_log_callback log_callback, void * user_data) {
  5222. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  5223. g_state.log_callback_user_data = user_data;
  5224. }
  5225. static void llama_log_internal_v(llama_log_level level, const char * format, va_list args) {
  5226. va_list args_copy;
  5227. va_copy(args_copy, args);
  5228. char buffer[128];
  5229. int len = vsnprintf(buffer, 128, format, args);
  5230. if (len < 128) {
  5231. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  5232. } else {
  5233. char* buffer2 = new char[len+1];
  5234. vsnprintf(buffer2, len+1, format, args_copy);
  5235. buffer2[len] = 0;
  5236. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  5237. delete[] buffer2;
  5238. }
  5239. va_end(args_copy);
  5240. }
  5241. static void llama_log_internal(llama_log_level level, const char * format, ...) {
  5242. va_list args;
  5243. va_start(args, format);
  5244. llama_log_internal_v(level, format, args);
  5245. va_end(args);
  5246. }
  5247. static void llama_log_callback_default(llama_log_level level, const char * text, void * user_data) {
  5248. (void) level;
  5249. (void) user_data;
  5250. fputs(text, stderr);
  5251. fflush(stderr);
  5252. }