llama.cpp 400 KB

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