llama.cpp 561 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429
  1. #define LLAMA_API_INTERNAL
  2. #include "llama.h"
  3. #include "unicode.h"
  4. #include "ggml.h"
  5. #include "ggml-alloc.h"
  6. #include "ggml-backend.h"
  7. #ifdef GGML_USE_CUBLAS
  8. # include "ggml-cuda.h"
  9. #elif defined(GGML_USE_CLBLAST)
  10. # include "ggml-opencl.h"
  11. #elif defined(GGML_USE_VULKAN)
  12. # include "ggml-vulkan.h"
  13. #elif defined(GGML_USE_SYCL)
  14. # include "ggml-sycl.h"
  15. #elif defined(GGML_USE_KOMPUTE)
  16. # include "ggml-kompute.h"
  17. #endif
  18. #ifdef GGML_USE_METAL
  19. # include "ggml-metal.h"
  20. #endif
  21. #ifdef GGML_USE_MPI
  22. # include "ggml-mpi.h"
  23. #endif
  24. #ifndef QK_K
  25. # ifdef GGML_QKK_64
  26. # define QK_K 64
  27. # else
  28. # define QK_K 256
  29. # endif
  30. #endif
  31. #ifdef __has_include
  32. #if __has_include(<unistd.h>)
  33. #include <unistd.h>
  34. #if defined(_POSIX_MAPPED_FILES)
  35. #include <sys/mman.h>
  36. #include <fcntl.h>
  37. #endif
  38. #if defined(_POSIX_MEMLOCK_RANGE)
  39. #include <sys/resource.h>
  40. #endif
  41. #endif
  42. #endif
  43. #if defined(_WIN32)
  44. #define WIN32_LEAN_AND_MEAN
  45. #ifndef NOMINMAX
  46. #define NOMINMAX
  47. #endif
  48. #include <windows.h>
  49. #include <io.h>
  50. #endif
  51. #include <algorithm>
  52. #include <array>
  53. #include <cassert>
  54. #include <cfloat>
  55. #include <cinttypes>
  56. #include <climits>
  57. #include <cmath>
  58. #include <cstdarg>
  59. #include <cstddef>
  60. #include <cstdint>
  61. #include <cstdio>
  62. #include <cstring>
  63. #include <ctime>
  64. #include <cwctype>
  65. #include <forward_list>
  66. #include <fstream>
  67. #include <functional>
  68. #include <initializer_list>
  69. #include <locale>
  70. #include <map>
  71. #include <memory>
  72. #include <mutex>
  73. #include <numeric>
  74. #include <queue>
  75. #include <random>
  76. #include <regex>
  77. #include <set>
  78. #include <sstream>
  79. #include <thread>
  80. #include <type_traits>
  81. #include <unordered_map>
  82. #if defined(_MSC_VER)
  83. #pragma warning(disable: 4244 4267) // possible loss of data
  84. #endif
  85. #ifdef __GNUC__
  86. #ifdef __MINGW32__
  87. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  88. #else
  89. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  90. #endif
  91. #else
  92. #define LLAMA_ATTRIBUTE_FORMAT(...)
  93. #endif
  94. #define LLAMA_MAX_NODES 8192
  95. #define LLAMA_MAX_EXPERTS 8
  96. //
  97. // logging
  98. //
  99. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  100. static void llama_log_internal (ggml_log_level level, const char* format, ...);
  101. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
  102. #define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  103. #define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  104. #define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  105. //
  106. // helpers
  107. //
  108. static size_t utf8_len(char src) {
  109. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  110. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  111. return lookup[highbits];
  112. }
  113. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  114. std::string result;
  115. for (size_t pos = 0; ; pos += search.length()) {
  116. auto new_pos = s.find(search, pos);
  117. if (new_pos == std::string::npos) {
  118. result += s.substr(pos, s.size() - pos);
  119. break;
  120. }
  121. result += s.substr(pos, new_pos - pos) + replace;
  122. pos = new_pos;
  123. }
  124. s = std::move(result);
  125. }
  126. static bool is_float_close(float a, float b, float abs_tol) {
  127. // Check for non-negative tolerance
  128. if (abs_tol < 0.0) {
  129. throw std::invalid_argument("Tolerance must be non-negative");
  130. }
  131. // Exact equality check
  132. if (a == b) {
  133. return true;
  134. }
  135. // Check for infinities
  136. if (std::isinf(a) || std::isinf(b)) {
  137. return false;
  138. }
  139. // Regular comparison using the provided absolute tolerance
  140. return std::fabs(b - a) <= abs_tol;
  141. }
  142. static void zeros(std::ofstream & file, size_t n) {
  143. char zero = 0;
  144. for (size_t i = 0; i < n; ++i) {
  145. file.write(&zero, 1);
  146. }
  147. }
  148. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  149. static std::string format(const char * fmt, ...) {
  150. va_list ap;
  151. va_list ap2;
  152. va_start(ap, fmt);
  153. va_copy(ap2, ap);
  154. int size = vsnprintf(NULL, 0, fmt, ap);
  155. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  156. std::vector<char> buf(size + 1);
  157. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  158. GGML_ASSERT(size2 == size);
  159. va_end(ap2);
  160. va_end(ap);
  161. return std::string(buf.data(), size);
  162. }
  163. //
  164. // gguf constants (sync with gguf.py)
  165. //
  166. enum llm_arch {
  167. LLM_ARCH_LLAMA,
  168. LLM_ARCH_FALCON,
  169. LLM_ARCH_BAICHUAN,
  170. LLM_ARCH_GPT2,
  171. LLM_ARCH_GPTJ,
  172. LLM_ARCH_GPTNEOX,
  173. LLM_ARCH_MPT,
  174. LLM_ARCH_STARCODER,
  175. LLM_ARCH_PERSIMMON,
  176. LLM_ARCH_REFACT,
  177. LLM_ARCH_BERT,
  178. LLM_ARCH_NOMIC_BERT,
  179. LLM_ARCH_BLOOM,
  180. LLM_ARCH_STABLELM,
  181. LLM_ARCH_QWEN,
  182. LLM_ARCH_QWEN2,
  183. LLM_ARCH_PHI2,
  184. LLM_ARCH_PLAMO,
  185. LLM_ARCH_CODESHELL,
  186. LLM_ARCH_ORION,
  187. LLM_ARCH_INTERNLM2,
  188. LLM_ARCH_MINICPM,
  189. LLM_ARCH_GEMMA,
  190. LLM_ARCH_STARCODER2,
  191. LLM_ARCH_MAMBA,
  192. LLM_ARCH_UNKNOWN,
  193. };
  194. static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  195. { LLM_ARCH_LLAMA, "llama" },
  196. { LLM_ARCH_FALCON, "falcon" },
  197. { LLM_ARCH_GPT2, "gpt2" },
  198. { LLM_ARCH_GPTJ, "gptj" },
  199. { LLM_ARCH_GPTNEOX, "gptneox" },
  200. { LLM_ARCH_MPT, "mpt" },
  201. { LLM_ARCH_BAICHUAN, "baichuan" },
  202. { LLM_ARCH_STARCODER, "starcoder" },
  203. { LLM_ARCH_PERSIMMON, "persimmon" },
  204. { LLM_ARCH_REFACT, "refact" },
  205. { LLM_ARCH_BERT, "bert" },
  206. { LLM_ARCH_NOMIC_BERT, "nomic-bert" },
  207. { LLM_ARCH_BLOOM, "bloom" },
  208. { LLM_ARCH_STABLELM, "stablelm" },
  209. { LLM_ARCH_QWEN, "qwen" },
  210. { LLM_ARCH_QWEN2, "qwen2" },
  211. { LLM_ARCH_PHI2, "phi2" },
  212. { LLM_ARCH_PLAMO, "plamo" },
  213. { LLM_ARCH_CODESHELL, "codeshell" },
  214. { LLM_ARCH_ORION, "orion" },
  215. { LLM_ARCH_INTERNLM2, "internlm2" },
  216. { LLM_ARCH_MINICPM, "minicpm" },
  217. { LLM_ARCH_GEMMA, "gemma" },
  218. { LLM_ARCH_STARCODER2, "starcoder2" },
  219. { LLM_ARCH_MAMBA, "mamba" },
  220. { LLM_ARCH_UNKNOWN, "(unknown)" },
  221. };
  222. enum llm_kv {
  223. LLM_KV_GENERAL_ARCHITECTURE,
  224. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  225. LLM_KV_GENERAL_ALIGNMENT,
  226. LLM_KV_GENERAL_NAME,
  227. LLM_KV_GENERAL_AUTHOR,
  228. LLM_KV_GENERAL_URL,
  229. LLM_KV_GENERAL_DESCRIPTION,
  230. LLM_KV_GENERAL_LICENSE,
  231. LLM_KV_GENERAL_SOURCE_URL,
  232. LLM_KV_GENERAL_SOURCE_HF_REPO,
  233. LLM_KV_VOCAB_SIZE,
  234. LLM_KV_CONTEXT_LENGTH,
  235. LLM_KV_EMBEDDING_LENGTH,
  236. LLM_KV_BLOCK_COUNT,
  237. LLM_KV_FEED_FORWARD_LENGTH,
  238. LLM_KV_USE_PARALLEL_RESIDUAL,
  239. LLM_KV_TENSOR_DATA_LAYOUT,
  240. LLM_KV_EXPERT_COUNT,
  241. LLM_KV_EXPERT_USED_COUNT,
  242. LLM_KV_POOLING_TYPE,
  243. LLM_KV_ATTENTION_HEAD_COUNT,
  244. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  245. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  246. LLM_KV_ATTENTION_CLAMP_KQV,
  247. LLM_KV_ATTENTION_KEY_LENGTH,
  248. LLM_KV_ATTENTION_VALUE_LENGTH,
  249. LLM_KV_ATTENTION_LAYERNORM_EPS,
  250. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  251. LLM_KV_ATTENTION_CAUSAL,
  252. LLM_KV_ROPE_DIMENSION_COUNT,
  253. LLM_KV_ROPE_FREQ_BASE,
  254. LLM_KV_ROPE_SCALE_LINEAR,
  255. LLM_KV_ROPE_SCALING_TYPE,
  256. LLM_KV_ROPE_SCALING_FACTOR,
  257. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  258. LLM_KV_ROPE_SCALING_FINETUNED,
  259. LLM_KV_SSM_INNER_SIZE,
  260. LLM_KV_SSM_CONV_KERNEL,
  261. LLM_KV_SSM_STATE_SIZE,
  262. LLM_KV_SSM_TIME_STEP_RANK,
  263. LLM_KV_TOKENIZER_MODEL,
  264. LLM_KV_TOKENIZER_LIST,
  265. LLM_KV_TOKENIZER_TOKEN_TYPE,
  266. LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT,
  267. LLM_KV_TOKENIZER_SCORES,
  268. LLM_KV_TOKENIZER_MERGES,
  269. LLM_KV_TOKENIZER_BOS_ID,
  270. LLM_KV_TOKENIZER_EOS_ID,
  271. LLM_KV_TOKENIZER_UNK_ID,
  272. LLM_KV_TOKENIZER_SEP_ID,
  273. LLM_KV_TOKENIZER_PAD_ID,
  274. LLM_KV_TOKENIZER_ADD_BOS,
  275. LLM_KV_TOKENIZER_ADD_EOS,
  276. LLM_KV_TOKENIZER_ADD_PREFIX,
  277. LLM_KV_TOKENIZER_HF_JSON,
  278. LLM_KV_TOKENIZER_RWKV,
  279. };
  280. static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
  281. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  282. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  283. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  284. { LLM_KV_GENERAL_NAME, "general.name" },
  285. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  286. { LLM_KV_GENERAL_URL, "general.url" },
  287. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  288. { LLM_KV_GENERAL_LICENSE, "general.license" },
  289. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  290. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  291. { LLM_KV_VOCAB_SIZE, "%s.vocab_size" },
  292. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  293. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  294. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  295. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  296. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  297. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  298. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  299. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  300. { LLM_KV_POOLING_TYPE , "%s.pooling_type" },
  301. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  302. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  303. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  304. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  305. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  306. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  307. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  308. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  309. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  310. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  311. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  312. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  313. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  314. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  315. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  316. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  317. { LLM_KV_SSM_CONV_KERNEL, "%s.ssm.conv_kernel" },
  318. { LLM_KV_SSM_INNER_SIZE, "%s.ssm.inner_size" },
  319. { LLM_KV_SSM_STATE_SIZE, "%s.ssm.state_size" },
  320. { LLM_KV_SSM_TIME_STEP_RANK, "%s.ssm.time_step_rank" },
  321. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  322. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  323. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  324. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  325. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  326. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  327. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  328. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  329. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  330. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  331. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  332. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  333. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  334. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  335. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  336. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  337. };
  338. struct LLM_KV {
  339. LLM_KV(llm_arch arch) : arch(arch) {}
  340. llm_arch arch;
  341. std::string operator()(llm_kv kv) const {
  342. return ::format(LLM_KV_NAMES.at(kv), LLM_ARCH_NAMES.at(arch));
  343. }
  344. };
  345. enum llm_tensor {
  346. LLM_TENSOR_TOKEN_EMBD,
  347. LLM_TENSOR_TOKEN_EMBD_NORM,
  348. LLM_TENSOR_TOKEN_TYPES,
  349. LLM_TENSOR_POS_EMBD,
  350. LLM_TENSOR_OUTPUT,
  351. LLM_TENSOR_OUTPUT_NORM,
  352. LLM_TENSOR_ROPE_FREQS,
  353. LLM_TENSOR_ATTN_Q,
  354. LLM_TENSOR_ATTN_K,
  355. LLM_TENSOR_ATTN_V,
  356. LLM_TENSOR_ATTN_QKV,
  357. LLM_TENSOR_ATTN_OUT,
  358. LLM_TENSOR_ATTN_NORM,
  359. LLM_TENSOR_ATTN_NORM_2,
  360. LLM_TENSOR_ATTN_OUT_NORM,
  361. LLM_TENSOR_ATTN_ROT_EMBD,
  362. LLM_TENSOR_FFN_GATE_INP,
  363. LLM_TENSOR_FFN_NORM,
  364. LLM_TENSOR_FFN_GATE,
  365. LLM_TENSOR_FFN_DOWN,
  366. LLM_TENSOR_FFN_UP,
  367. LLM_TENSOR_FFN_ACT,
  368. LLM_TENSOR_FFN_DOWN_EXP,
  369. LLM_TENSOR_FFN_GATE_EXP,
  370. LLM_TENSOR_FFN_UP_EXP,
  371. LLM_TENSOR_ATTN_Q_NORM,
  372. LLM_TENSOR_ATTN_K_NORM,
  373. LLM_TENSOR_LAYER_OUT_NORM,
  374. LLM_TENSOR_SSM_IN,
  375. LLM_TENSOR_SSM_CONV1D,
  376. LLM_TENSOR_SSM_X,
  377. LLM_TENSOR_SSM_DT,
  378. LLM_TENSOR_SSM_A,
  379. LLM_TENSOR_SSM_D,
  380. LLM_TENSOR_SSM_OUT,
  381. };
  382. static const std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  383. {
  384. LLM_ARCH_LLAMA,
  385. {
  386. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  387. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  388. { LLM_TENSOR_OUTPUT, "output" },
  389. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  390. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  391. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  392. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  393. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  394. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  395. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  396. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  397. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  398. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  399. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  400. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  401. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  402. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  403. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  404. },
  405. },
  406. {
  407. LLM_ARCH_BAICHUAN,
  408. {
  409. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  410. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  411. { LLM_TENSOR_OUTPUT, "output" },
  412. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  413. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  414. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  415. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  416. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  417. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  418. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  419. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  420. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  421. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  422. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  423. },
  424. },
  425. {
  426. LLM_ARCH_FALCON,
  427. {
  428. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  429. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  430. { LLM_TENSOR_OUTPUT, "output" },
  431. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  432. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  433. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  434. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  435. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  436. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  437. },
  438. },
  439. {
  440. LLM_ARCH_GPT2,
  441. {
  442. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  443. { LLM_TENSOR_POS_EMBD, "position_embd" },
  444. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  445. { LLM_TENSOR_OUTPUT, "output" },
  446. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  447. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  448. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  449. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  450. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  451. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  452. },
  453. },
  454. {
  455. LLM_ARCH_GPTJ,
  456. {
  457. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  458. },
  459. },
  460. {
  461. LLM_ARCH_GPTNEOX,
  462. {
  463. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  464. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  465. { LLM_TENSOR_OUTPUT, "output" },
  466. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  467. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  468. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  469. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  470. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  471. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  472. },
  473. },
  474. {
  475. LLM_ARCH_PERSIMMON,
  476. {
  477. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  478. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  479. { LLM_TENSOR_OUTPUT, "output"},
  480. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  481. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  482. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  483. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  484. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  485. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  486. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  487. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  488. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  489. },
  490. },
  491. {
  492. LLM_ARCH_MPT,
  493. {
  494. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  495. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  496. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  497. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  498. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  499. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  500. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  501. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  502. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  503. },
  504. },
  505. {
  506. LLM_ARCH_STARCODER,
  507. {
  508. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  509. { LLM_TENSOR_POS_EMBD, "position_embd" },
  510. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  511. { LLM_TENSOR_OUTPUT, "output" },
  512. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  513. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  514. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  515. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  516. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  517. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  518. },
  519. },
  520. {
  521. LLM_ARCH_REFACT,
  522. {
  523. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  524. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  525. { LLM_TENSOR_OUTPUT, "output" },
  526. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  527. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  528. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  529. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  530. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  531. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  532. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  533. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  534. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  535. },
  536. },
  537. {
  538. LLM_ARCH_BERT,
  539. {
  540. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  541. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  542. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  543. { LLM_TENSOR_POS_EMBD, "position_embd" },
  544. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  545. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  546. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  547. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  548. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  549. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  550. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  551. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  552. },
  553. },
  554. {
  555. LLM_ARCH_NOMIC_BERT,
  556. {
  557. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  558. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  559. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  560. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  561. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  562. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  563. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  564. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  565. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  566. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  567. },
  568. },
  569. {
  570. LLM_ARCH_BLOOM,
  571. {
  572. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  573. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  574. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  575. { LLM_TENSOR_OUTPUT, "output" },
  576. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  577. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  578. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  579. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  580. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  581. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  582. },
  583. },
  584. {
  585. LLM_ARCH_STABLELM,
  586. {
  587. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  588. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  589. { LLM_TENSOR_OUTPUT, "output" },
  590. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  591. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  592. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  593. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  594. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  595. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  596. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  597. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  598. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  599. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  600. },
  601. },
  602. {
  603. LLM_ARCH_QWEN,
  604. {
  605. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  606. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  607. { LLM_TENSOR_OUTPUT, "output" },
  608. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  609. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  610. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  611. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  612. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  613. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  614. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  615. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  616. },
  617. },
  618. {
  619. LLM_ARCH_QWEN2,
  620. {
  621. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  622. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  623. { LLM_TENSOR_OUTPUT, "output" },
  624. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  625. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  626. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  627. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  628. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  629. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  630. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  631. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  632. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  633. },
  634. },
  635. {
  636. LLM_ARCH_PHI2,
  637. {
  638. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  639. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  640. { LLM_TENSOR_OUTPUT, "output" },
  641. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  642. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  643. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  644. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  645. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  646. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  647. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  648. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  649. },
  650. },
  651. {
  652. LLM_ARCH_PLAMO,
  653. {
  654. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  655. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  656. { LLM_TENSOR_OUTPUT, "output" },
  657. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  658. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  659. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  660. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  661. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  662. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  663. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  664. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  665. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  666. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  667. },
  668. },
  669. {
  670. LLM_ARCH_CODESHELL,
  671. {
  672. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  673. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  674. { LLM_TENSOR_OUTPUT, "output" },
  675. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  676. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  677. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  678. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  679. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  680. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  681. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  682. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  683. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  684. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  685. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  686. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  687. },
  688. },
  689. {
  690. LLM_ARCH_ORION,
  691. {
  692. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  693. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  694. { LLM_TENSOR_OUTPUT, "output" },
  695. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  696. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  697. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  698. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  699. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  700. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  701. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  702. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  703. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  704. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  705. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  706. },
  707. },
  708. {
  709. LLM_ARCH_INTERNLM2,
  710. {
  711. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  712. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  713. { LLM_TENSOR_OUTPUT, "output" },
  714. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  715. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  716. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  717. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  718. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  719. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  720. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  721. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  722. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  723. },
  724. },
  725. {
  726. LLM_ARCH_MINICPM,
  727. {
  728. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  729. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  730. { LLM_TENSOR_OUTPUT, "output" },
  731. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  732. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  733. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  734. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  735. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  736. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  737. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  738. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  739. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  740. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  741. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  742. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  743. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  744. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  745. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  746. },
  747. },
  748. {
  749. LLM_ARCH_GEMMA,
  750. {
  751. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  752. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  753. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  754. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  755. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  756. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  757. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  758. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  759. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  760. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  761. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  762. },
  763. },
  764. {
  765. LLM_ARCH_STARCODER2,
  766. {
  767. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  768. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  769. { LLM_TENSOR_OUTPUT, "output" },
  770. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  771. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  772. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  773. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  774. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  775. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  776. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  777. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  778. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  779. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  780. },
  781. },
  782. {
  783. LLM_ARCH_MAMBA,
  784. {
  785. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  786. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  787. { LLM_TENSOR_OUTPUT, "output" },
  788. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  789. { LLM_TENSOR_SSM_IN, "blk.%d.ssm_in" },
  790. { LLM_TENSOR_SSM_CONV1D, "blk.%d.ssm_conv1d" },
  791. { LLM_TENSOR_SSM_X, "blk.%d.ssm_x" },
  792. { LLM_TENSOR_SSM_DT, "blk.%d.ssm_dt" },
  793. { LLM_TENSOR_SSM_A, "blk.%d.ssm_a" },
  794. { LLM_TENSOR_SSM_D, "blk.%d.ssm_d" },
  795. { LLM_TENSOR_SSM_OUT, "blk.%d.ssm_out" },
  796. },
  797. },
  798. {
  799. LLM_ARCH_UNKNOWN,
  800. {
  801. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  802. },
  803. },
  804. };
  805. static llm_arch llm_arch_from_string(const std::string & name) {
  806. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  807. if (kv.second == name) {
  808. return kv.first;
  809. }
  810. }
  811. return LLM_ARCH_UNKNOWN;
  812. }
  813. // helper to handle gguf constants
  814. // usage:
  815. //
  816. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  817. //
  818. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  819. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  820. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  821. //
  822. struct LLM_TN {
  823. LLM_TN(llm_arch arch) : arch(arch) {}
  824. llm_arch arch;
  825. std::string operator()(llm_tensor tensor) const {
  826. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  827. return "__missing__";
  828. }
  829. return LLM_TENSOR_NAMES.at(arch).at(tensor);
  830. }
  831. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  832. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  833. return "__missing__";
  834. }
  835. return LLM_TENSOR_NAMES.at(arch).at(tensor) + "." + suffix;
  836. }
  837. std::string operator()(llm_tensor tensor, int bid) const {
  838. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  839. return "__missing__";
  840. }
  841. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid);
  842. }
  843. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  844. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  845. return "__missing__";
  846. }
  847. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid) + "." + suffix;
  848. }
  849. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  850. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  851. return "__missing__";
  852. }
  853. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid, xid) + "." + suffix;
  854. }
  855. };
  856. //
  857. // gguf helpers
  858. //
  859. static const std::map<llama_rope_scaling_type, const char *> LLAMA_ROPE_SCALING_TYPES = {
  860. { LLAMA_ROPE_SCALING_TYPE_NONE, "none" },
  861. { LLAMA_ROPE_SCALING_TYPE_LINEAR, "linear" },
  862. { LLAMA_ROPE_SCALING_TYPE_YARN, "yarn" },
  863. };
  864. static llama_rope_scaling_type llama_rope_scaling_type_from_string(const std::string & name) {
  865. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  866. if (kv.second == name) {
  867. return (llama_rope_scaling_type) kv.first;
  868. }
  869. }
  870. return LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
  871. }
  872. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  873. switch (type) {
  874. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  875. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  876. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  877. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  878. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  879. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  880. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  881. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  882. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  883. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  884. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  885. default: return format("unknown type %d", type);
  886. }
  887. }
  888. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  889. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  890. switch (type) {
  891. case GGUF_TYPE_STRING:
  892. return gguf_get_val_str(ctx_gguf, i);
  893. case GGUF_TYPE_ARRAY:
  894. {
  895. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  896. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  897. const void * data = gguf_get_arr_data(ctx_gguf, i);
  898. std::stringstream ss;
  899. ss << "[";
  900. for (int j = 0; j < arr_n; j++) {
  901. if (arr_type == GGUF_TYPE_STRING) {
  902. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  903. // escape quotes
  904. replace_all(val, "\\", "\\\\");
  905. replace_all(val, "\"", "\\\"");
  906. ss << '"' << val << '"';
  907. } else if (arr_type == GGUF_TYPE_ARRAY) {
  908. ss << "???";
  909. } else {
  910. ss << gguf_data_to_str(arr_type, data, j);
  911. }
  912. if (j < arr_n - 1) {
  913. ss << ", ";
  914. }
  915. }
  916. ss << "]";
  917. return ss.str();
  918. }
  919. default:
  920. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  921. }
  922. }
  923. //
  924. // llama helpers
  925. //
  926. #if defined(_WIN32)
  927. static std::string llama_format_win_err(DWORD err) {
  928. LPSTR buf;
  929. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  930. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  931. if (!size) {
  932. return "FormatMessageA failed";
  933. }
  934. std::string ret(buf, size);
  935. LocalFree(buf);
  936. return ret;
  937. }
  938. #endif
  939. template <typename T>
  940. struct no_init {
  941. T value;
  942. no_init() { /* do nothing */ }
  943. };
  944. struct llama_file {
  945. // use FILE * so we don't have to re-open the file to mmap
  946. FILE * fp;
  947. size_t size;
  948. llama_file(const char * fname, const char * mode) {
  949. fp = std::fopen(fname, mode);
  950. if (fp == NULL) {
  951. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  952. }
  953. seek(0, SEEK_END);
  954. size = tell();
  955. seek(0, SEEK_SET);
  956. }
  957. size_t tell() const {
  958. #ifdef _WIN32
  959. __int64 ret = _ftelli64(fp);
  960. #else
  961. long ret = std::ftell(fp);
  962. #endif
  963. GGML_ASSERT(ret != -1); // this really shouldn't fail
  964. return (size_t) ret;
  965. }
  966. void seek(size_t offset, int whence) const {
  967. #ifdef _WIN32
  968. int ret = _fseeki64(fp, (__int64) offset, whence);
  969. #else
  970. int ret = std::fseek(fp, (long) offset, whence);
  971. #endif
  972. GGML_ASSERT(ret == 0); // same
  973. }
  974. void read_raw(void * ptr, size_t len) const {
  975. if (len == 0) {
  976. return;
  977. }
  978. errno = 0;
  979. std::size_t ret = std::fread(ptr, len, 1, fp);
  980. if (ferror(fp)) {
  981. throw std::runtime_error(format("read error: %s", strerror(errno)));
  982. }
  983. if (ret != 1) {
  984. throw std::runtime_error("unexpectedly reached end of file");
  985. }
  986. }
  987. uint32_t read_u32() const {
  988. uint32_t ret;
  989. read_raw(&ret, sizeof(ret));
  990. return ret;
  991. }
  992. void write_raw(const void * ptr, size_t len) const {
  993. if (len == 0) {
  994. return;
  995. }
  996. errno = 0;
  997. size_t ret = std::fwrite(ptr, len, 1, fp);
  998. if (ret != 1) {
  999. throw std::runtime_error(format("write error: %s", strerror(errno)));
  1000. }
  1001. }
  1002. void write_u32(std::uint32_t val) const {
  1003. write_raw(&val, sizeof(val));
  1004. }
  1005. ~llama_file() {
  1006. if (fp) {
  1007. std::fclose(fp);
  1008. }
  1009. }
  1010. };
  1011. struct llama_mmap {
  1012. void * addr;
  1013. size_t size;
  1014. llama_mmap(const llama_mmap &) = delete;
  1015. #ifdef _POSIX_MAPPED_FILES
  1016. static constexpr bool SUPPORTED = true;
  1017. // list of mapped fragments (first_offset, last_offset)
  1018. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  1019. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  1020. size = file->size;
  1021. int fd = fileno(file->fp);
  1022. int flags = MAP_SHARED;
  1023. // prefetch/readahead impairs performance on NUMA systems
  1024. if (numa) { prefetch = 0; }
  1025. #ifdef __linux__
  1026. // advise the kernel to read the file sequentially (increases readahead)
  1027. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  1028. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  1029. strerror(errno));
  1030. }
  1031. if (prefetch) { flags |= MAP_POPULATE; }
  1032. #endif
  1033. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  1034. if (addr == MAP_FAILED) { // NOLINT
  1035. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  1036. }
  1037. if (prefetch > 0) {
  1038. // advise the kernel to preload the mapped memory
  1039. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  1040. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  1041. strerror(errno));
  1042. }
  1043. }
  1044. if (numa) {
  1045. // advise the kernel not to use readahead
  1046. // (because the next page might not belong on the same node)
  1047. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  1048. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  1049. strerror(errno));
  1050. }
  1051. }
  1052. // initialize list of mapped_fragments
  1053. mapped_fragments.emplace_back(0, file->size);
  1054. }
  1055. static void align_range(size_t * first, size_t * last, size_t page_size) {
  1056. // align first to the next page
  1057. size_t offset_in_page = *first & (page_size - 1);
  1058. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  1059. *first += offset_to_page;
  1060. // align last to the previous page
  1061. *last = *last & ~(page_size - 1);
  1062. if (*last <= *first) {
  1063. *last = *first;
  1064. }
  1065. }
  1066. // partially unmap the file in the range [first, last)
  1067. void unmap_fragment(size_t first, size_t last) {
  1068. // note: this function must not be called multiple times with overlapping ranges
  1069. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  1070. int page_size = sysconf(_SC_PAGESIZE);
  1071. align_range(&first, &last, page_size);
  1072. size_t len = last - first;
  1073. if (len == 0) {
  1074. return;
  1075. }
  1076. GGML_ASSERT(first % page_size == 0);
  1077. GGML_ASSERT(last % page_size == 0);
  1078. GGML_ASSERT(last > first);
  1079. void * next_page_start = (uint8_t *) addr + first;
  1080. // unmap the range
  1081. if (munmap(next_page_start, len)) {
  1082. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1083. }
  1084. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  1085. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  1086. for (const auto & frag : mapped_fragments) {
  1087. if (frag.first < first && frag.second > last) {
  1088. // the range is in the middle of the fragment, split it
  1089. new_mapped_fragments.emplace_back(frag.first, first);
  1090. new_mapped_fragments.emplace_back(last, frag.second);
  1091. } else if (frag.first < first && frag.second > first) {
  1092. // the range starts in the middle of the fragment
  1093. new_mapped_fragments.emplace_back(frag.first, first);
  1094. } else if (frag.first < last && frag.second > last) {
  1095. // the range ends in the middle of the fragment
  1096. new_mapped_fragments.emplace_back(last, frag.second);
  1097. } else if (frag.first >= first && frag.second <= last) {
  1098. // the range covers the entire fragment
  1099. } else {
  1100. // the range is outside the fragment
  1101. new_mapped_fragments.push_back(frag);
  1102. }
  1103. }
  1104. mapped_fragments = std::move(new_mapped_fragments);
  1105. }
  1106. ~llama_mmap() {
  1107. for (const auto & frag : mapped_fragments) {
  1108. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  1109. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1110. }
  1111. }
  1112. }
  1113. #elif defined(_WIN32)
  1114. static constexpr bool SUPPORTED = true;
  1115. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  1116. GGML_UNUSED(numa);
  1117. size = file->size;
  1118. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  1119. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  1120. if (hMapping == NULL) {
  1121. DWORD error = GetLastError();
  1122. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  1123. }
  1124. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  1125. DWORD error = GetLastError();
  1126. CloseHandle(hMapping);
  1127. if (addr == NULL) {
  1128. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  1129. }
  1130. if (prefetch > 0) {
  1131. #if _WIN32_WINNT >= 0x602
  1132. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  1133. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  1134. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  1135. // may fail on pre-Windows 8 systems
  1136. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  1137. if (pPrefetchVirtualMemory) {
  1138. // advise the kernel to preload the mapped memory
  1139. WIN32_MEMORY_RANGE_ENTRY range;
  1140. range.VirtualAddress = addr;
  1141. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  1142. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  1143. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  1144. llama_format_win_err(GetLastError()).c_str());
  1145. }
  1146. }
  1147. #else
  1148. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  1149. #endif
  1150. }
  1151. }
  1152. void unmap_fragment(size_t first, size_t last) {
  1153. // not supported
  1154. GGML_UNUSED(first);
  1155. GGML_UNUSED(last);
  1156. }
  1157. ~llama_mmap() {
  1158. if (!UnmapViewOfFile(addr)) {
  1159. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  1160. llama_format_win_err(GetLastError()).c_str());
  1161. }
  1162. }
  1163. #else
  1164. static constexpr bool SUPPORTED = false;
  1165. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  1166. GGML_UNUSED(file);
  1167. GGML_UNUSED(prefetch);
  1168. GGML_UNUSED(numa);
  1169. throw std::runtime_error("mmap not supported");
  1170. }
  1171. void unmap_fragment(size_t first, size_t last) {
  1172. GGML_UNUSED(first);
  1173. GGML_UNUSED(last);
  1174. throw std::runtime_error("mmap not supported");
  1175. }
  1176. #endif
  1177. };
  1178. // Represents some region of memory being locked using mlock or VirtualLock;
  1179. // will automatically unlock on destruction.
  1180. struct llama_mlock {
  1181. void * addr = NULL;
  1182. size_t size = 0;
  1183. bool failed_already = false;
  1184. llama_mlock() {}
  1185. llama_mlock(const llama_mlock &) = delete;
  1186. ~llama_mlock() {
  1187. if (size) {
  1188. raw_unlock(addr, size);
  1189. }
  1190. }
  1191. void init(void * ptr) {
  1192. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1193. addr = ptr;
  1194. }
  1195. void grow_to(size_t target_size) {
  1196. GGML_ASSERT(addr);
  1197. if (failed_already) {
  1198. return;
  1199. }
  1200. size_t granularity = lock_granularity();
  1201. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1202. if (target_size > size) {
  1203. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1204. size = target_size;
  1205. } else {
  1206. failed_already = true;
  1207. }
  1208. }
  1209. }
  1210. #ifdef _POSIX_MEMLOCK_RANGE
  1211. static constexpr bool SUPPORTED = true;
  1212. static size_t lock_granularity() {
  1213. return (size_t) sysconf(_SC_PAGESIZE);
  1214. }
  1215. #ifdef __APPLE__
  1216. #define MLOCK_SUGGESTION \
  1217. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1218. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  1219. #else
  1220. #define MLOCK_SUGGESTION \
  1221. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  1222. #endif
  1223. bool raw_lock(const void * addr, size_t size) const {
  1224. if (!mlock(addr, size)) {
  1225. return true;
  1226. }
  1227. char* errmsg = std::strerror(errno);
  1228. bool suggest = (errno == ENOMEM);
  1229. // Check if the resource limit is fine after all
  1230. struct rlimit lock_limit;
  1231. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1232. suggest = false;
  1233. }
  1234. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1235. suggest = false;
  1236. }
  1237. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1238. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1239. return false;
  1240. }
  1241. #undef MLOCK_SUGGESTION
  1242. static void raw_unlock(void * addr, size_t size) {
  1243. if (munlock(addr, size)) {
  1244. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1245. }
  1246. }
  1247. #elif defined(_WIN32)
  1248. static constexpr bool SUPPORTED = true;
  1249. static size_t lock_granularity() {
  1250. SYSTEM_INFO si;
  1251. GetSystemInfo(&si);
  1252. return (size_t) si.dwPageSize;
  1253. }
  1254. bool raw_lock(void * ptr, size_t len) const {
  1255. for (int tries = 1; ; tries++) {
  1256. if (VirtualLock(ptr, len)) {
  1257. return true;
  1258. }
  1259. if (tries == 2) {
  1260. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1261. len, size, llama_format_win_err(GetLastError()).c_str());
  1262. return false;
  1263. }
  1264. // It failed but this was only the first try; increase the working
  1265. // set size and try again.
  1266. SIZE_T min_ws_size, max_ws_size;
  1267. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1268. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1269. llama_format_win_err(GetLastError()).c_str());
  1270. return false;
  1271. }
  1272. // Per MSDN: "The maximum number of pages that a process can lock
  1273. // is equal to the number of pages in its minimum working set minus
  1274. // a small overhead."
  1275. // Hopefully a megabyte is enough overhead:
  1276. size_t increment = len + 1048576;
  1277. // The minimum must be <= the maximum, so we need to increase both:
  1278. min_ws_size += increment;
  1279. max_ws_size += increment;
  1280. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1281. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1282. llama_format_win_err(GetLastError()).c_str());
  1283. return false;
  1284. }
  1285. }
  1286. }
  1287. static void raw_unlock(void * ptr, size_t len) {
  1288. if (!VirtualUnlock(ptr, len)) {
  1289. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1290. llama_format_win_err(GetLastError()).c_str());
  1291. }
  1292. }
  1293. #else
  1294. static constexpr bool SUPPORTED = false;
  1295. static size_t lock_granularity() {
  1296. return (size_t) 65536;
  1297. }
  1298. bool raw_lock(const void * addr, size_t len) const {
  1299. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1300. return false;
  1301. }
  1302. static void raw_unlock(const void * addr, size_t len) {}
  1303. #endif
  1304. };
  1305. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1306. std::vector<char> result(8, 0);
  1307. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1308. if (n_tokens < 0) {
  1309. result.resize(-n_tokens);
  1310. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1311. GGML_ASSERT(check == -n_tokens);
  1312. }
  1313. else {
  1314. result.resize(n_tokens);
  1315. }
  1316. return std::string(result.data(), result.size());
  1317. }
  1318. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1319. ggml_backend_buffer_type_t buft = nullptr;
  1320. #if defined(GGML_USE_CUBLAS)
  1321. // host buffers should only be used when data is expected to be copied to/from the GPU
  1322. if (host_buffer) {
  1323. buft = ggml_backend_cuda_host_buffer_type();
  1324. }
  1325. #elif defined(GGML_USE_SYCL)
  1326. if (host_buffer) {
  1327. buft = ggml_backend_sycl_host_buffer_type();
  1328. }
  1329. #elif defined(GGML_USE_CPU_HBM)
  1330. buft = ggml_backend_cpu_hbm_buffer_type();
  1331. #elif defined(GGML_USE_VULKAN)
  1332. if (host_buffer) {
  1333. buft = ggml_backend_vk_host_buffer_type();
  1334. }
  1335. #endif
  1336. if (buft == nullptr) {
  1337. buft = ggml_backend_cpu_buffer_type();
  1338. }
  1339. return buft;
  1340. GGML_UNUSED(host_buffer);
  1341. }
  1342. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(int gpu) {
  1343. ggml_backend_buffer_type_t buft = nullptr;
  1344. #ifdef GGML_USE_METAL
  1345. buft = ggml_backend_metal_buffer_type();
  1346. #elif defined(GGML_USE_CUBLAS)
  1347. buft = ggml_backend_cuda_buffer_type(gpu);
  1348. #elif defined(GGML_USE_VULKAN)
  1349. buft = ggml_backend_vk_buffer_type(gpu);
  1350. #elif defined(GGML_USE_SYCL)
  1351. buft = ggml_backend_sycl_buffer_type(gpu);
  1352. #elif defined(GGML_USE_CLBLAST)
  1353. buft = ggml_backend_opencl_buffer_type();
  1354. #elif defined(GGML_USE_KOMPUTE)
  1355. buft = ggml_backend_kompute_buffer_type(gpu);
  1356. if (buft == nullptr) {
  1357. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, gpu);
  1358. }
  1359. #endif
  1360. if (buft == nullptr) {
  1361. buft = llama_default_buffer_type_cpu(true);
  1362. }
  1363. return buft;
  1364. GGML_UNUSED(gpu);
  1365. }
  1366. static ggml_backend_buffer_type_t llama_default_buffer_type_split(int fallback_gpu, const float * tensor_split) {
  1367. ggml_backend_buffer_type_t buft = nullptr;
  1368. #ifdef GGML_USE_CUBLAS
  1369. if (ggml_backend_cuda_get_device_count() > 1) {
  1370. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  1371. }
  1372. #endif
  1373. #ifdef GGML_USE_SYCL
  1374. if (ggml_backend_sycl_get_device_count() > 1) {
  1375. buft = ggml_backend_sycl_split_buffer_type(tensor_split);
  1376. }
  1377. #endif
  1378. if (buft == nullptr) {
  1379. buft = llama_default_buffer_type_offload(fallback_gpu);
  1380. }
  1381. return buft;
  1382. GGML_UNUSED(tensor_split);
  1383. }
  1384. static size_t llama_get_device_count() {
  1385. #if defined(GGML_USE_CUBLAS)
  1386. return ggml_backend_cuda_get_device_count();
  1387. #elif defined(GGML_USE_SYCL)
  1388. return ggml_backend_sycl_get_device_count();
  1389. #elif defined(GGML_USE_VULKAN)
  1390. return ggml_backend_vk_get_device_count();
  1391. #else
  1392. return 1;
  1393. #endif
  1394. }
  1395. static size_t llama_get_device_memory(int device) {
  1396. #if defined(GGML_USE_CUBLAS)
  1397. size_t total;
  1398. size_t free;
  1399. ggml_backend_cuda_get_device_memory(device, &total, &free);
  1400. return free;
  1401. #elif defined(GGML_USE_SYCL)
  1402. size_t total;
  1403. size_t free;
  1404. ggml_backend_sycl_get_device_memory(device, &total, &free);
  1405. return free;
  1406. #elif defined(GGML_USE_VULKAN)
  1407. size_t total;
  1408. size_t free;
  1409. ggml_backend_vk_get_device_memory(device, &total, &free);
  1410. return free;
  1411. #else
  1412. return 1;
  1413. GGML_UNUSED(device);
  1414. #endif
  1415. }
  1416. //
  1417. // globals
  1418. //
  1419. struct llama_state {
  1420. llama_state() {
  1421. #ifdef GGML_USE_METAL
  1422. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1423. #endif
  1424. }
  1425. // We save the log callback globally
  1426. ggml_log_callback log_callback = llama_log_callback_default;
  1427. void * log_callback_user_data = nullptr;
  1428. };
  1429. static llama_state g_state;
  1430. // available llama models
  1431. enum e_model {
  1432. MODEL_UNKNOWN,
  1433. MODEL_17M,
  1434. MODEL_22M,
  1435. MODEL_33M,
  1436. MODEL_109M,
  1437. MODEL_137M,
  1438. MODEL_335M,
  1439. MODEL_0_5B,
  1440. MODEL_1B,
  1441. MODEL_2B,
  1442. MODEL_3B,
  1443. MODEL_4B,
  1444. MODEL_7B,
  1445. MODEL_8B,
  1446. MODEL_13B,
  1447. MODEL_14B,
  1448. MODEL_15B,
  1449. MODEL_20B,
  1450. MODEL_30B,
  1451. MODEL_34B,
  1452. MODEL_40B,
  1453. MODEL_65B,
  1454. MODEL_70B,
  1455. MODEL_SMALL,
  1456. MODEL_MEDIUM,
  1457. MODEL_LARGE,
  1458. MODEL_XL,
  1459. };
  1460. static const size_t kiB = 1024;
  1461. static const size_t MiB = 1024*kiB;
  1462. static const size_t GiB = 1024*MiB;
  1463. struct llama_hparams {
  1464. bool vocab_only;
  1465. bool rope_finetuned;
  1466. uint32_t n_vocab;
  1467. uint32_t n_ctx_train; // context size the model was trained on
  1468. uint32_t n_embd;
  1469. uint32_t n_head;
  1470. uint32_t n_head_kv;
  1471. uint32_t n_layer;
  1472. uint32_t n_rot;
  1473. uint32_t n_embd_head_k; // dimension of keys (d_k). d_q is assumed to be the same, but there are n_head q heads, and only n_head_kv k-v heads
  1474. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1475. uint32_t n_ff;
  1476. uint32_t n_expert = 0;
  1477. uint32_t n_expert_used = 0;
  1478. uint32_t n_vocab_type = 0; // for BERT-style token types
  1479. float f_norm_eps;
  1480. float f_norm_rms_eps;
  1481. float rope_freq_base_train;
  1482. float rope_freq_scale_train;
  1483. uint32_t n_yarn_orig_ctx;
  1484. // for State Space Models
  1485. uint32_t ssm_d_conv = 0;
  1486. uint32_t ssm_d_inner = 0;
  1487. uint32_t ssm_d_state = 0;
  1488. uint32_t ssm_dt_rank = 0;
  1489. float f_clamp_kqv = 0.0f;
  1490. float f_max_alibi_bias = 0.0f;
  1491. bool causal_attn = true;
  1492. bool need_kq_pos = false;
  1493. enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_NONE;
  1494. enum llama_rope_type rope_type = LLAMA_ROPE_TYPE_NONE;
  1495. enum llama_rope_scaling_type rope_scaling_type_train = LLAMA_ROPE_SCALING_TYPE_NONE;
  1496. bool operator!=(const llama_hparams & other) const {
  1497. if (this->vocab_only != other.vocab_only) return true;
  1498. if (this->n_vocab != other.n_vocab) return true;
  1499. if (this->n_ctx_train != other.n_ctx_train) return true;
  1500. if (this->n_embd != other.n_embd) return true;
  1501. if (this->n_head != other.n_head) return true;
  1502. if (this->n_head_kv != other.n_head_kv) return true;
  1503. if (this->n_layer != other.n_layer) return true;
  1504. if (this->n_rot != other.n_rot) return true;
  1505. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1506. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1507. if (this->n_ff != other.n_ff) return true;
  1508. if (this->n_expert != other.n_expert) return true;
  1509. if (this->n_expert_used != other.n_expert_used) return true;
  1510. if (this->rope_finetuned != other.rope_finetuned) return true;
  1511. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1512. if (this->ssm_d_conv != other.ssm_d_conv) return true;
  1513. if (this->ssm_d_inner != other.ssm_d_inner) return true;
  1514. if (this->ssm_d_state != other.ssm_d_state) return true;
  1515. if (this->ssm_dt_rank != other.ssm_dt_rank) return true;
  1516. const float EPSILON = 1e-9f;
  1517. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1518. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1519. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1520. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1521. return false;
  1522. }
  1523. uint32_t n_gqa() const {
  1524. if (n_head_kv == 0) {
  1525. return 0;
  1526. }
  1527. return n_head/n_head_kv;
  1528. }
  1529. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1530. return n_embd_head_k * n_head_kv;
  1531. }
  1532. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1533. return n_embd_head_v * n_head_kv;
  1534. }
  1535. uint32_t n_embd_k_s() const { // dimension of the rolling state embeddings
  1536. // corresponds to Mamba's conv_states size
  1537. // TODO: maybe support other convolution strides than 1
  1538. // NOTE: since the first column of the conv_state is shifted out each time, it's not actually needed
  1539. return (ssm_d_conv > 0 ? ssm_d_conv - 1 : 0) * ssm_d_inner;
  1540. }
  1541. uint32_t n_embd_v_s() const { // dimension of the recurrent state embeddings
  1542. // corresponds to Mamba's ssm_states size
  1543. return ssm_d_state * ssm_d_inner;
  1544. }
  1545. };
  1546. struct llama_cparams {
  1547. uint32_t n_ctx; // context size used during inference
  1548. uint32_t n_batch;
  1549. uint32_t n_ubatch;
  1550. uint32_t n_threads; // number of threads to use for generation
  1551. uint32_t n_threads_batch; // number of threads to use for batch processing
  1552. float rope_freq_base;
  1553. float rope_freq_scale;
  1554. uint32_t n_yarn_orig_ctx;
  1555. // These hyperparameters are not exposed in GGUF, because all
  1556. // existing YaRN models use the same values for them.
  1557. float yarn_ext_factor;
  1558. float yarn_attn_factor;
  1559. float yarn_beta_fast;
  1560. float yarn_beta_slow;
  1561. float defrag_thold;
  1562. bool embeddings;
  1563. bool causal_attn;
  1564. bool offload_kqv;
  1565. enum llama_pooling_type pooling_type;
  1566. ggml_backend_sched_eval_callback cb_eval;
  1567. void * cb_eval_user_data;
  1568. };
  1569. struct llama_layer {
  1570. // normalization
  1571. struct ggml_tensor * attn_norm;
  1572. struct ggml_tensor * attn_norm_b;
  1573. struct ggml_tensor * attn_norm_2;
  1574. struct ggml_tensor * attn_norm_2_b;
  1575. struct ggml_tensor * attn_q_norm;
  1576. struct ggml_tensor * attn_q_norm_b;
  1577. struct ggml_tensor * attn_k_norm;
  1578. struct ggml_tensor * attn_k_norm_b;
  1579. struct ggml_tensor * attn_out_norm;
  1580. struct ggml_tensor * attn_out_norm_b;
  1581. // attention
  1582. struct ggml_tensor * wq;
  1583. struct ggml_tensor * wk;
  1584. struct ggml_tensor * wv;
  1585. struct ggml_tensor * wo;
  1586. struct ggml_tensor * wqkv;
  1587. // attention bias
  1588. struct ggml_tensor * bq;
  1589. struct ggml_tensor * bk;
  1590. struct ggml_tensor * bv;
  1591. struct ggml_tensor * bo;
  1592. struct ggml_tensor * bqkv;
  1593. // normalization
  1594. struct ggml_tensor * ffn_norm;
  1595. struct ggml_tensor * ffn_norm_b;
  1596. struct ggml_tensor * layer_out_norm;
  1597. struct ggml_tensor * layer_out_norm_b;
  1598. // ff
  1599. struct ggml_tensor * ffn_gate; // w1
  1600. struct ggml_tensor * ffn_down; // w2
  1601. struct ggml_tensor * ffn_up; // w3
  1602. // ff MoE
  1603. struct ggml_tensor * ffn_gate_inp;
  1604. struct ggml_tensor * ffn_gate_exp[LLAMA_MAX_EXPERTS];
  1605. struct ggml_tensor * ffn_down_exp[LLAMA_MAX_EXPERTS];
  1606. struct ggml_tensor * ffn_up_exp [LLAMA_MAX_EXPERTS];
  1607. // ff bias
  1608. struct ggml_tensor * ffn_down_b; // b2
  1609. struct ggml_tensor * ffn_up_b; // b3
  1610. struct ggml_tensor * ffn_act;
  1611. // mamba proj
  1612. struct ggml_tensor * ssm_in;
  1613. struct ggml_tensor * ssm_x;
  1614. struct ggml_tensor * ssm_dt;
  1615. struct ggml_tensor * ssm_out;
  1616. // mamba
  1617. struct ggml_tensor * ssm_conv1d;
  1618. struct ggml_tensor * ssm_a;
  1619. struct ggml_tensor * ssm_d;
  1620. // mamba bias
  1621. struct ggml_tensor * ssm_conv1d_b;
  1622. struct ggml_tensor * ssm_dt_b;
  1623. };
  1624. struct llama_kv_cell {
  1625. llama_pos pos = -1;
  1626. llama_pos delta = 0;
  1627. int32_t src = 0; // used by recurrent state models to copy states
  1628. std::set<llama_seq_id> seq_id;
  1629. bool has_seq_id(const llama_seq_id & id) const {
  1630. return seq_id.find(id) != seq_id.end();
  1631. }
  1632. bool is_empty() const {
  1633. return seq_id.empty();
  1634. }
  1635. bool is_same_seq(const llama_kv_cell & other) const {
  1636. return seq_id == other.seq_id;
  1637. }
  1638. };
  1639. // ring-buffer of cached KV data
  1640. struct llama_kv_cache {
  1641. bool has_shift = false;
  1642. bool do_defrag = false;
  1643. bool do_copy = false;
  1644. // with recurrent state models, a cell can hold the state for more than one past token
  1645. bool recurrent = false;
  1646. // Note: The value of head isn't only used to optimize searching
  1647. // for a free KV slot. llama_decode_internal also uses it, so it
  1648. // cannot be freely changed after a slot has been allocated.
  1649. uint32_t head = 0;
  1650. uint32_t size = 0;
  1651. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1652. // computed before each graph build
  1653. uint32_t n = 0;
  1654. ggml_type type_k = GGML_TYPE_F16;
  1655. ggml_type type_v = GGML_TYPE_F16;
  1656. std::vector<llama_kv_cell> cells;
  1657. std::vector<struct ggml_tensor *> k_l; // per layer
  1658. std::vector<struct ggml_tensor *> v_l;
  1659. std::vector<struct ggml_context *> ctxs;
  1660. std::vector<ggml_backend_buffer_t> bufs;
  1661. size_t total_size() const {
  1662. size_t size = 0;
  1663. for (ggml_backend_buffer_t buf : bufs) {
  1664. size += ggml_backend_buffer_get_size(buf);
  1665. }
  1666. return size;
  1667. }
  1668. ~llama_kv_cache() {
  1669. for (struct ggml_context * ctx : ctxs) {
  1670. ggml_free(ctx);
  1671. }
  1672. for (ggml_backend_buffer_t buf : bufs) {
  1673. ggml_backend_buffer_free(buf);
  1674. }
  1675. }
  1676. };
  1677. struct llama_vocab {
  1678. using id = int32_t;
  1679. using token = std::string;
  1680. using ttype = llama_token_type;
  1681. struct token_data {
  1682. token text;
  1683. float score;
  1684. ttype type;
  1685. };
  1686. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1687. std::unordered_map<token, id> token_to_id;
  1688. std::vector<token_data> id_to_token;
  1689. std::unordered_map<token, id> special_tokens_cache;
  1690. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1691. // default LLaMA special tokens
  1692. id special_bos_id = 1;
  1693. id special_eos_id = 2;
  1694. id special_unk_id = 0;
  1695. id special_sep_id = -1;
  1696. id special_pad_id = -1;
  1697. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1698. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1699. id linefeed_id = 13;
  1700. id special_prefix_id = 32007;
  1701. id special_middle_id = 32009;
  1702. id special_suffix_id = 32008;
  1703. id special_eot_id = 32010;
  1704. bool add_space_prefix = true;
  1705. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1706. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1707. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1708. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1709. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1710. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1711. if (it == bpe_ranks.end()) {
  1712. return -1;
  1713. }
  1714. return it->second;
  1715. }
  1716. };
  1717. struct llama_model {
  1718. e_model type = MODEL_UNKNOWN;
  1719. llm_arch arch = LLM_ARCH_UNKNOWN;
  1720. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1721. std::string name = "n/a";
  1722. llama_hparams hparams = {};
  1723. llama_vocab vocab;
  1724. struct ggml_tensor * tok_embd;
  1725. struct ggml_tensor * type_embd;
  1726. struct ggml_tensor * pos_embd;
  1727. struct ggml_tensor * tok_norm;
  1728. struct ggml_tensor * tok_norm_b;
  1729. struct ggml_tensor * output_norm;
  1730. struct ggml_tensor * output_norm_b;
  1731. struct ggml_tensor * output;
  1732. struct ggml_tensor * output_b;
  1733. std::vector<llama_layer> layers;
  1734. llama_split_mode split_mode;
  1735. int main_gpu;
  1736. int n_gpu_layers;
  1737. // gguf metadata
  1738. std::unordered_map<std::string, std::string> gguf_kv;
  1739. // layer -> buffer type mapping
  1740. struct layer_buft {
  1741. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1742. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1743. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1744. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1745. ggml_backend_buffer_type_t buft; // everything else
  1746. };
  1747. layer_buft buft_input;
  1748. layer_buft buft_output;
  1749. std::vector<layer_buft> buft_layer;
  1750. // contexts where the model tensors metadata is stored
  1751. std::vector<struct ggml_context *> ctxs;
  1752. // the model memory buffers for the tensor data
  1753. std::vector<ggml_backend_buffer_t> bufs;
  1754. // model memory mapped file
  1755. std::unique_ptr<llama_mmap> mapping;
  1756. // objects representing data potentially being locked in memory
  1757. std::vector<std::unique_ptr<llama_mlock>> mlock_bufs;
  1758. llama_mlock mlock_mmap;
  1759. // for quantize-stats only
  1760. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1761. int64_t t_load_us = 0;
  1762. int64_t t_start_us = 0;
  1763. ~llama_model() {
  1764. for (struct ggml_context * ctx : ctxs) {
  1765. ggml_free(ctx);
  1766. }
  1767. for (ggml_backend_buffer_t buf : bufs) {
  1768. ggml_backend_buffer_free(buf);
  1769. }
  1770. }
  1771. };
  1772. struct llama_context {
  1773. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1774. ~llama_context() {
  1775. ggml_backend_sched_free(sched);
  1776. for (ggml_backend_t backend : backends) {
  1777. ggml_backend_free(backend);
  1778. }
  1779. #ifdef GGML_USE_VULKAN
  1780. ggml_vk_free_cpu_assist();
  1781. #endif
  1782. ggml_backend_buffer_free(buf_output);
  1783. }
  1784. llama_cparams cparams;
  1785. std::vector<ggml_backend_t> backends;
  1786. #ifdef GGML_USE_METAL
  1787. ggml_backend_t backend_metal = nullptr;
  1788. #endif
  1789. ggml_backend_t backend_cpu = nullptr;
  1790. const llama_model & model;
  1791. // key + value cache for the self attention
  1792. struct llama_kv_cache kv_self;
  1793. std::mt19937 rng;
  1794. bool has_evaluated_once = false;
  1795. int64_t t_start_us;
  1796. int64_t t_load_us;
  1797. int64_t t_sample_us = 0;
  1798. int64_t t_p_eval_us = 0;
  1799. int64_t t_eval_us = 0;
  1800. int64_t t_compute_start_us = 0;
  1801. int64_t n_queued_tokens = 0;
  1802. int32_t n_sample = 0; // number of tokens sampled
  1803. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1804. int32_t n_eval = 0; // number of eval calls
  1805. // host buffer for the model output (logits and embeddings)
  1806. ggml_backend_buffer_t buf_output = nullptr;
  1807. // decode output (2-dimensional array: [n_tokens][n_vocab])
  1808. size_t logits_size = 0;
  1809. float * logits = nullptr;
  1810. #ifndef NDEBUG
  1811. // guard against access to unset logits
  1812. std::vector<bool> logits_valid;
  1813. #endif
  1814. bool logits_all = false;
  1815. // embeddings output (2-dimensional array: [n_tokens][n_embd])
  1816. // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE
  1817. size_t embd_size = 0;
  1818. float * embd = nullptr;
  1819. // sequence embeddings output (map of [n_embd] vectors)
  1820. // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE
  1821. std::map<llama_seq_id, std::vector<float>> embd_seq;
  1822. // memory buffers used to evaluate the model
  1823. std::vector<uint8_t> buf_compute_meta;
  1824. ggml_backend_sched_t sched = nullptr;
  1825. ggml_abort_callback abort_callback = nullptr;
  1826. void * abort_callback_data = nullptr;
  1827. // input tensors
  1828. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  1829. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  1830. struct ggml_tensor * inp_pos; // I32 [n_batch]
  1831. struct ggml_tensor * inp_KQ_mask; // F32 [kv_size, n_batch]
  1832. struct ggml_tensor * inp_KQ_pos; // F32 [kv_size]
  1833. struct ggml_tensor * inp_K_shift; // I32 [kv_size]
  1834. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  1835. struct ggml_tensor * inp_cls; // I32 [n_batch]
  1836. struct ggml_tensor * inp_s_copy; // I32 [kv_size]
  1837. struct ggml_tensor * inp_s_mask; // F32 [1, kv_size]
  1838. struct ggml_tensor * inp_s_seq; // I32 [kv_size, n_batch]
  1839. #ifdef GGML_USE_MPI
  1840. ggml_mpi_context * ctx_mpi = NULL;
  1841. #endif
  1842. };
  1843. //
  1844. // kv cache helpers
  1845. //
  1846. static bool llama_kv_cache_init(
  1847. struct llama_kv_cache & cache,
  1848. const llama_model & model,
  1849. ggml_type type_k,
  1850. ggml_type type_v,
  1851. uint32_t kv_size,
  1852. bool offload) {
  1853. const struct llama_hparams & hparams = model.hparams;
  1854. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  1855. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  1856. const int64_t n_layer = hparams.n_layer;
  1857. cache.has_shift = false;
  1858. // TODO: find a nicer way to add other recurrent model architectures
  1859. cache.recurrent = model.arch == LLM_ARCH_MAMBA;
  1860. // TODO: support mixed reccurent Transformer architectues
  1861. // NOTE: (!a || b) is a logical implication (a -> b)
  1862. GGML_ASSERT(!cache.recurrent || n_embd_k_gqa == hparams.n_embd_k_s());
  1863. GGML_ASSERT(!cache.recurrent || n_embd_v_gqa == hparams.n_embd_v_s());
  1864. GGML_ASSERT( cache.recurrent || n_embd_k_gqa == hparams.n_embd_k_gqa());
  1865. GGML_ASSERT( cache.recurrent || n_embd_v_gqa == hparams.n_embd_v_gqa());
  1866. cache.head = 0;
  1867. cache.size = kv_size;
  1868. cache.used = 0;
  1869. cache.type_k = type_k;
  1870. cache.type_v = type_v;
  1871. cache.cells.clear();
  1872. cache.cells.resize(kv_size);
  1873. if (cache.recurrent) {
  1874. // init state copy sources
  1875. for (uint32_t i = 0; i < cache.size; ++i) {
  1876. cache.cells[i].src = i;
  1877. }
  1878. }
  1879. #ifdef GGML_USE_CLBLAST
  1880. offload = false;
  1881. #endif
  1882. // count used buffer types
  1883. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  1884. if (offload) {
  1885. for (int64_t i = 0; i < n_layer; ++i) {
  1886. buft_layer_count[model.buft_layer[i].buft]++;
  1887. }
  1888. } else {
  1889. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  1890. }
  1891. // create a context for each buffer type
  1892. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  1893. for (auto & it : buft_layer_count) {
  1894. int n_layers = it.second;
  1895. struct ggml_init_params params = {
  1896. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  1897. /*.mem_buffer =*/ NULL,
  1898. /*.no_alloc =*/ true,
  1899. };
  1900. ggml_context * ctx = ggml_init(params);
  1901. if (!ctx) {
  1902. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  1903. return false;
  1904. }
  1905. ctx_map[it.first] = ctx;
  1906. cache.ctxs.push_back(ctx);
  1907. }
  1908. cache.k_l.reserve(n_layer);
  1909. cache.v_l.reserve(n_layer);
  1910. for (int i = 0; i < (int) n_layer; i++) {
  1911. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  1912. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  1913. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*kv_size);
  1914. ggml_format_name(k, "cache_k_l%d", i);
  1915. ggml_format_name(v, "cache_v_l%d", i);
  1916. cache.k_l.push_back(k);
  1917. cache.v_l.push_back(v);
  1918. }
  1919. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  1920. for (auto it : ctx_map) {
  1921. ggml_backend_buffer_type_t buft = it.first;
  1922. ggml_context * ctx = it.second;
  1923. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  1924. if (!buf) {
  1925. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  1926. return false;
  1927. }
  1928. ggml_backend_buffer_clear(buf, 0);
  1929. LLAMA_LOG_INFO("%s: %10s KV buffer size = %8.2f MiB\n", __func__, ggml_backend_buffer_name(buf), ggml_backend_buffer_get_size(buf)/1024.0/1024.0);
  1930. cache.bufs.push_back(buf);
  1931. }
  1932. return true;
  1933. }
  1934. // find an empty slot of size "n_tokens" in the cache
  1935. // updates the cache head
  1936. // Note: On success, it's important that cache.head points
  1937. // to the first cell of the slot.
  1938. static bool llama_kv_cache_find_slot(
  1939. struct llama_kv_cache & cache,
  1940. const struct llama_batch & batch) {
  1941. const uint32_t n_ctx = cache.size;
  1942. const uint32_t n_tokens = batch.n_tokens;
  1943. if (cache.recurrent) {
  1944. // For recurrent state architectures (like Mamba),
  1945. // each KV cache cell can store the state for a whole sequence.
  1946. llama_seq_id min = cache.size - 1;
  1947. llama_seq_id max = 0;
  1948. for (uint32_t i = 0; i < n_tokens; ++i) {
  1949. for (int32_t j = 0; j < batch.n_seq_id[i]; ++j) {
  1950. llama_seq_id seq_id = batch.seq_id[i][j];
  1951. // make sure it's a valid seq_id
  1952. if ((uint32_t) seq_id < cache.size) {
  1953. if (seq_id > max) {
  1954. max = seq_id;
  1955. }
  1956. if (seq_id < min) {
  1957. min = seq_id;
  1958. }
  1959. // Assuming the tokens are in-order
  1960. if (batch.pos[i] != cache.cells[seq_id].pos + 1) {
  1961. // What should happen when the pos backtracks or skips a value?
  1962. // Clearing the state mid-batch would require special-casing which isn't done.
  1963. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d\n",
  1964. __func__, batch.pos[i], cache.cells[seq_id].pos, seq_id);
  1965. }
  1966. if (cache.cells[seq_id].pos < 0 && 0 <= batch.pos[i]) {
  1967. cache.used += 1;
  1968. }
  1969. cache.cells[seq_id].pos = batch.pos[i];
  1970. // NOTE: seq_ids are not inserted here; they are handled when the input tensors are set
  1971. } else {
  1972. // too big seq_id
  1973. // TODO: would it be possible to resize the KV cache size instead?
  1974. LLAMA_LOG_ERROR("%s: seq_id=%d >= kv_size=%d Try using a bigger --parallel value\n", __func__, seq_id, cache.size);
  1975. return false;
  1976. }
  1977. }
  1978. }
  1979. // allow getting the range of used cells, from head to head + n
  1980. cache.head = min;
  1981. cache.n = max - min + 1;
  1982. // sanity check
  1983. return max >= min;
  1984. }
  1985. // otherwise, one cell per token.
  1986. if (n_tokens > n_ctx) {
  1987. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  1988. return false;
  1989. }
  1990. uint32_t n_tested = 0;
  1991. while (true) {
  1992. if (cache.head + n_tokens > n_ctx) {
  1993. n_tested += n_ctx - cache.head;
  1994. cache.head = 0;
  1995. continue;
  1996. }
  1997. bool found = true;
  1998. for (uint32_t i = 0; i < n_tokens; i++) {
  1999. if (cache.cells[cache.head + i].pos >= 0) {
  2000. found = false;
  2001. cache.head += i + 1;
  2002. n_tested += i + 1;
  2003. break;
  2004. }
  2005. }
  2006. if (found) {
  2007. break;
  2008. }
  2009. if (n_tested >= n_ctx) {
  2010. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  2011. return false;
  2012. }
  2013. }
  2014. for (uint32_t i = 0; i < n_tokens; i++) {
  2015. cache.cells[cache.head + i].pos = batch.pos[i];
  2016. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  2017. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  2018. }
  2019. }
  2020. cache.used += n_tokens;
  2021. return true;
  2022. }
  2023. // find how many cells are currently in use
  2024. static uint32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  2025. for (uint32_t i = cache.size; i > 0; --i) {
  2026. const llama_kv_cell & cell = cache.cells[i - 1];
  2027. if (cell.pos >= 0 && !cell.is_empty()) {
  2028. return i;
  2029. }
  2030. }
  2031. return 0;
  2032. }
  2033. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  2034. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  2035. cache.cells[i].pos = -1;
  2036. cache.cells[i].seq_id.clear();
  2037. }
  2038. cache.head = 0;
  2039. cache.used = 0;
  2040. }
  2041. static bool llama_kv_cache_seq_rm(
  2042. struct llama_kv_cache & cache,
  2043. llama_seq_id seq_id,
  2044. llama_pos p0,
  2045. llama_pos p1) {
  2046. uint32_t new_head = cache.size;
  2047. if (p0 < 0) p0 = 0;
  2048. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2049. // models like Mamba can't have a state partially erased
  2050. if (cache.recurrent) {
  2051. if (seq_id >= (int64_t) cache.size) {
  2052. // could be fatal
  2053. return false;
  2054. }
  2055. if (0 <= seq_id) {
  2056. // partial intersection is invalid
  2057. if ((0 < p0 && p0 <= cache.cells[seq_id].pos) || (0 < p1 && p1 <= cache.cells[seq_id].pos)) {
  2058. return false;
  2059. }
  2060. } else {
  2061. // seq_id is negative, then the range should include everything or nothing
  2062. if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
  2063. return false;
  2064. }
  2065. }
  2066. }
  2067. for (uint32_t i = 0; i < cache.size; ++i) {
  2068. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2069. if (seq_id < 0) {
  2070. cache.cells[i].seq_id.clear();
  2071. } else if (cache.cells[i].has_seq_id(seq_id)) {
  2072. cache.cells[i].seq_id.erase(seq_id);
  2073. } else {
  2074. continue;
  2075. }
  2076. if (cache.cells[i].is_empty()) {
  2077. // keep count of the number of used cells
  2078. if (cache.cells[i].pos >= 0) cache.used--;
  2079. cache.cells[i].pos = -1;
  2080. if (new_head == cache.size) new_head = i;
  2081. }
  2082. }
  2083. }
  2084. // If we freed up a slot, set head to it so searching can start there.
  2085. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2086. return true;
  2087. }
  2088. static void llama_kv_cache_seq_cp(
  2089. struct llama_kv_cache & cache,
  2090. llama_seq_id seq_id_src,
  2091. llama_seq_id seq_id_dst,
  2092. llama_pos p0,
  2093. llama_pos p1) {
  2094. if (p0 < 0) p0 = 0;
  2095. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2096. if (cache.recurrent) {
  2097. if ((uint32_t) seq_id_dst < cache.size && (uint32_t) seq_id_src < cache.size) {
  2098. seq_id_src = cache.cells[seq_id_src].src;
  2099. GGML_ASSERT((uint32_t) seq_id_src < cache.size);
  2100. // intent to "copy from"
  2101. // supports copy chains thanks to taking the source of the source
  2102. cache.cells[seq_id_dst].src = seq_id_src;
  2103. // preserve the "keep or clear" status of the copied sequence
  2104. if (cache.cells[seq_id_src].has_seq_id(seq_id_src)) {
  2105. cache.cells[seq_id_dst].seq_id.insert(seq_id_dst);
  2106. } else {
  2107. cache.cells[seq_id_dst].seq_id.erase(seq_id_dst);
  2108. }
  2109. cache.do_copy = true;
  2110. cache.cells[seq_id_dst].pos = cache.cells[seq_id_src].pos;
  2111. }
  2112. return;
  2113. }
  2114. // otherwise, this is the KV cache of a Transformer-like model
  2115. cache.head = 0;
  2116. for (uint32_t i = 0; i < cache.size; ++i) {
  2117. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2118. cache.cells[i].seq_id.insert(seq_id_dst);
  2119. }
  2120. }
  2121. }
  2122. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2123. uint32_t new_head = cache.size;
  2124. for (uint32_t i = 0; i < cache.size; ++i) {
  2125. if (!cache.cells[i].has_seq_id(seq_id)) {
  2126. if (cache.cells[i].pos >= 0) cache.used--;
  2127. cache.cells[i].pos = -1;
  2128. cache.cells[i].seq_id.clear();
  2129. if (new_head == cache.size) new_head = i;
  2130. } else {
  2131. cache.cells[i].seq_id.clear();
  2132. cache.cells[i].seq_id.insert(seq_id);
  2133. }
  2134. }
  2135. // If we freed up a slot, set head to it so searching can start there.
  2136. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2137. }
  2138. static void llama_kv_cache_seq_add(
  2139. struct llama_kv_cache & cache,
  2140. llama_seq_id seq_id,
  2141. llama_pos p0,
  2142. llama_pos p1,
  2143. llama_pos delta) {
  2144. uint32_t new_head = cache.size;
  2145. if (p0 < 0) p0 = 0;
  2146. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2147. if (cache.recurrent) {
  2148. // for Mamba-like models, only the pos needs to be shifted
  2149. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2150. llama_kv_cell & cell = cache.cells[seq_id];
  2151. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2152. cell.pos += delta;
  2153. }
  2154. }
  2155. return;
  2156. }
  2157. for (uint32_t i = 0; i < cache.size; ++i) {
  2158. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2159. cache.has_shift = true;
  2160. cache.cells[i].pos += delta;
  2161. cache.cells[i].delta += delta;
  2162. if (cache.cells[i].pos < 0) {
  2163. if (!cache.cells[i].is_empty()) {
  2164. cache.used--;
  2165. }
  2166. cache.cells[i].pos = -1;
  2167. cache.cells[i].seq_id.clear();
  2168. if (new_head == cache.size) {
  2169. new_head = i;
  2170. }
  2171. }
  2172. }
  2173. }
  2174. // If we freed up a slot, set head to it so searching can start there.
  2175. // Otherwise we just start the next search from the beginning.
  2176. cache.head = new_head != cache.size ? new_head : 0;
  2177. }
  2178. static void llama_kv_cache_seq_div(
  2179. struct llama_kv_cache & cache,
  2180. llama_seq_id seq_id,
  2181. llama_pos p0,
  2182. llama_pos p1,
  2183. int d) {
  2184. if (p0 < 0) p0 = 0;
  2185. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2186. if (cache.recurrent) {
  2187. // for Mamba-like models, only the pos needs to be changed
  2188. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2189. llama_kv_cell & cell = cache.cells[seq_id];
  2190. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2191. cell.pos /= d;
  2192. }
  2193. }
  2194. return;
  2195. }
  2196. for (uint32_t i = 0; i < cache.size; ++i) {
  2197. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2198. cache.has_shift = true;
  2199. {
  2200. llama_pos p_old = cache.cells[i].pos;
  2201. cache.cells[i].pos /= d;
  2202. cache.cells[i].delta += cache.cells[i].pos - p_old;
  2203. }
  2204. }
  2205. }
  2206. }
  2207. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2208. llama_pos result = 0;
  2209. for (uint32_t i = 0; i < cache.size; ++i) {
  2210. if (cache.cells[i].has_seq_id(seq_id)) {
  2211. result = std::max(result, cache.cells[i].pos);
  2212. }
  2213. }
  2214. return result;
  2215. }
  2216. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  2217. cache.do_defrag = true;
  2218. }
  2219. //
  2220. // model loading and saving
  2221. //
  2222. enum llama_fver {
  2223. GGUF_FILE_VERSION_V1 = 1,
  2224. GGUF_FILE_VERSION_V2 = 2,
  2225. GGUF_FILE_VERSION_V3 = 3,
  2226. };
  2227. static const char * llama_file_version_name(llama_fver version) {
  2228. switch (version) {
  2229. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  2230. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  2231. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  2232. }
  2233. return "unknown";
  2234. }
  2235. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  2236. char buf[256];
  2237. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  2238. for (size_t i = 1; i < ne.size(); i++) {
  2239. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  2240. }
  2241. return buf;
  2242. }
  2243. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  2244. char buf[256];
  2245. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  2246. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  2247. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  2248. }
  2249. return buf;
  2250. }
  2251. namespace GGUFMeta {
  2252. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  2253. struct GKV_Base_Type {
  2254. static constexpr gguf_type gt = gt_;
  2255. static T getter(const gguf_context * ctx, const int kid) {
  2256. return gfun(ctx, kid);
  2257. }
  2258. };
  2259. template<typename T> struct GKV_Base;
  2260. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  2261. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  2262. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  2263. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  2264. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  2265. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  2266. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  2267. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  2268. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  2269. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  2270. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  2271. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  2272. template<> struct GKV_Base<std::string> {
  2273. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  2274. static std::string getter(const gguf_context * ctx, const int kid) {
  2275. return gguf_get_val_str(ctx, kid);
  2276. }
  2277. };
  2278. struct ArrayInfo {
  2279. const gguf_type gt;
  2280. const size_t length;
  2281. const void * data;
  2282. };
  2283. template<> struct GKV_Base<ArrayInfo> {
  2284. public:
  2285. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  2286. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  2287. return ArrayInfo {
  2288. gguf_get_arr_type(ctx, k),
  2289. size_t(gguf_get_arr_n(ctx, k)),
  2290. gguf_get_arr_data(ctx, k),
  2291. };
  2292. }
  2293. };
  2294. template<typename T>
  2295. class GKV : public GKV_Base<T> {
  2296. GKV() = delete;
  2297. public:
  2298. static T get_kv(const gguf_context * ctx, const int k) {
  2299. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  2300. if (kt != GKV::gt) {
  2301. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  2302. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  2303. }
  2304. return GKV::getter(ctx, k);
  2305. }
  2306. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  2307. switch (ty) {
  2308. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  2309. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  2310. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  2311. }
  2312. return "unknown";
  2313. }
  2314. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  2315. if (!ovrd) { return false; }
  2316. if (ovrd->tag == expected_type) {
  2317. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  2318. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  2319. switch (ovrd->tag) {
  2320. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  2321. LLAMA_LOG_INFO("%s\n", ovrd->bool_value ? "true" : "false");
  2322. } break;
  2323. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  2324. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->int_value);
  2325. } break;
  2326. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  2327. LLAMA_LOG_INFO("%.6f\n", ovrd->float_value);
  2328. } break;
  2329. default:
  2330. // Shouldn't be possible to end up here, but just in case...
  2331. throw std::runtime_error(
  2332. format("Unsupported attempt to override %s type for metadata key %s\n",
  2333. override_type_to_str(ovrd->tag), ovrd->key));
  2334. }
  2335. return true;
  2336. }
  2337. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  2338. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  2339. return false;
  2340. }
  2341. template<typename OT>
  2342. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  2343. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2344. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  2345. target = ovrd->bool_value;
  2346. return true;
  2347. }
  2348. return false;
  2349. }
  2350. template<typename OT>
  2351. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  2352. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2353. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  2354. target = ovrd->int_value;
  2355. return true;
  2356. }
  2357. return false;
  2358. }
  2359. template<typename OT>
  2360. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  2361. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2362. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  2363. target = ovrd->float_value;
  2364. return true;
  2365. }
  2366. return false;
  2367. }
  2368. template<typename OT>
  2369. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  2370. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2371. (void)target;
  2372. (void)ovrd;
  2373. if (!ovrd) { return false; }
  2374. // Currently, we should never end up here so it would be a bug if we do.
  2375. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  2376. ovrd ? ovrd->key : "NULL"));
  2377. }
  2378. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2379. if (try_override<T>(target, ovrd)) {
  2380. return true;
  2381. }
  2382. if (k < 0) { return false; }
  2383. target = get_kv(ctx, k);
  2384. return true;
  2385. }
  2386. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2387. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  2388. }
  2389. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2390. return set(ctx, key.c_str(), target, ovrd);
  2391. }
  2392. };
  2393. }
  2394. struct llama_model_loader {
  2395. int n_kv = 0;
  2396. int n_tensors = 0;
  2397. int n_created = 0;
  2398. int64_t n_elements = 0;
  2399. size_t n_bytes = 0;
  2400. bool use_mmap = false;
  2401. llama_file file;
  2402. llama_ftype ftype;
  2403. llama_fver fver;
  2404. std::unique_ptr<llama_mmap> mapping;
  2405. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  2406. struct gguf_context * ctx_gguf = NULL;
  2407. struct ggml_context * ctx_meta = NULL;
  2408. std::string arch_name;
  2409. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  2410. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) : file(fname.c_str(), "rb") {
  2411. int trace = 0;
  2412. if (getenv("LLAMA_TRACE")) {
  2413. trace = atoi(getenv("LLAMA_TRACE"));
  2414. }
  2415. struct gguf_init_params params = {
  2416. /*.no_alloc = */ true,
  2417. /*.ctx = */ &ctx_meta,
  2418. };
  2419. if (param_overrides_p != nullptr) {
  2420. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  2421. kv_overrides.insert({std::string(p->key), *p});
  2422. }
  2423. }
  2424. ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  2425. if (!ctx_gguf) {
  2426. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  2427. }
  2428. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  2429. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  2430. n_kv = gguf_get_n_kv(ctx_gguf);
  2431. n_tensors = gguf_get_n_tensors(ctx_gguf);
  2432. fver = (enum llama_fver ) gguf_get_version(ctx_gguf);
  2433. for (int i = 0; i < n_tensors; i++) {
  2434. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  2435. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, name);
  2436. n_elements += ggml_nelements(t);
  2437. n_bytes += ggml_nbytes(t);
  2438. }
  2439. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  2440. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  2441. // determine file type based on the number of tensors for each quantization and print meta data
  2442. // TODO: make optional
  2443. {
  2444. std::map<enum ggml_type, uint32_t> n_type;
  2445. uint32_t n_type_max = 0;
  2446. enum ggml_type type_max = GGML_TYPE_F32;
  2447. for (int i = 0; i < n_tensors; i++) {
  2448. enum ggml_type type = gguf_get_tensor_type(ctx_gguf, i);
  2449. n_type[type]++;
  2450. if (n_type_max < n_type[type]) {
  2451. n_type_max = n_type[type];
  2452. type_max = type;
  2453. }
  2454. if (trace > 0) {
  2455. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2456. LLAMA_LOG_INFO("%s: - tensor %4d: %32s %-8s [ %s ]\n", __func__, i, ggml_get_name(meta), ggml_type_name(type), llama_format_tensor_shape(meta).c_str());
  2457. }
  2458. }
  2459. switch (type_max) {
  2460. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  2461. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  2462. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  2463. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  2464. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  2465. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  2466. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  2467. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  2468. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  2469. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  2470. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  2471. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  2472. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  2473. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  2474. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  2475. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  2476. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  2477. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  2478. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  2479. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  2480. default:
  2481. {
  2482. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  2483. ftype = LLAMA_FTYPE_ALL_F32;
  2484. } break;
  2485. }
  2486. // this is a way to mark that we have "guessed" the file type
  2487. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  2488. {
  2489. const int kid = gguf_find_key(ctx_gguf, "general.file_type");
  2490. if (kid >= 0) {
  2491. ftype = (llama_ftype) gguf_get_val_u32(ctx_gguf, kid);
  2492. }
  2493. }
  2494. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2495. for (int i = 0; i < n_kv; i++) {
  2496. const char * name = gguf_get_key(ctx_gguf, i);
  2497. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  2498. const std::string type_name =
  2499. type == GGUF_TYPE_ARRAY
  2500. ? 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))
  2501. : gguf_type_name(type);
  2502. std::string value = gguf_kv_to_str(ctx_gguf, i);
  2503. const size_t MAX_VALUE_LEN = 40;
  2504. if (value.size() > MAX_VALUE_LEN) {
  2505. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2506. }
  2507. replace_all(value, "\n", "\\n");
  2508. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2509. }
  2510. // print type counts
  2511. for (auto & kv : n_type) {
  2512. if (kv.second == 0) {
  2513. continue;
  2514. }
  2515. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2516. }
  2517. }
  2518. if (!llama_mmap::SUPPORTED) {
  2519. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2520. use_mmap = false;
  2521. }
  2522. this->use_mmap = use_mmap;
  2523. }
  2524. ~llama_model_loader() {
  2525. if (ctx_gguf) {
  2526. gguf_free(ctx_gguf);
  2527. }
  2528. if (ctx_meta) {
  2529. ggml_free(ctx_meta);
  2530. }
  2531. }
  2532. template<typename T>
  2533. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2534. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2535. const int kid = gguf_find_key(ctx_gguf, key.c_str());
  2536. if (kid < 0) {
  2537. if (required) {
  2538. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2539. }
  2540. return false;
  2541. }
  2542. struct GGUFMeta::ArrayInfo arr_info =
  2543. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(ctx_gguf, kid);
  2544. result = arr_info.length;
  2545. return true;
  2546. }
  2547. template<typename T>
  2548. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2549. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2550. return get_arr_n(llm_kv(kid), result, required);
  2551. }
  2552. template<typename T>
  2553. bool get_key(const std::string & key, T & result, const bool required = true) {
  2554. auto it = kv_overrides.find(key);
  2555. const struct llama_model_kv_override * override =
  2556. it != kv_overrides.end() ? &it->second : nullptr;
  2557. const bool found = GGUFMeta::GKV<T>::set(ctx_gguf, key, result, override);
  2558. if (required && !found) {
  2559. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2560. }
  2561. return found;
  2562. }
  2563. template<typename T>
  2564. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2565. return get_key(llm_kv(kid), result, required);
  2566. }
  2567. std::string get_arch_name() const {
  2568. return arch_name;
  2569. }
  2570. enum llm_arch get_arch() const {
  2571. return llm_kv.arch;
  2572. }
  2573. const char * get_tensor_name(int i) const {
  2574. return gguf_get_tensor_name(ctx_gguf, i);
  2575. }
  2576. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2577. return ggml_get_tensor(ctx_meta, name);
  2578. }
  2579. struct ggml_tensor * get_tensor_meta(int i) const {
  2580. return get_tensor_meta(get_tensor_name(i));
  2581. }
  2582. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, struct ggml_tensor * meta) {
  2583. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
  2584. ggml_set_name(tensor, ggml_get_name(meta));
  2585. n_created++;
  2586. return tensor;
  2587. }
  2588. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  2589. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, name.c_str());
  2590. if (cur == NULL) {
  2591. if (!required) {
  2592. return NULL;
  2593. }
  2594. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2595. }
  2596. {
  2597. bool is_ok = true;
  2598. for (size_t i = 0; i < ne.size(); ++i) {
  2599. if (ne[i] != cur->ne[i]) {
  2600. is_ok = false;
  2601. break;
  2602. }
  2603. }
  2604. if (!is_ok) {
  2605. throw std::runtime_error(
  2606. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2607. __func__, name.c_str(),
  2608. llama_format_tensor_shape(ne).c_str(),
  2609. llama_format_tensor_shape(cur).c_str()));
  2610. }
  2611. }
  2612. return create_tensor_for(ctx, cur);
  2613. }
  2614. void done_getting_tensors() const {
  2615. if (n_created != n_tensors) {
  2616. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  2617. }
  2618. }
  2619. size_t file_offset(const char * name) const {
  2620. const int idx = gguf_find_tensor(ctx_gguf, name);
  2621. if (idx < 0) {
  2622. throw std::runtime_error(format("%s: tensor '%s' not found in the file", __func__, name));
  2623. }
  2624. return gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, idx);
  2625. }
  2626. void init_mapping(bool prefetch = true, llama_mlock * lmlock = nullptr) {
  2627. // prefetch the whole file - all the data is needed anyway
  2628. if (use_mmap) {
  2629. mapping.reset(new llama_mmap(&file, prefetch ? -1 : 0, ggml_is_numa()));
  2630. }
  2631. // compute the total size of all tensors for progress reporting
  2632. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2633. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2634. size_data += ggml_nbytes(cur);
  2635. }
  2636. if (use_mmap && mapping) {
  2637. if (lmlock) {
  2638. lmlock->init(mapping->addr);
  2639. }
  2640. mmap_used_first = mapping->size;
  2641. }
  2642. }
  2643. void get_mapping_range(size_t * first, size_t * last, ggml_context * ctx) const {
  2644. GGML_ASSERT(mapping);
  2645. *first = mapping->size;
  2646. *last = 0;
  2647. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  2648. const size_t offs = file_offset(ggml_get_name(tensor));
  2649. *first = std::min(*first, offs);
  2650. *last = std::max(*last, offs + ggml_nbytes(tensor));
  2651. }
  2652. }
  2653. // for backwards compatibility, does not support ggml-backend
  2654. void load_data_for(struct ggml_tensor * cur) const {
  2655. const size_t offs = file_offset(ggml_get_name(cur));
  2656. if (use_mmap && mapping) {
  2657. if (cur->data == nullptr) {
  2658. cur->data = (uint8_t *)mapping->addr + offs;
  2659. } else {
  2660. memcpy(cur->data, (uint8_t *)mapping->addr + offs, ggml_nbytes(cur));
  2661. }
  2662. } else {
  2663. GGML_ASSERT(cur->data != nullptr);
  2664. file.seek(offs, SEEK_SET);
  2665. file.read_raw(cur->data, ggml_nbytes(cur));
  2666. }
  2667. }
  2668. size_t size_done = 0;
  2669. size_t size_data = 0;
  2670. size_t mmap_used_first = -1;
  2671. size_t mmap_used_last = 0;
  2672. // Returns false if cancelled by progress_callback
  2673. 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) {
  2674. GGML_ASSERT(size_data != 0 && "call init_mapping() first");
  2675. std::vector<no_init<uint8_t>> read_buf;
  2676. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  2677. if (progress_callback) {
  2678. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2679. return false;
  2680. }
  2681. }
  2682. const size_t offs = file_offset(ggml_get_name(cur));
  2683. if (use_mmap && mapping) {
  2684. if (buf_mmap && cur->data == nullptr) {
  2685. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + offs);
  2686. if (lmlock) {
  2687. lmlock->grow_to(offs + ggml_nbytes(cur));
  2688. }
  2689. mmap_used_first = std::min(mmap_used_first, offs);
  2690. mmap_used_last = std::max(mmap_used_last, offs + ggml_nbytes(cur));
  2691. } else {
  2692. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + offs, 0, ggml_nbytes(cur));
  2693. }
  2694. } else {
  2695. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2696. file.seek(offs, SEEK_SET);
  2697. file.read_raw(cur->data, ggml_nbytes(cur));
  2698. } else {
  2699. read_buf.resize(ggml_nbytes(cur));
  2700. file.seek(offs, SEEK_SET);
  2701. file.read_raw(read_buf.data(), ggml_nbytes(cur));
  2702. ggml_backend_tensor_set(cur, read_buf.data(), 0, ggml_nbytes(cur));
  2703. }
  2704. }
  2705. size_done += ggml_nbytes(cur);
  2706. }
  2707. // check if this is the last call and do final cleanup
  2708. if (size_done >= size_data) {
  2709. // unmap offloaded tensors and metadata
  2710. if (use_mmap && mapping) {
  2711. mapping->unmap_fragment(0, mmap_used_first);
  2712. if (mmap_used_last != 0) {
  2713. mapping->unmap_fragment(mmap_used_last, mapping->size);
  2714. }
  2715. }
  2716. if (progress_callback) {
  2717. // Even though the model is done loading, we still honor
  2718. // cancellation since we need to free allocations.
  2719. return progress_callback(1.0f, progress_callback_user_data);
  2720. }
  2721. }
  2722. return true;
  2723. }
  2724. };
  2725. template<>
  2726. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  2727. uint32_t tmp;
  2728. const bool found = get_key(kid, tmp, required);
  2729. if (found) {
  2730. result = (enum llama_pooling_type) tmp;
  2731. } else {
  2732. result = LLAMA_POOLING_TYPE_UNSPECIFIED;
  2733. }
  2734. return found;
  2735. }
  2736. //
  2737. // load LLaMA models
  2738. //
  2739. static const char * llama_model_arch_name(llm_arch arch) {
  2740. auto it = LLM_ARCH_NAMES.find(arch);
  2741. if (it == LLM_ARCH_NAMES.end()) {
  2742. return "unknown";
  2743. }
  2744. return it->second;
  2745. }
  2746. static std::string llama_model_ftype_name(llama_ftype ftype) {
  2747. if (ftype & LLAMA_FTYPE_GUESSED) {
  2748. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  2749. }
  2750. switch (ftype) {
  2751. case LLAMA_FTYPE_ALL_F32: return "all F32";
  2752. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  2753. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  2754. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  2755. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  2756. return "Q4_1, some F16";
  2757. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  2758. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  2759. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  2760. // K-quants
  2761. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  2762. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  2763. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  2764. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  2765. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  2766. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  2767. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  2768. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  2769. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  2770. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  2771. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XXS - 2.0625 bpw";
  2772. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  2773. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  2774. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  2775. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  2776. case LLAMA_FTYPE_MOSTLY_IQ3_XXS:return "IQ3_XXS - 3.0625 bpw";
  2777. case LLAMA_FTYPE_MOSTLY_IQ1_S :return "IQ1_S - 1.5625 bpw";
  2778. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  2779. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  2780. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  2781. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  2782. default: return "unknown, may not work";
  2783. }
  2784. }
  2785. static const char * llama_model_type_name(e_model type) {
  2786. switch (type) {
  2787. case MODEL_22M: return "22M";
  2788. case MODEL_33M: return "33M";
  2789. case MODEL_109M: return "109M";
  2790. case MODEL_137M: return "137M";
  2791. case MODEL_0_5B: return "0.5B";
  2792. case MODEL_1B: return "1B";
  2793. case MODEL_2B: return "2B";
  2794. case MODEL_3B: return "3B";
  2795. case MODEL_7B: return "7B";
  2796. case MODEL_8B: return "8B";
  2797. case MODEL_13B: return "13B";
  2798. case MODEL_14B: return "14B";
  2799. case MODEL_15B: return "15B";
  2800. case MODEL_20B: return "20B";
  2801. case MODEL_30B: return "30B";
  2802. case MODEL_34B: return "34B";
  2803. case MODEL_40B: return "40B";
  2804. case MODEL_65B: return "65B";
  2805. case MODEL_70B: return "70B";
  2806. case MODEL_SMALL: return "0.1B";
  2807. case MODEL_MEDIUM: return "0.4B";
  2808. case MODEL_LARGE: return "0.8B";
  2809. case MODEL_XL: return "1.5B";
  2810. default: return "?B";
  2811. }
  2812. }
  2813. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  2814. switch (type) {
  2815. case LLAMA_VOCAB_TYPE_NONE: return "no vocab";
  2816. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  2817. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  2818. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  2819. default: return "unknown";
  2820. }
  2821. }
  2822. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  2823. model.arch = ml.get_arch();
  2824. if (model.arch == LLM_ARCH_UNKNOWN) {
  2825. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  2826. }
  2827. }
  2828. static void llm_load_hparams(
  2829. llama_model_loader & ml,
  2830. llama_model & model) {
  2831. auto & hparams = model.hparams;
  2832. const gguf_context * ctx = ml.ctx_gguf;
  2833. // get metadata as string
  2834. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  2835. enum gguf_type type = gguf_get_kv_type(ctx, i);
  2836. if (type == GGUF_TYPE_ARRAY) {
  2837. continue;
  2838. }
  2839. const char * name = gguf_get_key(ctx, i);
  2840. const std::string value = gguf_kv_to_str(ctx, i);
  2841. model.gguf_kv.emplace(name, value);
  2842. }
  2843. // get general kv
  2844. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  2845. // get hparams kv
  2846. ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab, false) || ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  2847. ml.get_key(LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  2848. ml.get_key(LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  2849. ml.get_key(LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  2850. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  2851. ml.get_key(LLM_KV_BLOCK_COUNT, hparams.n_layer);
  2852. ml.get_key(LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  2853. ml.get_key(LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  2854. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  2855. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  2856. if (hparams.n_expert > 0) {
  2857. GGML_ASSERT(hparams.n_expert_used > 0);
  2858. } else {
  2859. GGML_ASSERT(hparams.n_expert_used == 0);
  2860. }
  2861. // n_head_kv is optional, default to n_head
  2862. hparams.n_head_kv = hparams.n_head;
  2863. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  2864. bool rope_finetuned = false;
  2865. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  2866. hparams.rope_finetuned = rope_finetuned;
  2867. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  2868. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  2869. // rope_freq_base (optional)
  2870. hparams.rope_freq_base_train = 10000.0f;
  2871. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  2872. std::string rope_scaling("linear");
  2873. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  2874. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  2875. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  2876. // rope_freq_scale (inverse of the kv) is optional
  2877. float ropescale = 0.0f;
  2878. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  2879. // try the old key name
  2880. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  2881. }
  2882. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  2883. // sanity check for n_rot (optional)
  2884. {
  2885. hparams.n_rot = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  2886. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  2887. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  2888. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  2889. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  2890. }
  2891. }
  2892. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  2893. // gpt-j n_rot = rotary_dim
  2894. }
  2895. hparams.n_embd_head_k = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  2896. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  2897. hparams.n_embd_head_v = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  2898. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  2899. // arch-specific KVs
  2900. switch (model.arch) {
  2901. case LLM_ARCH_LLAMA:
  2902. {
  2903. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2904. switch (hparams.n_layer) {
  2905. case 22: model.type = e_model::MODEL_1B; break;
  2906. case 26: model.type = e_model::MODEL_3B; break;
  2907. case 32: model.type = e_model::MODEL_7B; break;
  2908. case 40: model.type = e_model::MODEL_13B; break;
  2909. case 48: model.type = e_model::MODEL_34B; break;
  2910. case 60: model.type = e_model::MODEL_30B; break;
  2911. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  2912. default: model.type = e_model::MODEL_UNKNOWN;
  2913. }
  2914. } break;
  2915. case LLM_ARCH_MINICPM:
  2916. {
  2917. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2918. switch (hparams.n_layer) {
  2919. case 40: model.type = e_model::MODEL_2B; break;
  2920. default: model.type = e_model::MODEL_UNKNOWN;
  2921. }
  2922. } break;
  2923. case LLM_ARCH_FALCON:
  2924. {
  2925. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2926. switch (hparams.n_layer) {
  2927. case 32: model.type = e_model::MODEL_7B; break;
  2928. case 60: model.type = e_model::MODEL_40B; break;
  2929. default: model.type = e_model::MODEL_UNKNOWN;
  2930. }
  2931. } break;
  2932. case LLM_ARCH_BAICHUAN:
  2933. {
  2934. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2935. switch (hparams.n_layer) {
  2936. case 32: model.type = e_model::MODEL_7B; break;
  2937. case 40: model.type = e_model::MODEL_13B; break;
  2938. default: model.type = e_model::MODEL_UNKNOWN;
  2939. }
  2940. if (model.type == e_model::MODEL_13B) {
  2941. // TODO: become GGUF KV parameter
  2942. hparams.f_max_alibi_bias = 8.0f;
  2943. }
  2944. } break;
  2945. case LLM_ARCH_STARCODER:
  2946. {
  2947. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2948. switch (hparams.n_layer) {
  2949. case 24: model.type = e_model::MODEL_1B; break;
  2950. case 36: model.type = e_model::MODEL_3B; break;
  2951. case 42: model.type = e_model::MODEL_7B; break;
  2952. case 40: model.type = e_model::MODEL_15B; break;
  2953. default: model.type = e_model::MODEL_UNKNOWN;
  2954. }
  2955. } break;
  2956. case LLM_ARCH_PERSIMMON:
  2957. {
  2958. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2959. switch (hparams.n_layer) {
  2960. case 36: model.type = e_model::MODEL_8B; break;
  2961. default: model.type = e_model::MODEL_UNKNOWN;
  2962. }
  2963. } break;
  2964. case LLM_ARCH_REFACT:
  2965. {
  2966. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2967. switch (hparams.n_layer) {
  2968. case 32: model.type = e_model::MODEL_1B; break;
  2969. default: model.type = e_model::MODEL_UNKNOWN;
  2970. }
  2971. // TODO: become GGUF KV parameter
  2972. hparams.f_max_alibi_bias = 8.0f;
  2973. } break;
  2974. case LLM_ARCH_BERT:
  2975. {
  2976. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2977. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  2978. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  2979. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  2980. switch (hparams.n_layer) {
  2981. case 3:
  2982. model.type = e_model::MODEL_17M; break; // bge-micro
  2983. case 6:
  2984. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  2985. case 12:
  2986. switch (hparams.n_embd) {
  2987. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  2988. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  2989. } break;
  2990. case 24:
  2991. model.type = e_model::MODEL_335M; break; // bge-large
  2992. }
  2993. } break;
  2994. case LLM_ARCH_NOMIC_BERT:
  2995. {
  2996. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2997. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  2998. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  2999. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  3000. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  3001. model.type = e_model::MODEL_137M;
  3002. }
  3003. } break;
  3004. case LLM_ARCH_BLOOM:
  3005. {
  3006. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3007. switch (hparams.n_layer) {
  3008. case 24: model.type = e_model::MODEL_1B; break;
  3009. case 30:
  3010. switch (hparams.n_embd) {
  3011. case 2560: model.type = e_model::MODEL_3B; break;
  3012. case 4096: model.type = e_model::MODEL_7B; break;
  3013. } break;
  3014. }
  3015. // TODO: become GGUF KV parameter
  3016. hparams.f_max_alibi_bias = 8.0f;
  3017. } break;
  3018. case LLM_ARCH_MPT:
  3019. {
  3020. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3021. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  3022. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  3023. switch (hparams.n_layer) {
  3024. case 32: model.type = e_model::MODEL_7B; break;
  3025. case 48: model.type = e_model::MODEL_30B; break;
  3026. default: model.type = e_model::MODEL_UNKNOWN;
  3027. }
  3028. } break;
  3029. case LLM_ARCH_STABLELM:
  3030. {
  3031. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3032. switch (hparams.n_layer) {
  3033. case 24: model.type = e_model::MODEL_1B; break;
  3034. case 32: model.type = e_model::MODEL_3B; break;
  3035. default: model.type = e_model::MODEL_UNKNOWN;
  3036. }
  3037. } break;
  3038. case LLM_ARCH_QWEN:
  3039. {
  3040. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3041. switch (hparams.n_layer) {
  3042. case 32: model.type = e_model::MODEL_7B; break;
  3043. case 40: model.type = e_model::MODEL_13B; break;
  3044. default: model.type = e_model::MODEL_UNKNOWN;
  3045. }
  3046. } break;
  3047. case LLM_ARCH_QWEN2:
  3048. {
  3049. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3050. switch (hparams.n_layer) {
  3051. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  3052. case 32: model.type = e_model::MODEL_7B; break;
  3053. case 40: model.type = hparams.n_head == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  3054. case 80: model.type = e_model::MODEL_70B; break;
  3055. default: model.type = e_model::MODEL_UNKNOWN;
  3056. }
  3057. } break;
  3058. case LLM_ARCH_PHI2:
  3059. {
  3060. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3061. switch (hparams.n_layer) {
  3062. case 24: model.type = e_model::MODEL_1B; break;
  3063. case 32: model.type = e_model::MODEL_3B; break;
  3064. default: model.type = e_model::MODEL_UNKNOWN;
  3065. }
  3066. } break;
  3067. case LLM_ARCH_PLAMO:
  3068. {
  3069. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3070. switch (hparams.n_layer) {
  3071. case 40: model.type = e_model::MODEL_13B; break;
  3072. default: model.type = e_model::MODEL_UNKNOWN;
  3073. }
  3074. } break;
  3075. case LLM_ARCH_GPT2:
  3076. {
  3077. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3078. switch (hparams.n_layer) {
  3079. case 12: model.type = e_model::MODEL_SMALL; break;
  3080. case 24: model.type = e_model::MODEL_MEDIUM; break;
  3081. case 36: model.type = e_model::MODEL_LARGE; break;
  3082. case 48: model.type = e_model::MODEL_XL; break;
  3083. default: model.type = e_model::MODEL_UNKNOWN;
  3084. }
  3085. } break;
  3086. case LLM_ARCH_CODESHELL:
  3087. {
  3088. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3089. switch (hparams.n_layer) {
  3090. case 42: model.type = e_model::MODEL_SMALL; break;
  3091. default: model.type = e_model::MODEL_UNKNOWN;
  3092. }
  3093. } break;
  3094. case LLM_ARCH_ORION:
  3095. {
  3096. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3097. switch (hparams.n_layer) {
  3098. case 40: model.type = e_model::MODEL_14B; break;
  3099. default: model.type = e_model::MODEL_UNKNOWN;
  3100. }
  3101. } break;
  3102. case LLM_ARCH_INTERNLM2:
  3103. {
  3104. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3105. switch (hparams.n_layer) {
  3106. case 32: model.type = e_model::MODEL_7B; break;
  3107. case 48: model.type = e_model::MODEL_20B; break;
  3108. default: model.type = e_model::MODEL_UNKNOWN;
  3109. }
  3110. } break;
  3111. case LLM_ARCH_GEMMA:
  3112. {
  3113. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3114. switch (hparams.n_layer) {
  3115. case 18: model.type = e_model::MODEL_2B; break;
  3116. case 28: model.type = e_model::MODEL_7B; break;
  3117. default: model.type = e_model::MODEL_UNKNOWN;
  3118. }
  3119. } break;
  3120. case LLM_ARCH_STARCODER2:
  3121. {
  3122. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3123. switch (hparams.n_layer) {
  3124. case 30: model.type = e_model::MODEL_3B; break;
  3125. case 32: model.type = e_model::MODEL_7B; break;
  3126. case 40: model.type = e_model::MODEL_15B; break;
  3127. default: model.type = e_model::MODEL_UNKNOWN;
  3128. }
  3129. } break;
  3130. case LLM_ARCH_MAMBA:
  3131. {
  3132. ml.get_key(LLM_KV_SSM_CONV_KERNEL, hparams.ssm_d_conv);
  3133. ml.get_key(LLM_KV_SSM_INNER_SIZE, hparams.ssm_d_inner);
  3134. ml.get_key(LLM_KV_SSM_STATE_SIZE, hparams.ssm_d_state);
  3135. ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
  3136. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3137. switch (hparams.n_layer) {
  3138. case 24:
  3139. switch (hparams.n_embd) {
  3140. case 768: model.type = e_model::MODEL_SMALL; break;
  3141. default: model.type = e_model::MODEL_UNKNOWN;
  3142. } break;
  3143. case 48:
  3144. switch (hparams.n_embd) {
  3145. case 1024: model.type = e_model::MODEL_MEDIUM; break;
  3146. case 1536: model.type = e_model::MODEL_LARGE; break;
  3147. case 2048: model.type = e_model::MODEL_XL; break;
  3148. default: model.type = e_model::MODEL_UNKNOWN;
  3149. } break;
  3150. case 64:
  3151. switch (hparams.n_embd) {
  3152. case 2560: model.type = e_model::MODEL_3B; break;
  3153. default: model.type = e_model::MODEL_UNKNOWN;
  3154. } break;
  3155. default: model.type = e_model::MODEL_UNKNOWN;
  3156. }
  3157. } break;
  3158. default: (void)0;
  3159. }
  3160. model.ftype = ml.ftype;
  3161. if (hparams.f_max_alibi_bias > 0.0f) {
  3162. hparams.need_kq_pos = true;
  3163. }
  3164. hparams.rope_type = llama_rope_type(&model);
  3165. }
  3166. // TODO: This should probably be in llama.h
  3167. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  3168. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  3169. static void llm_load_vocab(
  3170. llama_model_loader & ml,
  3171. llama_model & model) {
  3172. auto & vocab = model.vocab;
  3173. struct gguf_context * ctx = ml.ctx_gguf;
  3174. const auto kv = LLM_KV(model.arch);
  3175. // determine vocab type
  3176. {
  3177. std::string tokenizer_name;
  3178. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  3179. if (tokenizer_name == "no_vocab") {
  3180. vocab.type = LLAMA_VOCAB_TYPE_NONE;
  3181. // default special tokens
  3182. vocab.special_bos_id = -1;
  3183. vocab.special_eos_id = -1;
  3184. vocab.special_unk_id = -1;
  3185. vocab.special_sep_id = -1;
  3186. vocab.special_pad_id = -1;
  3187. vocab.linefeed_id = -1;
  3188. return;
  3189. } else if (tokenizer_name == "llama") {
  3190. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  3191. // default special tokens
  3192. vocab.special_bos_id = 1;
  3193. vocab.special_eos_id = 2;
  3194. vocab.special_unk_id = 0;
  3195. vocab.special_sep_id = -1;
  3196. vocab.special_pad_id = -1;
  3197. const int add_space_prefix_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_ADD_PREFIX).c_str());
  3198. if (add_space_prefix_keyidx != -1) {
  3199. vocab.add_space_prefix = gguf_get_val_bool(ctx, add_space_prefix_keyidx);
  3200. } // The default value of add_space_prefix is true.
  3201. } else if (tokenizer_name == "gpt2") {
  3202. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  3203. // read bpe merges and populate bpe ranks
  3204. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  3205. if (merges_keyidx == -1) {
  3206. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  3207. }
  3208. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  3209. for (int i = 0; i < n_merges; i++) {
  3210. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  3211. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  3212. std::string first;
  3213. std::string second;
  3214. const size_t pos = word.find(' ', 1);
  3215. if (pos != std::string::npos) {
  3216. first = word.substr(0, pos);
  3217. second = word.substr(pos + 1);
  3218. }
  3219. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  3220. }
  3221. // default special tokens
  3222. vocab.special_bos_id = 11;
  3223. vocab.special_eos_id = 11;
  3224. vocab.special_unk_id = -1;
  3225. vocab.special_sep_id = -1;
  3226. vocab.special_pad_id = -1;
  3227. } else if (tokenizer_name == "bert") {
  3228. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  3229. // default special tokens
  3230. vocab.special_bos_id = 101;
  3231. vocab.special_eos_id = 102;
  3232. vocab.special_unk_id = 100;
  3233. vocab.special_sep_id = -1;
  3234. vocab.special_pad_id = -1;
  3235. vocab.add_space_prefix = false;
  3236. } else {
  3237. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  3238. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  3239. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  3240. }
  3241. }
  3242. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  3243. if (token_idx == -1) {
  3244. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  3245. }
  3246. const float * scores = nullptr;
  3247. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  3248. if (score_idx != -1) {
  3249. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  3250. }
  3251. const int * toktypes = nullptr;
  3252. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  3253. if (toktype_idx != -1) {
  3254. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  3255. }
  3256. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  3257. vocab.id_to_token.resize(n_vocab);
  3258. for (uint32_t i = 0; i < n_vocab; i++) {
  3259. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  3260. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  3261. vocab.token_to_id[word] = i;
  3262. auto & token_data = vocab.id_to_token[i];
  3263. token_data.text = std::move(word);
  3264. token_data.score = scores ? scores[i] : 0.0f;
  3265. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  3266. }
  3267. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  3268. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  3269. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  3270. try {
  3271. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  3272. } catch (const std::exception & e) {
  3273. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  3274. vocab.linefeed_id = vocab.special_pad_id;
  3275. }
  3276. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  3277. vocab.linefeed_id = vocab.special_pad_id;
  3278. } else {
  3279. const std::vector<int> ids = llama_tokenize_internal(vocab, "\u010A", false);
  3280. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  3281. vocab.linefeed_id = ids[0];
  3282. }
  3283. // special tokens
  3284. {
  3285. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  3286. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  3287. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  3288. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  3289. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  3290. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  3291. };
  3292. for (const auto & it : special_token_types) {
  3293. const std::string & key = kv(std::get<0>(it));
  3294. int32_t & id = std::get<1>(it);
  3295. uint32_t new_id;
  3296. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  3297. continue;
  3298. }
  3299. if (new_id >= vocab.id_to_token.size()) {
  3300. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  3301. __func__, key.c_str(), new_id, id);
  3302. } else {
  3303. id = new_id;
  3304. }
  3305. }
  3306. // Handle add_bos_token and add_eos_token
  3307. {
  3308. bool temp = true;
  3309. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  3310. vocab.special_add_bos = int(temp);
  3311. }
  3312. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  3313. vocab.special_add_eos = int(temp);
  3314. }
  3315. }
  3316. }
  3317. // build special tokens cache
  3318. {
  3319. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  3320. // and will always be correctly labeled in 'added_tokens.json' etc.
  3321. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  3322. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  3323. // are special tokens.
  3324. // From testing, this appears to correlate 1:1 with special tokens.
  3325. //
  3326. // Counting special tokens and verifying in only one direction
  3327. // is sufficient to detect difference in those two sets.
  3328. //
  3329. uint32_t special_tokens_count_by_type = 0;
  3330. uint32_t special_tokens_count_from_verification = 0;
  3331. bool special_tokens_definition_mismatch = false;
  3332. for (const auto & t : vocab.token_to_id) {
  3333. const auto & token = t.first;
  3334. const auto & id = t.second;
  3335. // Count all non-normal tokens in the vocab while iterating
  3336. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  3337. special_tokens_count_by_type++;
  3338. }
  3339. // Skip single character tokens
  3340. if (token.length() > 1) {
  3341. bool is_tokenizable = false;
  3342. // Split token string representation in two, in all possible ways
  3343. // and check if both halves can be matched to a valid token
  3344. for (unsigned i = 1; i < token.length();) {
  3345. const auto left = token.substr(0, i);
  3346. const auto right = token.substr(i);
  3347. // check if we didnt partition in the middle of a utf sequence
  3348. auto utf = utf8_len(left.at(left.length() - 1));
  3349. if (utf == 1) {
  3350. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  3351. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  3352. is_tokenizable = true;
  3353. break;
  3354. }
  3355. i++;
  3356. } else {
  3357. // skip over the rest of multibyte utf sequence
  3358. i += utf - 1;
  3359. }
  3360. }
  3361. if (!is_tokenizable) {
  3362. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  3363. // it's faster to re-filter them here, since there are way less candidates now
  3364. // Calculate a total "utf" length of a token string representation
  3365. size_t utf8_str_len = 0;
  3366. for (unsigned i = 0; i < token.length();) {
  3367. utf8_str_len++;
  3368. i += utf8_len(token.at(i));
  3369. }
  3370. // And skip the ones which are one character
  3371. if (utf8_str_len > 1) {
  3372. // At this point what we have left are special tokens only
  3373. vocab.special_tokens_cache[token] = id;
  3374. // Count manually found special tokens
  3375. special_tokens_count_from_verification++;
  3376. // If this manually found special token is not marked as such, flag a mismatch
  3377. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  3378. special_tokens_definition_mismatch = true;
  3379. }
  3380. }
  3381. }
  3382. }
  3383. }
  3384. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  3385. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  3386. __func__,
  3387. special_tokens_count_from_verification, vocab.id_to_token.size(),
  3388. special_tokens_count_by_type, vocab.id_to_token.size()
  3389. );
  3390. } else {
  3391. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  3392. __func__,
  3393. special_tokens_count_from_verification, vocab.id_to_token.size()
  3394. );
  3395. }
  3396. }
  3397. }
  3398. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  3399. const auto & hparams = model.hparams;
  3400. const auto & vocab = model.vocab;
  3401. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  3402. // hparams
  3403. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  3404. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  3405. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  3406. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  3407. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  3408. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  3409. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  3410. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  3411. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  3412. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  3413. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  3414. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  3415. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  3416. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  3417. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  3418. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  3419. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  3420. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  3421. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  3422. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  3423. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  3424. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  3425. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  3426. LLAMA_LOG_INFO("%s: causal attn = %d\n", __func__, hparams.causal_attn);
  3427. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  3428. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  3429. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  3430. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  3431. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  3432. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  3433. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  3434. LLAMA_LOG_INFO("%s: ssm_d_conv = %u\n", __func__, hparams.ssm_d_conv);
  3435. LLAMA_LOG_INFO("%s: ssm_d_inner = %u\n", __func__, hparams.ssm_d_inner);
  3436. LLAMA_LOG_INFO("%s: ssm_d_state = %u\n", __func__, hparams.ssm_d_state);
  3437. LLAMA_LOG_INFO("%s: ssm_dt_rank = %u\n", __func__, hparams.ssm_dt_rank);
  3438. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  3439. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  3440. if (ml.n_elements >= 1e12) {
  3441. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  3442. } else if (ml.n_elements >= 1e9) {
  3443. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  3444. } else if (ml.n_elements >= 1e6) {
  3445. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  3446. } else {
  3447. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  3448. }
  3449. if (ml.n_bytes < GiB) {
  3450. 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);
  3451. } else {
  3452. 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);
  3453. }
  3454. // general kv
  3455. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  3456. // special tokens
  3457. 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() ); }
  3458. 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() ); }
  3459. 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() ); }
  3460. 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() ); }
  3461. 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() ); }
  3462. 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() ); }
  3463. }
  3464. // Returns false if cancelled by progress_callback
  3465. static bool llm_load_tensors(
  3466. llama_model_loader & ml,
  3467. llama_model & model,
  3468. int n_gpu_layers,
  3469. enum llama_split_mode split_mode,
  3470. int main_gpu,
  3471. const float * tensor_split,
  3472. bool use_mlock,
  3473. llama_progress_callback progress_callback,
  3474. void * progress_callback_user_data) {
  3475. model.t_start_us = ggml_time_us();
  3476. auto & hparams = model.hparams;
  3477. model.split_mode = split_mode;
  3478. model.main_gpu = main_gpu;
  3479. model.n_gpu_layers = n_gpu_layers;
  3480. const int64_t n_layer = hparams.n_layer;
  3481. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  3482. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  3483. model.buft_input = llama_default_buffer_type_cpu(true);
  3484. //model.buft_input = llama_default_buffer_type_offload(main_gpu);
  3485. model.buft_layer.resize(n_layer);
  3486. // assign cpu layers
  3487. for (int64_t i = 0; i < i_gpu_start; ++i) {
  3488. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  3489. }
  3490. if (split_mode == LLAMA_SPLIT_MODE_LAYER) {
  3491. // calculate the split points
  3492. int device_count = llama_get_device_count();
  3493. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  3494. std::vector<float> splits(device_count);
  3495. if (all_zero) {
  3496. // default split, by free memory
  3497. for (int i = 0; i < device_count; ++i) {
  3498. splits[i] = llama_get_device_memory(i);
  3499. }
  3500. } else {
  3501. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  3502. }
  3503. // sum and normalize the splits to get the split points
  3504. float split_sum = 0.0f;
  3505. for (int i = 0; i < device_count; ++i) {
  3506. split_sum += splits[i];
  3507. splits[i] = split_sum;
  3508. }
  3509. for (int i = 0; i < device_count; ++i) {
  3510. splits[i] /= split_sum;
  3511. }
  3512. // assign the repeating layers to the devices according to the splits
  3513. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  3514. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3515. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  3516. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  3517. }
  3518. // assign the output layer
  3519. if (n_gpu_layers > n_layer) {
  3520. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  3521. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  3522. } else {
  3523. model.buft_output = llama_default_buffer_type_cpu(true);
  3524. }
  3525. } else {
  3526. ggml_backend_buffer_type_t split_buft;
  3527. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  3528. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  3529. } else {
  3530. // LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_LAYER in backends where it is not supported
  3531. split_buft = llama_default_buffer_type_offload(main_gpu);
  3532. }
  3533. // assign the repeating layers
  3534. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3535. model.buft_layer[i] = {
  3536. split_buft,
  3537. llama_default_buffer_type_offload(main_gpu)
  3538. };
  3539. }
  3540. // assign the output layer
  3541. if (n_gpu_layers > n_layer) {
  3542. model.buft_output = {
  3543. split_buft,
  3544. llama_default_buffer_type_offload(main_gpu)
  3545. };
  3546. } else {
  3547. model.buft_output = llama_default_buffer_type_cpu(true);
  3548. }
  3549. }
  3550. // count used buffer types
  3551. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  3552. buft_layer_count[model.buft_input.buft]++;
  3553. buft_layer_count[model.buft_input.buft_matrix]++;
  3554. buft_layer_count[model.buft_output.buft]++;
  3555. buft_layer_count[model.buft_output.buft_matrix]++;
  3556. for (int64_t i = 0; i < n_layer; ++i) {
  3557. buft_layer_count[model.buft_layer[i].buft]++;
  3558. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  3559. }
  3560. // create one context per buffer type
  3561. size_t ctx_size = ggml_tensor_overhead()*(ml.n_tensors + 1); // +1 for models where tok_embd is duplicated as output
  3562. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3563. for (auto & it : buft_layer_count) {
  3564. struct ggml_init_params params = {
  3565. /*.mem_size =*/ ctx_size,
  3566. /*.mem_buffer =*/ NULL,
  3567. /*.no_alloc =*/ true,
  3568. };
  3569. ggml_context * ctx = ggml_init(params);
  3570. if (!ctx) {
  3571. throw std::runtime_error(format("failed to create context"));
  3572. }
  3573. ctx_map[it.first] = ctx;
  3574. model.ctxs.push_back(ctx);
  3575. }
  3576. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  3577. // create tensors for the weights
  3578. {
  3579. const int64_t n_embd = hparams.n_embd;
  3580. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3581. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3582. const int64_t n_embd_gqa = n_embd_v_gqa;
  3583. const int64_t n_vocab = hparams.n_vocab;
  3584. const int64_t n_vocab_type = hparams.n_vocab_type;
  3585. const int64_t n_ff = hparams.n_ff;
  3586. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  3587. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  3588. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  3589. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  3590. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  3591. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  3592. model.layers.resize(n_layer);
  3593. const auto tn = LLM_TN(model.arch);
  3594. switch (model.arch) {
  3595. case LLM_ARCH_LLAMA:
  3596. case LLM_ARCH_REFACT:
  3597. case LLM_ARCH_MINICPM:
  3598. {
  3599. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3600. // output
  3601. {
  3602. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3603. if (model.arch != LLM_ARCH_MINICPM){
  3604. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  3605. // if output is NULL, init from the input tok embed
  3606. if (model.output == NULL) {
  3607. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3608. ml.n_created--; // artificial tensor
  3609. ml.size_data += ggml_nbytes(model.output);
  3610. }
  3611. }
  3612. }
  3613. for (int i = 0; i < n_layer; ++i) {
  3614. ggml_context * ctx_layer = ctx_for_layer(i);
  3615. ggml_context * ctx_split = ctx_for_layer_split(i);
  3616. auto & layer = model.layers[i];
  3617. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3618. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3619. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3620. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3621. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3622. // optional bias tensors
  3623. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3624. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3625. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3626. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3627. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3628. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd}, false);
  3629. if (layer.ffn_gate_inp == nullptr) {
  3630. GGML_ASSERT(hparams.n_expert == 0);
  3631. GGML_ASSERT(hparams.n_expert_used == 0);
  3632. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3633. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3634. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3635. } else {
  3636. GGML_ASSERT(hparams.n_expert > 0);
  3637. GGML_ASSERT(hparams.n_expert_used > 0);
  3638. // MoE branch
  3639. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  3640. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  3641. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  3642. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  3643. }
  3644. }
  3645. }
  3646. } break;
  3647. case LLM_ARCH_BAICHUAN:
  3648. {
  3649. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3650. {
  3651. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3652. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3653. }
  3654. for (int i = 0; i < n_layer; ++i) {
  3655. ggml_context * ctx_layer = ctx_for_layer(i);
  3656. ggml_context * ctx_split = ctx_for_layer_split(i);
  3657. auto & layer = model.layers[i];
  3658. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3659. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3660. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3661. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3662. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3663. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3664. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3665. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3666. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3667. }
  3668. } break;
  3669. case LLM_ARCH_FALCON:
  3670. {
  3671. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3672. // output
  3673. {
  3674. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3675. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3676. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_OUTPUT, "weight").c_str()) >= 0) {
  3677. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3678. } else {
  3679. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  3680. ml.n_created--; // artificial tensor
  3681. ml.size_data += ggml_nbytes(model.output);
  3682. }
  3683. }
  3684. for (int i = 0; i < n_layer; ++i) {
  3685. ggml_context * ctx_layer = ctx_for_layer(i);
  3686. ggml_context * ctx_split = ctx_for_layer_split(i);
  3687. auto & layer = model.layers[i];
  3688. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3689. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3690. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i).c_str()) >= 0) {
  3691. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd});
  3692. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd});
  3693. }
  3694. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3695. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3696. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3697. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3698. }
  3699. } break;
  3700. case LLM_ARCH_STARCODER:
  3701. {
  3702. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3703. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3704. // output
  3705. {
  3706. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3707. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3708. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3709. }
  3710. for (int i = 0; i < n_layer; ++i) {
  3711. ggml_context * ctx_layer = ctx_for_layer(i);
  3712. ggml_context * ctx_split = ctx_for_layer_split(i);
  3713. auto & layer = model.layers[i];
  3714. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3715. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3716. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3717. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3718. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3719. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3720. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3721. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3722. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3723. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3724. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3725. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3726. }
  3727. } break;
  3728. case LLM_ARCH_PERSIMMON:
  3729. {
  3730. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3731. {
  3732. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3733. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3734. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3735. }
  3736. for (int i = 0; i < n_layer; ++i) {
  3737. ggml_context * ctx_layer = ctx_for_layer(i);
  3738. ggml_context * ctx_split = ctx_for_layer_split(i);
  3739. auto & layer = model.layers[i];
  3740. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3741. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3742. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3743. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3744. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3745. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3746. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3747. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3748. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3749. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3750. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3751. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3752. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  3753. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  3754. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  3755. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  3756. }
  3757. } break;
  3758. case LLM_ARCH_BERT:
  3759. case LLM_ARCH_NOMIC_BERT:
  3760. {
  3761. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3762. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  3763. if (model.arch == LLM_ARCH_BERT) {
  3764. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3765. }
  3766. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3767. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3768. for (int i = 0; i < n_layer; ++i) {
  3769. ggml_context * ctx_layer = ctx_for_layer(i);
  3770. ggml_context * ctx_split = ctx_for_layer_split(i);
  3771. auto & layer = model.layers[i];
  3772. if (model.arch == LLM_ARCH_BERT) {
  3773. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3774. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3775. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3776. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3777. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3778. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3779. } else {
  3780. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3781. }
  3782. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3783. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  3784. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  3785. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3786. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3787. if (model.arch == LLM_ARCH_BERT) {
  3788. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3789. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3790. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3791. } else {
  3792. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3793. }
  3794. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  3795. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  3796. }
  3797. } break;
  3798. case LLM_ARCH_BLOOM:
  3799. {
  3800. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3801. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3802. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3803. // output
  3804. {
  3805. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3806. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3807. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3808. }
  3809. for (int i = 0; i < n_layer; ++i) {
  3810. ggml_context * ctx_layer = ctx_for_layer(i);
  3811. ggml_context * ctx_split = ctx_for_layer_split(i);
  3812. auto & layer = model.layers[i];
  3813. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3814. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3815. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3816. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3817. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3818. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3819. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3820. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3821. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3822. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3823. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3824. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3825. }
  3826. } break;
  3827. case LLM_ARCH_MPT:
  3828. {
  3829. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3830. // output
  3831. {
  3832. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3833. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, false);
  3834. // same as tok_embd, duplicated to allow offloading
  3835. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3836. ml.n_created--; // artificial tensor
  3837. ml.size_data += ggml_nbytes(model.output);
  3838. }
  3839. for (int i = 0; i < n_layer; ++i) {
  3840. ggml_context * ctx_layer = ctx_for_layer(i);
  3841. ggml_context * ctx_split = ctx_for_layer_split(i);
  3842. auto & layer = model.layers[i];
  3843. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3844. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, false);
  3845. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3846. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3847. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3848. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3849. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3850. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, false);
  3851. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3852. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, false);
  3853. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3854. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, false);
  3855. // AWQ ScaleActivation layer
  3856. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  3857. }
  3858. } break;
  3859. case LLM_ARCH_STABLELM:
  3860. {
  3861. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3862. // output
  3863. {
  3864. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3865. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3866. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3867. }
  3868. for (int i = 0; i < n_layer; ++i) {
  3869. ggml_context * ctx_layer = ctx_for_layer(i);
  3870. ggml_context * ctx_split = ctx_for_layer_split(i);
  3871. auto & layer = model.layers[i];
  3872. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3873. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3874. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3875. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3876. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3877. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3878. // optional bias tensors, present in Stable LM 2 1.6B
  3879. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3880. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3881. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3882. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3883. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3884. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3885. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3886. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3887. }
  3888. } break;
  3889. case LLM_ARCH_QWEN:
  3890. {
  3891. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3892. // output
  3893. {
  3894. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3895. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3896. }
  3897. for (int i = 0; i < n_layer; ++i) {
  3898. ggml_context * ctx_layer = ctx_for_layer(i);
  3899. ggml_context * ctx_split = ctx_for_layer_split(i);
  3900. auto & layer = model.layers[i];
  3901. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3902. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  3903. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  3904. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3905. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3906. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  3907. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  3908. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  3909. }
  3910. } break;
  3911. case LLM_ARCH_QWEN2:
  3912. {
  3913. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3914. // output
  3915. {
  3916. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3917. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3918. }
  3919. for (int i = 0; i < n_layer; ++i) {
  3920. ggml_context * ctx_layer = ctx_for_layer(i);
  3921. ggml_context * ctx_split = ctx_for_layer_split(i);
  3922. auto & layer = model.layers[i];
  3923. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3924. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3925. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3926. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3927. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3928. // optional bias tensors
  3929. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3930. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3931. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3932. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3933. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3934. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3935. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3936. }
  3937. } break;
  3938. case LLM_ARCH_PHI2:
  3939. {
  3940. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3941. // output
  3942. {
  3943. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3944. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3945. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3946. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  3947. }
  3948. for (int i = 0; i < n_layer; ++i) {
  3949. ggml_context * ctx_layer = ctx_for_layer(i);
  3950. ggml_context * ctx_split = ctx_for_layer_split(i);
  3951. auto & layer = model.layers[i];
  3952. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3953. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3954. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  3955. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3956. if (layer.wqkv == nullptr) {
  3957. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3958. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3959. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3960. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3961. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3962. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3963. }
  3964. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3965. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3966. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3967. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3968. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3969. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3970. }
  3971. } break;
  3972. case LLM_ARCH_PLAMO:
  3973. {
  3974. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3975. // output
  3976. {
  3977. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3978. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3979. }
  3980. for (int i = 0; i < n_layer; ++i) {
  3981. ggml_context * ctx_layer = ctx_for_layer(i);
  3982. ggml_context * ctx_split = ctx_for_layer_split(i);
  3983. auto & layer = model.layers[i];
  3984. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3985. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3986. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3987. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3988. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3989. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3990. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3991. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3992. }
  3993. } break;
  3994. case LLM_ARCH_GPT2:
  3995. {
  3996. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3997. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3998. // output
  3999. {
  4000. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4001. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4002. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4003. }
  4004. for (int i = 0; i < n_layer; ++i) {
  4005. ggml_context * ctx_layer = ctx_for_layer(i);
  4006. ggml_context * ctx_split = ctx_for_layer_split(i);
  4007. auto & layer = model.layers[i];
  4008. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4009. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4010. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4011. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4012. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4013. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4014. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4015. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4016. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4017. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4018. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4019. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4020. }
  4021. } break;
  4022. case LLM_ARCH_CODESHELL:
  4023. {
  4024. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4025. // output
  4026. {
  4027. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4028. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4029. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4030. }
  4031. for (int i = 0; i < n_layer; ++i) {
  4032. ggml_context * ctx_layer = ctx_for_layer(i);
  4033. ggml_context * ctx_split = ctx_for_layer_split(i);
  4034. auto & layer = model.layers[i];
  4035. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4036. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4037. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4038. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4039. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4040. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4041. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4042. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4043. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4044. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4045. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4046. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4047. }
  4048. } break;
  4049. case LLM_ARCH_ORION:
  4050. {
  4051. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4052. {
  4053. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4054. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4055. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4056. }
  4057. for (int i = 0; i < n_layer; ++i) {
  4058. ggml_context * ctx_layer = ctx_for_layer(i);
  4059. ggml_context * ctx_split = ctx_for_layer_split(i);
  4060. auto & layer = model.layers[i];
  4061. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4062. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4063. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4064. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4065. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4066. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4067. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4068. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4069. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4070. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4071. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4072. }
  4073. } break;
  4074. case LLM_ARCH_INTERNLM2:
  4075. {
  4076. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4077. // output
  4078. {
  4079. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4080. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4081. }
  4082. for (int i = 0; i < n_layer; ++i) {
  4083. ggml_context * ctx_layer = ctx_for_layer(i);
  4084. ggml_context * ctx_split = ctx_for_layer_split(i);
  4085. auto & layer = model.layers[i];
  4086. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4087. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4088. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4089. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4090. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4091. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4092. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4093. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4094. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4095. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4096. }
  4097. } break;
  4098. case LLM_ARCH_GEMMA:
  4099. {
  4100. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4101. // output
  4102. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4103. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // same as tok_embd, duplicated to allow offloading
  4104. ml.n_created--; // artificial tensor
  4105. ml.size_data += ggml_nbytes(model.output);
  4106. const int64_t n_ff = hparams.n_ff;
  4107. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  4108. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4109. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4110. for (uint32_t i = 0; i < n_layer; ++i) {
  4111. ggml_context * ctx_layer = ctx_for_layer(i);
  4112. ggml_context * ctx_split = ctx_for_layer_split(i);
  4113. auto & layer = model.layers[i];
  4114. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4115. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * hparams.n_head});
  4116. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  4117. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  4118. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * hparams.n_head, n_embd});
  4119. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4120. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4121. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4122. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4123. }
  4124. } break;
  4125. case LLM_ARCH_STARCODER2:
  4126. {
  4127. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4128. // output
  4129. {
  4130. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4131. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4132. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4133. // if output is NULL, init from the input tok embed
  4134. if (model.output == NULL) {
  4135. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4136. ml.n_created--; // artificial tensor
  4137. ml.size_data += ggml_nbytes(model.output);
  4138. }
  4139. }
  4140. for (int i = 0; i < n_layer; ++i) {
  4141. ggml_context * ctx_layer = ctx_for_layer(i);
  4142. ggml_context * ctx_split = ctx_for_layer_split(i);
  4143. auto & layer = model.layers[i];
  4144. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4145. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4146. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4147. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4148. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4149. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4150. // optional bias tensors
  4151. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4152. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4153. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4154. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4155. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4156. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4157. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4158. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4159. // optional bias tensors
  4160. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4161. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP , "bias", i), { n_ff});
  4162. }
  4163. } break;
  4164. case LLM_ARCH_MAMBA:
  4165. {
  4166. const int64_t d_conv = hparams.ssm_d_conv;
  4167. const int64_t d_inner = hparams.ssm_d_inner;
  4168. const int64_t d_state = hparams.ssm_d_state;
  4169. const int64_t dt_rank = hparams.ssm_dt_rank;
  4170. // only an expansion factor of 2 is supported for now
  4171. GGML_ASSERT(2 * n_embd == d_inner);
  4172. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4173. // output
  4174. {
  4175. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4176. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4177. // if output is NULL, init from the input tok embed, duplicated to allow offloading
  4178. if (model.output == NULL) {
  4179. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4180. ml.n_created--; // artificial tensor
  4181. ml.size_data += ggml_nbytes(model.output);
  4182. }
  4183. }
  4184. for (int i = 0; i < n_layer; ++i) {
  4185. ggml_context * ctx_layer = ctx_for_layer(i);
  4186. ggml_context * ctx_split = ctx_for_layer_split(i);
  4187. auto & layer = model.layers[i];
  4188. // norm
  4189. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4190. layer.ssm_in = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_IN, "weight", i), {n_embd, 2*d_inner});
  4191. layer.ssm_conv1d = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_CONV1D, "weight", i), {d_conv, d_inner});
  4192. layer.ssm_conv1d_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_CONV1D, "bias", i), {d_inner});
  4193. layer.ssm_x = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_X, "weight", i), {d_inner, dt_rank + 2*d_state});
  4194. layer.ssm_dt = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_DT, "weight", i), {dt_rank, d_inner});
  4195. layer.ssm_dt_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_DT, "bias", i), {d_inner});
  4196. // no "weight" suffix for these
  4197. layer.ssm_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_A, i), {d_state, d_inner});
  4198. layer.ssm_d = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_D, i), {d_inner});
  4199. // out_proj
  4200. layer.ssm_out = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_OUT, "weight", i), {d_inner, n_embd});
  4201. }
  4202. } break;
  4203. default:
  4204. throw std::runtime_error("unknown architecture");
  4205. }
  4206. }
  4207. ml.done_getting_tensors();
  4208. ml.init_mapping(true, use_mlock ? &model.mlock_mmap : nullptr);
  4209. // create the backend buffers
  4210. std::vector<std::pair<ggml_context *, ggml_backend_buffer_t>> ctx_bufs;
  4211. for (auto & it : ctx_map) {
  4212. ggml_backend_buffer_type_t buft = it.first;
  4213. ggml_context * ctx = it.second;
  4214. ggml_backend_buffer_t buf = nullptr;
  4215. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  4216. // this is important for metal with apple silicon: if the entire model could be mapped to a metal buffer, then we could just use metal for all layers
  4217. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  4218. if (ml.use_mmap && buft == llama_default_buffer_type_cpu(true)) {
  4219. size_t first, last;
  4220. ml.get_mapping_range(&first, &last, ctx);
  4221. buf = ggml_backend_cpu_buffer_from_ptr((char *) ml.mapping->addr + first, last - first);
  4222. }
  4223. #ifdef GGML_USE_METAL
  4224. else if (ml.use_mmap && buft == ggml_backend_metal_buffer_type()) {
  4225. const size_t max_size = ggml_get_max_tensor_size(ctx);
  4226. size_t first, last;
  4227. ml.get_mapping_range(&first, &last, ctx);
  4228. buf = ggml_backend_metal_buffer_from_ptr((char *) ml.mapping->addr + first, last - first, max_size);
  4229. }
  4230. #endif
  4231. else {
  4232. buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  4233. if (buf != nullptr && use_mlock && ggml_backend_buffer_is_host(buf)) {
  4234. model.mlock_bufs.emplace_back(new llama_mlock);
  4235. auto & mlock_buf = model.mlock_bufs.back();
  4236. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  4237. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  4238. }
  4239. }
  4240. if (buf == nullptr) {
  4241. throw std::runtime_error("failed to allocate buffer");
  4242. }
  4243. // indicate that this buffer contains weights
  4244. // this is used by ggml_backend_sched to improve op scheduling -> ops that use a weight are preferably scheduled to the backend that contains the weight
  4245. ggml_backend_buffer_set_usage(buf, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  4246. model.bufs.push_back(buf);
  4247. ctx_bufs.emplace_back(ctx, buf);
  4248. }
  4249. if (llama_supports_gpu_offload()) {
  4250. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  4251. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  4252. if (n_gpu_layers > (int) hparams.n_layer) {
  4253. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  4254. }
  4255. const int max_backend_supported_layers = hparams.n_layer + 1;
  4256. const int max_offloadable_layers = hparams.n_layer + 1;
  4257. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  4258. }
  4259. // print memory requirements
  4260. for (ggml_backend_buffer_t buf : model.bufs) {
  4261. LLAMA_LOG_INFO("%s: %10s buffer size = %8.2f MiB\n", __func__, ggml_backend_buffer_name(buf), ggml_backend_buffer_get_size(buf) / 1024.0 / 1024.0);
  4262. }
  4263. // populate tensors_by_name
  4264. for (ggml_context * ctx : model.ctxs) {
  4265. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  4266. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  4267. }
  4268. }
  4269. // load tensor data
  4270. for (auto & it : ctx_bufs) {
  4271. ggml_context * ctx = it.first;
  4272. ggml_backend_buffer_t buf = it.second;
  4273. if (!ml.load_all_data(ctx, progress_callback, progress_callback_user_data, buf, use_mlock ? &model.mlock_mmap : NULL)) {
  4274. return false;
  4275. }
  4276. }
  4277. model.mapping = std::move(ml.mapping);
  4278. // loading time will be recalculate after the first eval, so
  4279. // we take page faults deferred by mmap() into consideration
  4280. model.t_load_us = ggml_time_us() - model.t_start_us;
  4281. return true;
  4282. }
  4283. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  4284. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  4285. try {
  4286. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  4287. model.hparams.vocab_only = params.vocab_only;
  4288. try {
  4289. llm_load_arch(ml, model);
  4290. } catch(const std::exception & e) {
  4291. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  4292. }
  4293. try {
  4294. llm_load_hparams(ml, model);
  4295. } catch(const std::exception & e) {
  4296. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  4297. }
  4298. try {
  4299. llm_load_vocab(ml, model);
  4300. } catch(const std::exception & e) {
  4301. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  4302. }
  4303. llm_load_print_meta(ml, model);
  4304. if (model.vocab.type != LLAMA_VOCAB_TYPE_NONE &&
  4305. model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  4306. throw std::runtime_error("vocab size mismatch");
  4307. }
  4308. if (params.vocab_only) {
  4309. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  4310. return 0;
  4311. }
  4312. #ifdef GGML_USE_KOMPUTE
  4313. if (params.n_gpu_layers > 0 && (
  4314. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  4315. || !(
  4316. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  4317. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  4318. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  4319. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  4320. )
  4321. )) {
  4322. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  4323. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  4324. params.n_gpu_layers = 0;
  4325. }
  4326. #endif
  4327. if (!llm_load_tensors(
  4328. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  4329. params.progress_callback, params.progress_callback_user_data
  4330. )) {
  4331. return -2;
  4332. }
  4333. } catch (const std::exception & err) {
  4334. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  4335. return -1;
  4336. }
  4337. return 0;
  4338. }
  4339. //
  4340. // llm_build
  4341. //
  4342. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  4343. enum llm_ffn_op_type {
  4344. LLM_FFN_SILU,
  4345. LLM_FFN_GELU,
  4346. LLM_FFN_RELU,
  4347. LLM_FFN_RELU_SQR,
  4348. };
  4349. enum llm_ffn_gate_type {
  4350. LLM_FFN_SEQ,
  4351. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  4352. };
  4353. enum llm_norm_type {
  4354. LLM_NORM,
  4355. LLM_NORM_RMS,
  4356. };
  4357. static struct ggml_tensor * llm_build_inp_embd(
  4358. struct ggml_context * ctx,
  4359. struct llama_context & lctx,
  4360. const llama_hparams & hparams,
  4361. const llama_batch & batch,
  4362. struct ggml_tensor * tok_embd,
  4363. const llm_build_cb & cb) {
  4364. const int64_t n_embd = hparams.n_embd;
  4365. struct ggml_tensor * inpL;
  4366. if (batch.token) {
  4367. lctx.inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  4368. cb(lctx.inp_tokens, "inp_tokens", -1);
  4369. ggml_set_input(lctx.inp_tokens);
  4370. inpL = ggml_get_rows(ctx, tok_embd, lctx.inp_tokens);
  4371. } else {
  4372. #ifdef GGML_USE_MPI
  4373. GGML_ASSERT(false && "not implemented");
  4374. #endif
  4375. lctx.inp_embd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  4376. inpL = lctx.inp_embd;
  4377. ggml_set_input(lctx.inp_embd);
  4378. }
  4379. cb(inpL, "inp_embd", -1);
  4380. return inpL;
  4381. }
  4382. static void llm_build_kv_store(
  4383. struct ggml_context * ctx,
  4384. const llama_hparams & hparams,
  4385. const llama_kv_cache & kv,
  4386. struct ggml_cgraph * graph,
  4387. struct ggml_tensor * k_cur,
  4388. struct ggml_tensor * v_cur,
  4389. int64_t n_ctx,
  4390. int32_t n_tokens,
  4391. int32_t kv_head,
  4392. const llm_build_cb & cb,
  4393. int64_t il) {
  4394. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4395. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4396. GGML_ASSERT(kv.size == n_ctx);
  4397. // compute the transposed [n_tokens, n_embd] V matrix
  4398. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, ggml_reshape_2d(ctx, v_cur, n_embd_v_gqa, n_tokens));
  4399. //struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur); // TODO: reshape above is likely not needed
  4400. cb(v_cur_t, "v_cur_t", il);
  4401. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  4402. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  4403. cb(k_cache_view, "k_cache_view", il);
  4404. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  4405. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  4406. (kv_head)*ggml_element_size(kv.v_l[il]));
  4407. cb(v_cache_view, "v_cache_view", il);
  4408. // important: storing RoPE-ed version of K in the KV cache!
  4409. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  4410. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  4411. }
  4412. static struct ggml_tensor * llm_build_norm(
  4413. struct ggml_context * ctx,
  4414. struct ggml_tensor * cur,
  4415. const llama_hparams & hparams,
  4416. struct ggml_tensor * mw,
  4417. struct ggml_tensor * mb,
  4418. llm_norm_type type,
  4419. const llm_build_cb & cb,
  4420. int il) {
  4421. switch (type) {
  4422. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  4423. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  4424. }
  4425. if (mw || mb) {
  4426. cb(cur, "norm", il);
  4427. }
  4428. if (mw) {
  4429. cur = ggml_mul(ctx, cur, mw);
  4430. if (mb) {
  4431. cb(cur, "norm_w", il);
  4432. }
  4433. }
  4434. if (mb) {
  4435. cur = ggml_add(ctx, cur, mb);
  4436. }
  4437. return cur;
  4438. }
  4439. static struct ggml_tensor * llm_build_ffn(
  4440. struct ggml_context * ctx,
  4441. struct ggml_tensor * cur,
  4442. struct ggml_tensor * up,
  4443. struct ggml_tensor * up_b,
  4444. struct ggml_tensor * gate,
  4445. struct ggml_tensor * gate_b,
  4446. struct ggml_tensor * down,
  4447. struct ggml_tensor * down_b,
  4448. struct ggml_tensor * act_scales,
  4449. llm_ffn_op_type type_op,
  4450. llm_ffn_gate_type type_gate,
  4451. const llm_build_cb & cb,
  4452. int il) {
  4453. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  4454. cb(tmp, "ffn_up", il);
  4455. if (up_b) {
  4456. tmp = ggml_add(ctx, tmp, up_b);
  4457. cb(tmp, "ffn_up_b", il);
  4458. }
  4459. if (gate) {
  4460. switch (type_gate) {
  4461. case LLM_FFN_SEQ:
  4462. {
  4463. cur = ggml_mul_mat(ctx, gate, tmp);
  4464. cb(cur, "ffn_gate", il);
  4465. } break;
  4466. case LLM_FFN_PAR:
  4467. {
  4468. cur = ggml_mul_mat(ctx, gate, cur);
  4469. cb(cur, "ffn_gate", il);
  4470. } break;
  4471. }
  4472. if (gate_b) {
  4473. cur = ggml_add(ctx, cur, gate_b);
  4474. cb(cur, "ffn_gate_b", il);
  4475. }
  4476. } else {
  4477. cur = tmp;
  4478. }
  4479. switch (type_op) {
  4480. case LLM_FFN_SILU:
  4481. {
  4482. cur = ggml_silu(ctx, cur);
  4483. cb(cur, "ffn_silu", il);
  4484. } break;
  4485. case LLM_FFN_GELU:
  4486. {
  4487. cur = ggml_gelu(ctx, cur);
  4488. cb(cur, "ffn_gelu", il);
  4489. if (act_scales != NULL) {
  4490. cur = ggml_div(ctx, cur, act_scales);
  4491. cb(cur, "ffn_act", il);
  4492. }
  4493. } break;
  4494. case LLM_FFN_RELU:
  4495. {
  4496. cur = ggml_relu(ctx, cur);
  4497. cb(cur, "ffn_relu", il);
  4498. } break;
  4499. case LLM_FFN_RELU_SQR:
  4500. {
  4501. cur = ggml_relu(ctx, cur);
  4502. cb(cur, "ffn_relu", il);
  4503. cur = ggml_sqr(ctx, cur);
  4504. cb(cur, "ffn_sqr(relu)", il);
  4505. } break;
  4506. }
  4507. if (type_gate == LLM_FFN_PAR) {
  4508. cur = ggml_mul(ctx, cur, tmp);
  4509. cb(cur, "ffn_gate_par", il);
  4510. }
  4511. cur = ggml_mul_mat(ctx, down, cur);
  4512. if (down_b) {
  4513. cb(cur, "ffn_down", il);
  4514. }
  4515. if (down_b) {
  4516. cur = ggml_add(ctx, cur, down_b);
  4517. }
  4518. return cur;
  4519. }
  4520. // if max_alibi_bias > 0 then apply ALiBi
  4521. static struct ggml_tensor * llm_build_kqv(
  4522. struct ggml_context * ctx,
  4523. const llama_model & model,
  4524. const llama_hparams & hparams,
  4525. const llama_kv_cache & kv,
  4526. struct ggml_cgraph * graph,
  4527. struct ggml_tensor * wo,
  4528. struct ggml_tensor * wo_b,
  4529. struct ggml_tensor * q_cur,
  4530. struct ggml_tensor * kq_mask,
  4531. struct ggml_tensor * kq_pos,
  4532. int64_t n_ctx,
  4533. int32_t n_tokens,
  4534. int32_t n_kv,
  4535. float kq_scale,
  4536. const llm_build_cb & cb,
  4537. int il) {
  4538. const int64_t n_head = hparams.n_head;
  4539. const int64_t n_head_kv = hparams.n_head_kv;
  4540. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  4541. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4542. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  4543. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  4544. cb(q, "q", il);
  4545. struct ggml_tensor * k =
  4546. ggml_view_3d(ctx, kv.k_l[il],
  4547. n_embd_head_k, n_kv, n_head_kv,
  4548. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  4549. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  4550. 0);
  4551. cb(k, "k", il);
  4552. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  4553. cb(kq, "kq", il);
  4554. if (model.arch == LLM_ARCH_PHI2) {
  4555. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  4556. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  4557. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  4558. }
  4559. #if defined(GGML_USE_KOMPUTE)
  4560. #pragma message("TODO: ALiBi support in ggml_soft_max_ext is not implemented for Kompute")
  4561. #pragma message(" Falling back to ggml_alibi(). Will become an error in Mar 2024")
  4562. #pragma message("ref: https://github.com/ggerganov/llama.cpp/pull/5488")
  4563. if (hparams.f_max_alibi_bias > 0.0f) {
  4564. kq = ggml_scale(ctx, kq, kq_scale);
  4565. cb(kq, "kq_scaled", il);
  4566. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, hparams.f_max_alibi_bias);
  4567. cb(kq, "kq_scaled_alibi", il);
  4568. kq = ggml_add(ctx, kq, kq_mask);
  4569. cb(kq, "kq_masked", il);
  4570. kq = ggml_soft_max(ctx, kq);
  4571. cb(kq, "kq_soft_max", il);
  4572. } else
  4573. #endif
  4574. {
  4575. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_pos, kq_scale, hparams.f_max_alibi_bias);
  4576. cb(kq, "kq_soft_max_ext", il);
  4577. }
  4578. GGML_ASSERT(kv.size == n_ctx);
  4579. // split cached v into n_head heads
  4580. struct ggml_tensor * v =
  4581. ggml_view_3d(ctx, kv.v_l[il],
  4582. n_kv, n_embd_head_v, n_head_kv,
  4583. ggml_element_size(kv.v_l[il])*n_ctx,
  4584. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  4585. 0);
  4586. cb(v, "v", il);
  4587. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  4588. cb(kqv, "kqv", il);
  4589. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  4590. cb(kqv_merged, "kqv_merged", il);
  4591. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  4592. cb(cur, "kqv_merged_cont", il);
  4593. ggml_build_forward_expand(graph, cur);
  4594. cur = ggml_mul_mat(ctx, wo, cur);
  4595. if (wo_b) {
  4596. cb(cur, "kqv_wo", il);
  4597. }
  4598. if (wo_b) {
  4599. cur = ggml_add(ctx, cur, wo_b);
  4600. }
  4601. return cur;
  4602. }
  4603. static struct ggml_tensor * llm_build_kv(
  4604. struct ggml_context * ctx,
  4605. const llama_model & model,
  4606. const llama_hparams & hparams,
  4607. const llama_kv_cache & kv,
  4608. struct ggml_cgraph * graph,
  4609. struct ggml_tensor * wo,
  4610. struct ggml_tensor * wo_b,
  4611. struct ggml_tensor * k_cur,
  4612. struct ggml_tensor * v_cur,
  4613. struct ggml_tensor * q_cur,
  4614. struct ggml_tensor * kq_mask,
  4615. struct ggml_tensor * kq_pos,
  4616. int64_t n_ctx,
  4617. int32_t n_tokens,
  4618. int32_t kv_head,
  4619. int32_t n_kv,
  4620. float kq_scale,
  4621. const llm_build_cb & cb,
  4622. int il) {
  4623. // these nodes are added to the graph together so that they are not reordered
  4624. // by doing so, the number of splits in the graph is reduced
  4625. ggml_build_forward_expand(graph, q_cur);
  4626. ggml_build_forward_expand(graph, k_cur);
  4627. ggml_build_forward_expand(graph, v_cur);
  4628. llm_build_kv_store(ctx, hparams, kv, graph, k_cur, v_cur, n_ctx, n_tokens, kv_head, cb, il);
  4629. struct ggml_tensor * cur;
  4630. cur = llm_build_kqv(ctx, model, hparams, kv, graph, wo, wo_b,
  4631. q_cur, kq_mask, kq_pos, n_ctx, n_tokens, n_kv, kq_scale, cb, il);
  4632. cb(cur, "kqv_out", il);
  4633. return cur;
  4634. }
  4635. struct llm_build_context {
  4636. const llama_model & model;
  4637. llama_context & lctx;
  4638. const llama_hparams & hparams;
  4639. const llama_cparams & cparams;
  4640. const llama_batch & batch;
  4641. const llama_kv_cache & kv_self;
  4642. const int64_t n_embd;
  4643. const int64_t n_layer;
  4644. const int64_t n_rot;
  4645. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  4646. const int64_t n_head;
  4647. const int64_t n_head_kv;
  4648. const int64_t n_embd_head_k;
  4649. const int64_t n_embd_k_gqa;
  4650. const int64_t n_embd_head_v;
  4651. const int64_t n_embd_v_gqa;
  4652. const int64_t n_expert;
  4653. const int64_t n_expert_used;
  4654. const float freq_base;
  4655. const float freq_scale;
  4656. const float ext_factor;
  4657. const float attn_factor;
  4658. const float beta_fast;
  4659. const float beta_slow;
  4660. const float norm_eps;
  4661. const float norm_rms_eps;
  4662. const int32_t n_tokens;
  4663. const int32_t n_kv; // size of KV cache to consider (n_kv <= n_ctx)
  4664. const int32_t kv_head; // index of where we store new KV data in the cache
  4665. const int32_t n_orig_ctx;
  4666. const enum llama_pooling_type pooling_type;
  4667. const enum llama_rope_type rope_type;
  4668. const llm_build_cb & cb;
  4669. std::vector<uint8_t> & buf_compute_meta;
  4670. struct ggml_context * ctx0 = nullptr;
  4671. // TODO: consider making the entire interface noexcept
  4672. llm_build_context(
  4673. llama_context & lctx,
  4674. const llama_batch & batch,
  4675. const llm_build_cb & cb,
  4676. bool worst_case) :
  4677. model (lctx.model),
  4678. lctx (lctx),
  4679. hparams (model.hparams),
  4680. cparams (lctx.cparams),
  4681. batch (batch),
  4682. kv_self (lctx.kv_self),
  4683. n_embd (hparams.n_embd),
  4684. n_layer (hparams.n_layer),
  4685. n_rot (hparams.n_rot),
  4686. n_ctx (cparams.n_ctx),
  4687. n_head (hparams.n_head),
  4688. n_head_kv (hparams.n_head_kv),
  4689. n_embd_head_k (hparams.n_embd_head_k),
  4690. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  4691. n_embd_head_v (hparams.n_embd_head_v),
  4692. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  4693. n_expert (hparams.n_expert),
  4694. n_expert_used (hparams.n_expert_used),
  4695. freq_base (cparams.rope_freq_base),
  4696. freq_scale (cparams.rope_freq_scale),
  4697. ext_factor (cparams.yarn_ext_factor),
  4698. attn_factor (cparams.yarn_attn_factor),
  4699. beta_fast (cparams.yarn_beta_fast),
  4700. beta_slow (cparams.yarn_beta_slow),
  4701. norm_eps (hparams.f_norm_eps),
  4702. norm_rms_eps (hparams.f_norm_rms_eps),
  4703. n_tokens (batch.n_tokens),
  4704. n_kv (worst_case ? kv_self.size : kv_self.n),
  4705. kv_head (worst_case ? (kv_self.recurrent ? 0 : kv_self.size - n_tokens) : kv_self.head),
  4706. n_orig_ctx (cparams.n_yarn_orig_ctx),
  4707. pooling_type (cparams.pooling_type),
  4708. rope_type (hparams.rope_type),
  4709. cb (cb),
  4710. buf_compute_meta (lctx.buf_compute_meta) {
  4711. // all initializations should be done in init()
  4712. }
  4713. void init() {
  4714. struct ggml_init_params params = {
  4715. /*.mem_size =*/ buf_compute_meta.size(),
  4716. /*.mem_buffer =*/ buf_compute_meta.data(),
  4717. /*.no_alloc =*/ true,
  4718. };
  4719. ctx0 = ggml_init(params);
  4720. lctx.inp_tokens = nullptr;
  4721. lctx.inp_embd = nullptr;
  4722. lctx.inp_pos = nullptr;
  4723. lctx.inp_KQ_mask = nullptr;
  4724. lctx.inp_KQ_pos = nullptr;
  4725. lctx.inp_K_shift = nullptr;
  4726. lctx.inp_mean = nullptr;
  4727. lctx.inp_cls = nullptr;
  4728. lctx.inp_s_copy = nullptr;
  4729. lctx.inp_s_mask = nullptr;
  4730. lctx.inp_s_seq = nullptr;
  4731. }
  4732. void free() {
  4733. if (ctx0) {
  4734. ggml_free(ctx0);
  4735. ctx0 = nullptr;
  4736. }
  4737. }
  4738. struct ggml_cgraph * build_k_shift() {
  4739. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4740. GGML_ASSERT(kv_self.size == n_ctx);
  4741. lctx.inp_K_shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_ctx);
  4742. cb(lctx.inp_K_shift, "K_shift", -1);
  4743. ggml_set_input(lctx.inp_K_shift);
  4744. for (int il = 0; il < n_layer; ++il) {
  4745. struct ggml_tensor * tmp =
  4746. // we rotate only the first n_rot dimensions
  4747. ggml_rope_custom_inplace(ctx0,
  4748. ggml_view_3d(ctx0, kv_self.k_l[il],
  4749. n_embd_head_k, n_head_kv, n_ctx,
  4750. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  4751. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  4752. 0),
  4753. lctx.inp_K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4754. ext_factor, attn_factor, beta_fast, beta_slow);
  4755. cb(tmp, "K_shifted", il);
  4756. ggml_build_forward_expand(gf, tmp);
  4757. }
  4758. return gf;
  4759. }
  4760. struct ggml_cgraph * build_s_copy() {
  4761. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4762. GGML_ASSERT(kv_self.recurrent);
  4763. struct ggml_tensor * state_copy = build_inp_s_copy();
  4764. for (int il = 0; il < n_layer; ++il) {
  4765. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  4766. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  4767. conv_states = ggml_get_rows(ctx0, conv_states, state_copy);
  4768. ssm_states = ggml_get_rows(ctx0, ssm_states, state_copy);
  4769. // TODO: name the intermediate tensors with cb()
  4770. ggml_build_forward_expand(gf, ggml_cpy(ctx0, conv_states, kv_self.k_l[il]));
  4771. ggml_build_forward_expand(gf, ggml_cpy(ctx0, ssm_states, kv_self.v_l[il]));
  4772. }
  4773. return gf;
  4774. }
  4775. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  4776. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4777. for (uint32_t i = 0; i < ids.size(); ++i) {
  4778. const uint32_t id = ids[i];
  4779. if (i == id || id == ids.size()) {
  4780. continue;
  4781. }
  4782. uint32_t nm = 1;
  4783. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  4784. nm++;
  4785. }
  4786. for (int il = 0; il < n_layer; ++il) {
  4787. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  4788. n_embd_k_gqa, nm,
  4789. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  4790. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  4791. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  4792. n_embd_k_gqa, nm,
  4793. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  4794. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  4795. ggml_tensor * view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  4796. nm, n_embd_v_gqa,
  4797. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  4798. ggml_row_size(kv_self.v_l[il]->type, i));
  4799. ggml_tensor * view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  4800. nm, n_embd_v_gqa,
  4801. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  4802. ggml_row_size(kv_self.v_l[il]->type, id));
  4803. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  4804. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  4805. }
  4806. i += nm - 1;
  4807. }
  4808. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  4809. return gf;
  4810. }
  4811. struct ggml_tensor * build_inp_pos() {
  4812. lctx.inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4813. cb(lctx.inp_pos, "inp_pos", -1);
  4814. ggml_set_input(lctx.inp_pos);
  4815. return lctx.inp_pos;
  4816. }
  4817. struct ggml_tensor * build_inp_KQ_mask(bool causal = true) {
  4818. if (causal) {
  4819. lctx.inp_KQ_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, n_tokens);
  4820. } else {
  4821. lctx.inp_KQ_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  4822. }
  4823. cb(lctx.inp_KQ_mask, "KQ_mask", -1);
  4824. ggml_set_input(lctx.inp_KQ_mask);
  4825. return lctx.inp_KQ_mask;
  4826. }
  4827. struct ggml_tensor * build_inp_KQ_pos() {
  4828. lctx.inp_KQ_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_kv);
  4829. cb(lctx.inp_KQ_pos, "KQ_pos", -1);
  4830. ggml_set_input(lctx.inp_KQ_pos);
  4831. return lctx.inp_KQ_pos;
  4832. }
  4833. struct ggml_tensor * build_inp_mean() {
  4834. lctx.inp_mean = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  4835. cb(lctx.inp_mean, "inp_mean", -1);
  4836. ggml_set_input(lctx.inp_mean);
  4837. return lctx.inp_mean;
  4838. }
  4839. struct ggml_tensor * build_inp_cls() {
  4840. lctx.inp_cls = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4841. cb(lctx.inp_cls, "inp_cls", -1);
  4842. ggml_set_input(lctx.inp_cls);
  4843. return lctx.inp_cls;
  4844. }
  4845. struct ggml_tensor * build_inp_s_copy() {
  4846. lctx.inp_s_copy = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, kv_self.size);
  4847. cb(lctx.inp_s_copy, "inp_s_copy", -1);
  4848. ggml_set_input(lctx.inp_s_copy);
  4849. return lctx.inp_s_copy;
  4850. }
  4851. struct ggml_tensor * build_inp_s_mask() {
  4852. lctx.inp_s_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_kv);
  4853. cb(lctx.inp_s_mask, "inp_s_mask", -1);
  4854. ggml_set_input(lctx.inp_s_mask);
  4855. return lctx.inp_s_mask;
  4856. }
  4857. struct ggml_tensor * build_inp_s_seq() {
  4858. lctx.inp_s_seq = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  4859. cb(lctx.inp_s_seq, "inp_s_seq", -1);
  4860. ggml_set_input(lctx.inp_s_seq);
  4861. return lctx.inp_s_seq;
  4862. }
  4863. struct ggml_cgraph * build_llama() {
  4864. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4865. const int64_t n_embd_head = hparams.n_embd_head_v;
  4866. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4867. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4868. struct ggml_tensor * cur;
  4869. struct ggml_tensor * inpL;
  4870. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  4871. // inp_pos - contains the positions
  4872. struct ggml_tensor * inp_pos = build_inp_pos();
  4873. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4874. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  4875. for (int il = 0; il < n_layer; ++il) {
  4876. struct ggml_tensor * inpSA = inpL;
  4877. // norm
  4878. cur = llm_build_norm(ctx0, inpL, hparams,
  4879. model.layers[il].attn_norm, NULL,
  4880. LLM_NORM_RMS, cb, il);
  4881. cb(cur, "attn_norm", il);
  4882. // self-attention
  4883. {
  4884. // compute Q and K and RoPE them
  4885. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4886. cb(Qcur, "Qcur", il);
  4887. if (model.layers[il].bq) {
  4888. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  4889. cb(Qcur, "Qcur", il);
  4890. }
  4891. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4892. cb(Kcur, "Kcur", il);
  4893. if (model.layers[il].bk) {
  4894. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4895. cb(Kcur, "Kcur", il);
  4896. }
  4897. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4898. cb(Vcur, "Vcur", il);
  4899. if (model.layers[il].bv) {
  4900. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4901. cb(Vcur, "Vcur", il);
  4902. }
  4903. Qcur = ggml_rope_custom(
  4904. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4905. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4906. ext_factor, attn_factor, beta_fast, beta_slow
  4907. );
  4908. cb(Qcur, "Qcur", il);
  4909. Kcur = ggml_rope_custom(
  4910. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4911. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4912. ext_factor, attn_factor, beta_fast, beta_slow
  4913. );
  4914. cb(Kcur, "Kcur", il);
  4915. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4916. model.layers[il].wo, model.layers[il].bo,
  4917. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4918. }
  4919. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4920. cb(ffn_inp, "ffn_inp", il);
  4921. // feed-forward network
  4922. if (model.layers[il].ffn_gate_inp == nullptr) {
  4923. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4924. model.layers[il].ffn_norm, NULL,
  4925. LLM_NORM_RMS, cb, il);
  4926. cb(cur, "ffn_norm", il);
  4927. cur = llm_build_ffn(ctx0, cur,
  4928. model.layers[il].ffn_up, NULL,
  4929. model.layers[il].ffn_gate, NULL,
  4930. model.layers[il].ffn_down, NULL,
  4931. NULL,
  4932. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4933. cb(cur, "ffn_out", il);
  4934. } else {
  4935. // MoE branch
  4936. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4937. model.layers[il].ffn_norm, NULL,
  4938. LLM_NORM_RMS, cb, il);
  4939. cb(cur, "ffn_norm", il);
  4940. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  4941. cb(logits, "ffn_moe_logits", il);
  4942. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  4943. cb(probs, "ffn_moe_probs", il);
  4944. // select experts
  4945. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  4946. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  4947. ggml_tensor * weights = ggml_get_rows(ctx0,
  4948. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  4949. cb(weights, "ffn_moe_weights", il);
  4950. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  4951. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  4952. cb(weights_sum, "ffn_moe_weights_sum", il);
  4953. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  4954. cb(weights, "ffn_moe_weights_norm", il);
  4955. // compute expert outputs
  4956. ggml_tensor * moe_out = nullptr;
  4957. for (int i = 0; i < n_expert_used; ++i) {
  4958. ggml_tensor * cur_expert;
  4959. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  4960. cb(cur_up, "ffn_moe_up", il);
  4961. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  4962. cb(cur_gate, "ffn_moe_gate", il);
  4963. cur_gate = ggml_silu(ctx0, cur_gate);
  4964. cb(cur_gate, "ffn_moe_silu", il);
  4965. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  4966. cb(cur_expert, "ffn_moe_gate_par", il);
  4967. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  4968. cb(cur_expert, "ffn_moe_down", il);
  4969. cur_expert = ggml_mul(ctx0, cur_expert,
  4970. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  4971. cb(cur_expert, "ffn_moe_weighted", il);
  4972. if (i == 0) {
  4973. moe_out = cur_expert;
  4974. } else {
  4975. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  4976. cb(moe_out, "ffn_moe_out", il);
  4977. }
  4978. }
  4979. cur = moe_out;
  4980. }
  4981. cur = ggml_add(ctx0, cur, ffn_inp);
  4982. cb(cur, "l_out", il);
  4983. // input for next layer
  4984. inpL = cur;
  4985. }
  4986. cur = inpL;
  4987. cur = llm_build_norm(ctx0, cur, hparams,
  4988. model.output_norm, NULL,
  4989. LLM_NORM_RMS, cb, -1);
  4990. cb(cur, "result_norm", -1);
  4991. // lm_head
  4992. cur = ggml_mul_mat(ctx0, model.output, cur);
  4993. cb(cur, "result_output", -1);
  4994. ggml_build_forward_expand(gf, cur);
  4995. return gf;
  4996. }
  4997. struct ggml_cgraph * build_baichuan() {
  4998. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4999. const int64_t n_embd_head = hparams.n_embd_head_v;
  5000. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5001. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5002. struct ggml_tensor * cur;
  5003. struct ggml_tensor * inpL;
  5004. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5005. // inp_pos - contains the positions
  5006. struct ggml_tensor * inp_pos = build_inp_pos();
  5007. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5008. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5009. // positions of the tokens in the KV cache
  5010. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  5011. for (int il = 0; il < n_layer; ++il) {
  5012. struct ggml_tensor * inpSA = inpL;
  5013. cur = llm_build_norm(ctx0, inpL, hparams,
  5014. model.layers[il].attn_norm, NULL,
  5015. LLM_NORM_RMS, cb, il);
  5016. cb(cur, "attn_norm", il);
  5017. // self-attention
  5018. {
  5019. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5020. cb(Qcur, "Qcur", il);
  5021. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5022. cb(Kcur, "Kcur", il);
  5023. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5024. cb(Vcur, "Vcur", il);
  5025. switch (model.type) {
  5026. case MODEL_7B:
  5027. Qcur = ggml_rope_custom(
  5028. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5029. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5030. ext_factor, attn_factor, beta_fast, beta_slow
  5031. );
  5032. Kcur = ggml_rope_custom(
  5033. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5034. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5035. ext_factor, attn_factor, beta_fast, beta_slow
  5036. );
  5037. break;
  5038. case MODEL_13B:
  5039. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  5040. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  5041. break;
  5042. default:
  5043. GGML_ASSERT(false);
  5044. }
  5045. cb(Qcur, "Qcur", il);
  5046. cb(Kcur, "Kcur", il);
  5047. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5048. model.layers[il].wo, NULL,
  5049. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5050. }
  5051. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5052. cb(ffn_inp, "ffn_inp", il);
  5053. // feed-forward network
  5054. {
  5055. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5056. model.layers[il].ffn_norm, NULL,
  5057. LLM_NORM_RMS, cb, il);
  5058. cb(cur, "ffn_norm", il);
  5059. cur = llm_build_ffn(ctx0, cur,
  5060. model.layers[il].ffn_up, NULL,
  5061. model.layers[il].ffn_gate, NULL,
  5062. model.layers[il].ffn_down, NULL,
  5063. NULL,
  5064. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5065. cb(cur, "ffn_out", il);
  5066. }
  5067. cur = ggml_add(ctx0, cur, ffn_inp);
  5068. cb(cur, "l_out", il);
  5069. // input for next layer
  5070. inpL = cur;
  5071. }
  5072. cur = inpL;
  5073. cur = llm_build_norm(ctx0, cur, hparams,
  5074. model.output_norm, NULL,
  5075. LLM_NORM_RMS, cb, -1);
  5076. cb(cur, "result_norm", -1);
  5077. // lm_head
  5078. cur = ggml_mul_mat(ctx0, model.output, cur);
  5079. cb(cur, "result_output", -1);
  5080. ggml_build_forward_expand(gf, cur);
  5081. return gf;
  5082. }
  5083. struct ggml_cgraph * build_falcon() {
  5084. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5085. const int64_t n_embd_head = hparams.n_embd_head_v;
  5086. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5087. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5088. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5089. struct ggml_tensor * cur;
  5090. struct ggml_tensor * inpL;
  5091. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5092. // inp_pos - contains the positions
  5093. struct ggml_tensor * inp_pos = build_inp_pos();
  5094. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5095. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5096. for (int il = 0; il < n_layer; ++il) {
  5097. struct ggml_tensor * attn_norm;
  5098. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  5099. model.layers[il].attn_norm,
  5100. model.layers[il].attn_norm_b,
  5101. LLM_NORM, cb, il);
  5102. cb(attn_norm, "attn_norm", il);
  5103. // self-attention
  5104. {
  5105. if (model.layers[il].attn_norm_2) {
  5106. // Falcon-40B
  5107. cur = llm_build_norm(ctx0, inpL, hparams,
  5108. model.layers[il].attn_norm_2,
  5109. model.layers[il].attn_norm_2_b,
  5110. LLM_NORM, cb, il);
  5111. cb(cur, "attn_norm_2", il);
  5112. } else {
  5113. cur = attn_norm;
  5114. }
  5115. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5116. cb(cur, "wqkv", il);
  5117. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5118. 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)));
  5119. 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)));
  5120. cb(Qcur, "Qcur", il);
  5121. cb(Kcur, "Kcur", il);
  5122. cb(Vcur, "Vcur", il);
  5123. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5124. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5125. // using mode = 2 for neox mode
  5126. Qcur = ggml_rope_custom(
  5127. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5128. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5129. );
  5130. cb(Qcur, "Qcur", il);
  5131. Kcur = ggml_rope_custom(
  5132. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5133. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5134. );
  5135. cb(Kcur, "Kcur", il);
  5136. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5137. model.layers[il].wo, NULL,
  5138. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5139. }
  5140. struct ggml_tensor * ffn_inp = cur;
  5141. // feed forward
  5142. {
  5143. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  5144. model.layers[il].ffn_up, NULL,
  5145. NULL, NULL,
  5146. model.layers[il].ffn_down, NULL,
  5147. NULL,
  5148. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5149. cb(cur, "ffn_out", il);
  5150. }
  5151. cur = ggml_add(ctx0, cur, ffn_inp);
  5152. cb(cur, "l_out", il);
  5153. cur = ggml_add(ctx0, cur, inpL);
  5154. cb(cur, "l_out", il);
  5155. // input for next layer
  5156. inpL = cur;
  5157. }
  5158. cur = inpL;
  5159. // norm
  5160. cur = llm_build_norm(ctx0, cur, hparams,
  5161. model.output_norm,
  5162. model.output_norm_b,
  5163. LLM_NORM, cb, -1);
  5164. cb(cur, "result_norm", -1);
  5165. cur = ggml_mul_mat(ctx0, model.output, cur);
  5166. cb(cur, "result_output", -1);
  5167. ggml_build_forward_expand(gf, cur);
  5168. return gf;
  5169. }
  5170. struct ggml_cgraph * build_starcoder() {
  5171. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5172. const int64_t n_embd_head = hparams.n_embd_head_v;
  5173. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5174. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5175. struct ggml_tensor * cur;
  5176. struct ggml_tensor * inpL;
  5177. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5178. // inp_pos - contains the positions
  5179. struct ggml_tensor * inp_pos = build_inp_pos();
  5180. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5181. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5182. struct ggml_tensor * pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  5183. cb(pos, "pos_embd", -1);
  5184. inpL = ggml_add(ctx0, inpL, pos);
  5185. cb(inpL, "inpL", -1);
  5186. for (int il = 0; il < n_layer; ++il) {
  5187. cur = llm_build_norm(ctx0, inpL, hparams,
  5188. model.layers[il].attn_norm,
  5189. model.layers[il].attn_norm_b,
  5190. LLM_NORM, cb, il);
  5191. cb(cur, "attn_norm", il);
  5192. // self-attention
  5193. {
  5194. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5195. cb(cur, "wqkv", il);
  5196. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5197. cb(cur, "bqkv", il);
  5198. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5199. 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)));
  5200. 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)));
  5201. cb(Qcur, "Qcur", il);
  5202. cb(Kcur, "Kcur", il);
  5203. cb(Vcur, "Vcur", il);
  5204. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5205. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5206. model.layers[il].wo, model.layers[il].bo,
  5207. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5208. }
  5209. // add the input
  5210. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5211. cb(ffn_inp, "ffn_inp", il);
  5212. // FF
  5213. {
  5214. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5215. model.layers[il].ffn_norm,
  5216. model.layers[il].ffn_norm_b,
  5217. LLM_NORM, cb, il);
  5218. cb(cur, "ffn_norm", il);
  5219. cur = llm_build_ffn(ctx0, cur,
  5220. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5221. NULL, NULL,
  5222. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5223. NULL,
  5224. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5225. cb(cur, "ffn_out", il);
  5226. }
  5227. inpL = ggml_add(ctx0, cur, ffn_inp);
  5228. cb(inpL, "l_out", il);
  5229. }
  5230. cur = llm_build_norm(ctx0, inpL, hparams,
  5231. model.output_norm,
  5232. model.output_norm_b,
  5233. LLM_NORM, cb, -1);
  5234. cb(cur, "result_norm", -1);
  5235. cur = ggml_mul_mat(ctx0, model.output, cur);
  5236. cb(cur, "result_output", -1);
  5237. ggml_build_forward_expand(gf, cur);
  5238. return gf;
  5239. }
  5240. struct ggml_cgraph * build_persimmon() {
  5241. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5242. const int64_t n_embd_head = hparams.n_embd_head_v;
  5243. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5244. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  5245. struct ggml_tensor * cur;
  5246. struct ggml_tensor * inpL;
  5247. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5248. // inp_pos - contains the positions
  5249. struct ggml_tensor * inp_pos = build_inp_pos();
  5250. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5251. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5252. for (int il = 0; il < n_layer; ++il) {
  5253. struct ggml_tensor * residual = inpL;
  5254. cur = llm_build_norm(ctx0, inpL, hparams,
  5255. model.layers[il].attn_norm,
  5256. model.layers[il].attn_norm_b,
  5257. LLM_NORM, cb, il);
  5258. cb(cur, "attn_norm", il);
  5259. // self attention
  5260. {
  5261. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5262. cb(cur, "wqkv", il);
  5263. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5264. cb(cur, "bqkv", il);
  5265. // split qkv
  5266. GGML_ASSERT(n_head_kv == n_head);
  5267. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  5268. cb(tmpqkv, "tmpqkv", il);
  5269. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  5270. cb(tmpqkv_perm, "tmpqkv", il);
  5271. struct ggml_tensor * tmpq = ggml_view_3d(
  5272. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  5273. ggml_element_size(tmpqkv_perm) * n_embd_head,
  5274. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  5275. 0
  5276. );
  5277. cb(tmpq, "tmpq", il);
  5278. struct ggml_tensor * tmpk = ggml_view_3d(
  5279. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  5280. ggml_element_size(tmpqkv_perm) * n_embd_head,
  5281. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  5282. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  5283. );
  5284. cb(tmpk, "tmpk", il);
  5285. // Q/K Layernorm
  5286. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  5287. model.layers[il].attn_q_norm,
  5288. model.layers[il].attn_q_norm_b,
  5289. LLM_NORM, cb, il);
  5290. cb(tmpq, "tmpq", il);
  5291. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  5292. model.layers[il].attn_k_norm,
  5293. model.layers[il].attn_k_norm_b,
  5294. LLM_NORM, cb, il);
  5295. cb(tmpk, "tmpk", il);
  5296. // RoPE the first n_rot of q/k, pass the other half, and concat.
  5297. struct ggml_tensor * qrot = ggml_view_3d(
  5298. ctx0, tmpq, n_rot, n_head, n_tokens,
  5299. ggml_element_size(tmpq) * n_embd_head,
  5300. ggml_element_size(tmpq) * n_embd_head * n_head,
  5301. 0
  5302. );
  5303. cb(qrot, "qrot", il);
  5304. struct ggml_tensor * krot = ggml_view_3d(
  5305. ctx0, tmpk, n_rot, n_head, n_tokens,
  5306. ggml_element_size(tmpk) * n_embd_head,
  5307. ggml_element_size(tmpk) * n_embd_head * n_head,
  5308. 0
  5309. );
  5310. cb(krot, "krot", il);
  5311. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  5312. struct ggml_tensor * qpass = ggml_view_3d(
  5313. ctx0, tmpq, n_rot, n_head, n_tokens,
  5314. ggml_element_size(tmpq) * n_embd_head,
  5315. ggml_element_size(tmpq) * n_embd_head * n_head,
  5316. ggml_element_size(tmpq) * n_rot
  5317. );
  5318. cb(qpass, "qpass", il);
  5319. struct ggml_tensor * kpass = ggml_view_3d(
  5320. ctx0, tmpk, n_rot, n_head, n_tokens,
  5321. ggml_element_size(tmpk) * n_embd_head,
  5322. ggml_element_size(tmpk) * n_embd_head * n_head,
  5323. ggml_element_size(tmpk) * n_rot
  5324. );
  5325. cb(kpass, "kpass", il);
  5326. struct ggml_tensor * qrotated = ggml_rope_custom(
  5327. ctx0, qrot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5328. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5329. );
  5330. cb(qrotated, "qrotated", il);
  5331. struct ggml_tensor * krotated = ggml_rope_custom(
  5332. ctx0, krot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5333. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5334. );
  5335. cb(krotated, "krotated", il);
  5336. // ggml currently only supports concatenation on dim=2
  5337. // so we need to permute qrot, qpass, concat, then permute back.
  5338. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  5339. cb(qrotated, "qrotated", il);
  5340. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  5341. cb(krotated, "krotated", il);
  5342. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  5343. cb(qpass, "qpass", il);
  5344. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  5345. cb(kpass, "kpass", il);
  5346. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  5347. cb(Qcur, "Qcur", il);
  5348. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  5349. cb(Kcur, "Kcur", il);
  5350. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  5351. cb(Q, "Q", il);
  5352. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  5353. cb(Kcur, "Kcur", il);
  5354. struct ggml_tensor * Vcur = ggml_view_3d(
  5355. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  5356. ggml_element_size(tmpqkv_perm) * n_embd_head,
  5357. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  5358. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  5359. );
  5360. cb(Vcur, "Vcur", il);
  5361. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5362. model.layers[il].wo, model.layers[il].bo,
  5363. Kcur, Vcur, Q, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5364. }
  5365. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  5366. cb(ffn_inp, "ffn_inp", il);
  5367. // feed-forward network
  5368. {
  5369. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5370. model.layers[il].ffn_norm,
  5371. model.layers[il].ffn_norm_b,
  5372. LLM_NORM, cb, il);
  5373. cb(cur, "ffn_norm", il);
  5374. cur = llm_build_ffn(ctx0, cur,
  5375. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5376. NULL, NULL,
  5377. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5378. NULL,
  5379. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  5380. cb(cur, "ffn_out", il);
  5381. }
  5382. cur = ggml_add(ctx0, cur, ffn_inp);
  5383. cb(cur, "l_out", il);
  5384. inpL = cur;
  5385. }
  5386. cur = inpL;
  5387. cur = llm_build_norm(ctx0, cur, hparams,
  5388. model.output_norm,
  5389. model.output_norm_b,
  5390. LLM_NORM, cb, -1);
  5391. cb(cur, "result_norm", -1);
  5392. cur = ggml_mul_mat(ctx0, model.output, cur);
  5393. cb(cur, "result_output", -1);
  5394. ggml_build_forward_expand(gf, cur);
  5395. return gf;
  5396. }
  5397. struct ggml_cgraph * build_refact() {
  5398. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5399. const int64_t n_embd_head = hparams.n_embd_head_v;
  5400. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5401. struct ggml_tensor * cur;
  5402. struct ggml_tensor * inpL;
  5403. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5404. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5405. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5406. // positions of the tokens in the KV cache
  5407. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  5408. for (int il = 0; il < n_layer; ++il) {
  5409. struct ggml_tensor * inpSA = inpL;
  5410. cur = llm_build_norm(ctx0, inpL, hparams,
  5411. model.layers[il].attn_norm, NULL,
  5412. LLM_NORM_RMS, cb, il);
  5413. cb(cur, "attn_norm", il);
  5414. // self-attention
  5415. {
  5416. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5417. cb(Qcur, "Qcur", il);
  5418. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5419. cb(Kcur, "Kcur", il);
  5420. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5421. cb(Vcur, "Vcur", il);
  5422. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5423. cb(Kcur, "Kcur", il);
  5424. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5425. cb(Qcur, "Qcur", il);
  5426. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5427. model.layers[il].wo, NULL,
  5428. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5429. }
  5430. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5431. cb(ffn_inp, "ffn_inp", il);
  5432. // feed-forward network
  5433. {
  5434. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5435. model.layers[il].ffn_norm, NULL,
  5436. LLM_NORM_RMS, cb, il);
  5437. cb(cur, "ffn_norm", il);
  5438. cur = llm_build_ffn(ctx0, cur,
  5439. model.layers[il].ffn_up, NULL,
  5440. model.layers[il].ffn_gate, NULL,
  5441. model.layers[il].ffn_down, NULL,
  5442. NULL,
  5443. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5444. cb(cur, "ffn_out", il);
  5445. }
  5446. cur = ggml_add(ctx0, cur, ffn_inp);
  5447. cb(cur, "l_out", il);
  5448. // input for next layer
  5449. inpL = cur;
  5450. }
  5451. cur = inpL;
  5452. cur = llm_build_norm(ctx0, cur, hparams,
  5453. model.output_norm, NULL,
  5454. LLM_NORM_RMS, cb, -1);
  5455. cb(cur, "result_norm", -1);
  5456. // lm_head
  5457. cur = ggml_mul_mat(ctx0, model.output, cur);
  5458. cb(cur, "result_output", -1);
  5459. ggml_build_forward_expand(gf, cur);
  5460. return gf;
  5461. }
  5462. struct ggml_cgraph * build_bert() {
  5463. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5464. const int64_t n_embd_head = hparams.n_embd_head_v;
  5465. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5466. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5467. struct ggml_tensor * cur;
  5468. struct ggml_tensor * inpL;
  5469. struct ggml_tensor * inp_pos = build_inp_pos();
  5470. struct ggml_tensor * inp_mean = build_inp_mean();
  5471. struct ggml_tensor * inp_cls = build_inp_cls();
  5472. // construct input embeddings (token, type, position)
  5473. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5474. // token types are hardcoded to zero ("Sentence A")
  5475. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  5476. inpL = ggml_add(ctx0, inpL, type_row0);
  5477. if (model.arch == LLM_ARCH_BERT) {
  5478. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  5479. }
  5480. cb(inpL, "inp_embd", -1);
  5481. // embed layer norm
  5482. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  5483. cb(inpL, "inp_norm", -1);
  5484. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5485. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(false);
  5486. // iterate layers
  5487. for (int il = 0; il < n_layer; ++il) {
  5488. struct ggml_tensor * cur = inpL;
  5489. struct ggml_tensor * Qcur;
  5490. struct ggml_tensor * Kcur;
  5491. struct ggml_tensor * Vcur;
  5492. // self-attention
  5493. if (model.arch == LLM_ARCH_BERT) {
  5494. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  5495. cb(Qcur, "Qcur", il);
  5496. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  5497. cb(Kcur, "Kcur", il);
  5498. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  5499. cb(Vcur, "Vcur", il);
  5500. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5501. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5502. } else {
  5503. // compute Q and K and RoPE them
  5504. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5505. cb(cur, "wqkv", il);
  5506. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5507. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5508. 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)));
  5509. cb(Qcur, "Qcur", il);
  5510. cb(Kcur, "Kcur", il);
  5511. cb(Vcur, "Vcur", il);
  5512. Qcur = ggml_rope_custom(
  5513. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5514. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5515. ext_factor, attn_factor, beta_fast, beta_slow
  5516. );
  5517. cb(Qcur, "Qcur", il);
  5518. Kcur = ggml_rope_custom(
  5519. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5520. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5521. ext_factor, attn_factor, beta_fast, beta_slow
  5522. );
  5523. cb(Kcur, "Kcur", il);
  5524. }
  5525. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  5526. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  5527. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  5528. cb(kq, "kq", il);
  5529. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask, nullptr, 1.0f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  5530. cb(kq, "kq_soft_max_ext", il);
  5531. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  5532. cb(v, "v", il);
  5533. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  5534. cb(kqv, "kqv", il);
  5535. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  5536. cb(kqv_merged, "kqv_merged", il);
  5537. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  5538. cb(cur, "kqv_merged_cont", il);
  5539. ggml_build_forward_expand(gf, cur);
  5540. cur = ggml_mul_mat(ctx0, model.layers[il].wo, cur);
  5541. if (model.layers[il].bo) {
  5542. cb(cur, "kqv_wo", il);
  5543. }
  5544. if (model.layers[il].bo) {
  5545. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  5546. }
  5547. cb(cur, "kqv_out", il);
  5548. // re-add the layer input
  5549. cur = ggml_add(ctx0, cur, inpL);
  5550. // attention layer norm
  5551. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  5552. struct ggml_tensor * ffn_inp = cur;
  5553. cb(ffn_inp, "ffn_inp", il);
  5554. // feed-forward network
  5555. if (model.arch == LLM_ARCH_BERT) {
  5556. cur = llm_build_ffn(ctx0, cur,
  5557. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5558. NULL, NULL,
  5559. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5560. NULL,
  5561. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5562. } else {
  5563. cur = llm_build_ffn(ctx0, cur,
  5564. model.layers[il].ffn_up, NULL,
  5565. model.layers[il].ffn_gate, NULL,
  5566. model.layers[il].ffn_down, NULL,
  5567. NULL,
  5568. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5569. }
  5570. cb(cur, "ffn_out", il);
  5571. // attentions bypass the intermediate layer
  5572. cur = ggml_add(ctx0, cur, ffn_inp);
  5573. // output layer norm
  5574. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  5575. // input for next layer
  5576. inpL = cur;
  5577. }
  5578. // final output
  5579. cur = inpL;
  5580. cb(cur, "result_embd", -1);
  5581. // pooling layer
  5582. switch (pooling_type) {
  5583. case LLAMA_POOLING_TYPE_NONE:
  5584. {
  5585. // nop
  5586. } break;
  5587. case LLAMA_POOLING_TYPE_MEAN:
  5588. {
  5589. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, cur)), inp_mean);
  5590. cb(cur, "result_embd_pooled", -1);
  5591. } break;
  5592. case LLAMA_POOLING_TYPE_CLS:
  5593. {
  5594. cur = ggml_get_rows(ctx0, cur, inp_cls);
  5595. cb(cur, "result_embd_pooled", -1);
  5596. } break;
  5597. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  5598. {
  5599. GGML_ASSERT(false && "Invalid pooling type");
  5600. } break;
  5601. }
  5602. ggml_build_forward_expand(gf, cur);
  5603. return gf;
  5604. }
  5605. struct ggml_cgraph * build_bloom() {
  5606. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5607. const int64_t n_embd_head = hparams.n_embd_head_v;
  5608. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5609. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5610. struct ggml_tensor * cur;
  5611. struct ggml_tensor * inpL;
  5612. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5613. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5614. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5615. // positions of the tokens in the KV cache
  5616. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  5617. inpL = llm_build_norm(ctx0, inpL, hparams,
  5618. model.tok_norm,
  5619. model.tok_norm_b,
  5620. LLM_NORM, cb, -1);
  5621. cb(inpL, "inp_norm", -1);
  5622. for (int il = 0; il < n_layer; ++il) {
  5623. cur = llm_build_norm(ctx0, inpL, hparams,
  5624. model.layers[il].attn_norm,
  5625. model.layers[il].attn_norm_b,
  5626. LLM_NORM, cb, il);
  5627. cb(cur, "attn_norm", il);
  5628. // self-attention
  5629. {
  5630. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5631. cb(cur, "wqkv", il);
  5632. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5633. cb(cur, "bqkv", il);
  5634. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5635. 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)));
  5636. 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)));
  5637. cb(Qcur, "Qcur", il);
  5638. cb(Kcur, "Kcur", il);
  5639. cb(Vcur, "Vcur", il);
  5640. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5641. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5642. model.layers[il].wo, model.layers[il].bo,
  5643. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5644. }
  5645. // Add the input
  5646. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5647. cb(ffn_inp, "ffn_inp", il);
  5648. // FF
  5649. {
  5650. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5651. model.layers[il].ffn_norm,
  5652. model.layers[il].ffn_norm_b,
  5653. LLM_NORM, cb, il);
  5654. cb(cur, "ffn_norm", il);
  5655. cur = llm_build_ffn(ctx0, cur,
  5656. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5657. NULL, NULL,
  5658. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5659. NULL,
  5660. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5661. cb(cur, "ffn_out", il);
  5662. }
  5663. inpL = ggml_add(ctx0, cur, ffn_inp);
  5664. cb(inpL, "l_out", il);
  5665. }
  5666. cur = llm_build_norm(ctx0, inpL, hparams,
  5667. model.output_norm,
  5668. model.output_norm_b,
  5669. LLM_NORM, cb, -1);
  5670. cb(cur, "result_norm", -1);
  5671. cur = ggml_mul_mat(ctx0, model.output, cur);
  5672. cb(cur, "result_output", -1);
  5673. ggml_build_forward_expand(gf, cur);
  5674. return gf;
  5675. }
  5676. struct ggml_cgraph * build_mpt() {
  5677. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5678. const int64_t n_embd_head = hparams.n_embd_head_v;
  5679. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5680. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5681. struct ggml_tensor * cur;
  5682. struct ggml_tensor * inpL;
  5683. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5684. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5685. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5686. // positions of the tokens in the KV cache
  5687. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  5688. for (int il = 0; il < n_layer; ++il) {
  5689. struct ggml_tensor * attn_norm;
  5690. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  5691. model.layers[il].attn_norm,
  5692. model.layers[il].attn_norm_b,
  5693. LLM_NORM, cb, il);
  5694. cb(attn_norm, "attn_norm", il);
  5695. // self-attention
  5696. {
  5697. cur = attn_norm;
  5698. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5699. cb(cur, "wqkv", il);
  5700. if (model.layers[il].bqkv){
  5701. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5702. cb(cur, "bqkv", il);
  5703. }
  5704. if (hparams.f_clamp_kqv > 0.0f) {
  5705. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  5706. cb(cur, "wqkv_clamped", il);
  5707. }
  5708. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5709. 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)));
  5710. 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)));
  5711. cb(Qcur, "Qcur", il);
  5712. cb(Kcur, "Kcur", il);
  5713. cb(Vcur, "Vcur", il);
  5714. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5715. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5716. model.layers[il].wo, model.layers[il].bo,
  5717. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5718. }
  5719. // Add the input
  5720. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5721. cb(ffn_inp, "ffn_inp", il);
  5722. // feed forward
  5723. {
  5724. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5725. model.layers[il].ffn_norm,
  5726. model.layers[il].ffn_norm_b,
  5727. LLM_NORM, cb, il);
  5728. cb(cur, "ffn_norm", il);
  5729. cur = llm_build_ffn(ctx0, cur,
  5730. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5731. NULL, NULL,
  5732. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5733. model.layers[il].ffn_act,
  5734. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5735. cb(cur, "ffn_out", il);
  5736. }
  5737. cur = ggml_add(ctx0, cur, ffn_inp);
  5738. cb(cur, "l_out", il);
  5739. // input for next layer
  5740. inpL = cur;
  5741. }
  5742. cur = inpL;
  5743. cur = llm_build_norm(ctx0, cur, hparams,
  5744. model.output_norm,
  5745. model.output_norm_b,
  5746. LLM_NORM, cb, -1);
  5747. cb(cur, "result_norm", -1);
  5748. cur = ggml_mul_mat(ctx0, model.output, cur);
  5749. cb(cur, "result_output", -1);
  5750. ggml_build_forward_expand(gf, cur);
  5751. return gf;
  5752. }
  5753. struct ggml_cgraph * build_stablelm() {
  5754. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  5755. const int64_t n_embd_head = hparams.n_embd_head_v;
  5756. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5757. struct ggml_tensor * cur;
  5758. struct ggml_tensor * inpL;
  5759. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5760. // inp_pos - contains the positions
  5761. struct ggml_tensor * inp_pos = build_inp_pos();
  5762. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5763. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5764. for (int il = 0; il < n_layer; ++il) {
  5765. struct ggml_tensor * inpSA = inpL;
  5766. // norm
  5767. cur = llm_build_norm(ctx0, inpL, hparams,
  5768. model.layers[il].attn_norm,
  5769. model.layers[il].attn_norm_b,
  5770. LLM_NORM, cb, il);
  5771. cb(cur, "attn_norm", il);
  5772. // self-attention
  5773. {
  5774. // compute Q and K and RoPE them
  5775. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5776. cb(Qcur, "Qcur", il);
  5777. if (model.layers[il].bq) {
  5778. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5779. cb(Qcur, "Qcur", il);
  5780. }
  5781. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5782. cb(Kcur, "Kcur", il);
  5783. if (model.layers[il].bk) {
  5784. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5785. cb(Kcur, "Kcur", il);
  5786. }
  5787. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5788. cb(Vcur, "Vcur", il);
  5789. if (model.layers[il].bv) {
  5790. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5791. cb(Vcur, "Vcur", il);
  5792. }
  5793. Qcur = ggml_rope_custom(
  5794. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5795. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5796. ext_factor, attn_factor, beta_fast, beta_slow
  5797. );
  5798. cb(Qcur, "Qcur", il);
  5799. Kcur = ggml_rope_custom(
  5800. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5801. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5802. ext_factor, attn_factor, beta_fast, beta_slow
  5803. );
  5804. cb(Kcur, "Kcur", il);
  5805. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5806. model.layers[il].wo, NULL,
  5807. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5808. }
  5809. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5810. cb(ffn_inp, "ffn_inp", il);
  5811. // feed-forward network
  5812. {
  5813. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5814. model.layers[il].ffn_norm,
  5815. model.layers[il].ffn_norm_b,
  5816. LLM_NORM, cb, il);
  5817. cb(cur, "ffn_norm", il);
  5818. cur = llm_build_ffn(ctx0, cur,
  5819. model.layers[il].ffn_up, NULL,
  5820. model.layers[il].ffn_gate, NULL,
  5821. model.layers[il].ffn_down, NULL,
  5822. NULL,
  5823. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5824. cb(cur, "ffn_out", il);
  5825. }
  5826. cur = ggml_add(ctx0, cur, ffn_inp);
  5827. cb(cur, "l_out", il);
  5828. // input for next layer
  5829. inpL = cur;
  5830. }
  5831. cur = inpL;
  5832. cur = llm_build_norm(ctx0, cur, hparams,
  5833. model.output_norm,
  5834. model.output_norm_b,
  5835. LLM_NORM, cb, -1);
  5836. cb(cur, "result_norm", -1);
  5837. // lm_head
  5838. cur = ggml_mul_mat(ctx0, model.output, cur);
  5839. cb(cur, "result_output", -1);
  5840. ggml_build_forward_expand(gf, cur);
  5841. return gf;
  5842. }
  5843. struct ggml_cgraph * build_qwen() {
  5844. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5845. const int64_t n_embd_head = hparams.n_embd_head_v;
  5846. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5847. struct ggml_tensor * cur;
  5848. struct ggml_tensor * inpL;
  5849. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5850. // inp_pos - contains the positions
  5851. struct ggml_tensor * inp_pos = build_inp_pos();
  5852. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5853. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5854. for (int il = 0; il < n_layer; ++il) {
  5855. struct ggml_tensor * inpSA = inpL;
  5856. cur = llm_build_norm(ctx0, inpL, hparams,
  5857. model.layers[il].attn_norm, NULL,
  5858. LLM_NORM_RMS, cb, il);
  5859. cb(cur, "attn_norm", il);
  5860. // self-attention
  5861. {
  5862. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5863. cb(cur, "wqkv", il);
  5864. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5865. cb(cur, "bqkv", il);
  5866. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5867. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5868. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  5869. cb(Qcur, "Qcur", il);
  5870. cb(Kcur, "Kcur", il);
  5871. cb(Vcur, "Vcur", il);
  5872. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5873. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5874. // using mode = 2 for neox mode
  5875. Qcur = ggml_rope_custom(
  5876. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5877. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5878. );
  5879. cb(Qcur, "Qcur", il);
  5880. Kcur = ggml_rope_custom(
  5881. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5882. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5883. );
  5884. cb(Kcur, "Kcur", il);
  5885. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5886. model.layers[il].wo, NULL,
  5887. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5888. }
  5889. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5890. cb(ffn_inp, "ffn_inp", il);
  5891. // feed-forward forward
  5892. {
  5893. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5894. model.layers[il].ffn_norm, NULL,
  5895. LLM_NORM_RMS, cb, il);
  5896. cb(cur, "ffn_norm", il);
  5897. cur = llm_build_ffn(ctx0, cur,
  5898. model.layers[il].ffn_up, NULL,
  5899. model.layers[il].ffn_gate, NULL,
  5900. model.layers[il].ffn_down, NULL,
  5901. NULL,
  5902. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5903. cb(cur, "ffn_out", il);
  5904. }
  5905. cur = ggml_add(ctx0, cur, ffn_inp);
  5906. cb(cur, "l_out", il);
  5907. // input for next layer
  5908. inpL = cur;
  5909. }
  5910. cur = inpL;
  5911. cur = llm_build_norm(ctx0, cur, hparams,
  5912. model.output_norm, NULL,
  5913. LLM_NORM_RMS, cb, -1);
  5914. cb(cur, "result_norm", -1);
  5915. // lm_head
  5916. cur = ggml_mul_mat(ctx0, model.output, cur);
  5917. cb(cur, "result_output", -1);
  5918. ggml_build_forward_expand(gf, cur);
  5919. return gf;
  5920. }
  5921. struct ggml_cgraph * build_qwen2() {
  5922. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5923. const int64_t n_embd_head = hparams.n_embd_head_v;
  5924. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5925. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5926. struct ggml_tensor * cur;
  5927. struct ggml_tensor * inpL;
  5928. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5929. // inp_pos - contains the positions
  5930. struct ggml_tensor * inp_pos = build_inp_pos();
  5931. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5932. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5933. for (int il = 0; il < n_layer; ++il) {
  5934. struct ggml_tensor * inpSA = inpL;
  5935. // norm
  5936. cur = llm_build_norm(ctx0, inpL, hparams,
  5937. model.layers[il].attn_norm, NULL,
  5938. LLM_NORM_RMS, cb, il);
  5939. cb(cur, "attn_norm", il);
  5940. // self-attention
  5941. {
  5942. // compute Q and K and RoPE them
  5943. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5944. cb(Qcur, "Qcur", il);
  5945. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5946. cb(Qcur, "Qcur", il);
  5947. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5948. cb(Kcur, "Kcur", il);
  5949. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5950. cb(Kcur, "Kcur", il);
  5951. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5952. cb(Vcur, "Vcur", il);
  5953. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5954. cb(Vcur, "Vcur", il);
  5955. // these nodes are added to the graph together so that they are not reordered
  5956. // by doing so, the number of splits in the graph is reduced
  5957. ggml_build_forward_expand(gf, Qcur);
  5958. ggml_build_forward_expand(gf, Kcur);
  5959. ggml_build_forward_expand(gf, Vcur);
  5960. Qcur = ggml_rope_custom(
  5961. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5962. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5963. ext_factor, attn_factor, beta_fast, beta_slow
  5964. );
  5965. cb(Qcur, "Qcur", il);
  5966. Kcur = ggml_rope_custom(
  5967. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5968. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5969. ext_factor, attn_factor, beta_fast, beta_slow
  5970. );
  5971. cb(Kcur, "Kcur", il);
  5972. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5973. model.layers[il].wo, model.layers[il].bo,
  5974. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5975. }
  5976. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5977. cb(ffn_inp, "ffn_inp", il);
  5978. // feed-forward network
  5979. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5980. model.layers[il].ffn_norm, NULL,
  5981. LLM_NORM_RMS, cb, il);
  5982. cb(cur, "ffn_norm", il);
  5983. cur = llm_build_ffn(ctx0, cur,
  5984. model.layers[il].ffn_up, NULL,
  5985. model.layers[il].ffn_gate, NULL,
  5986. model.layers[il].ffn_down, NULL,
  5987. NULL,
  5988. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5989. cb(cur, "ffn_out", il);
  5990. cur = ggml_add(ctx0, cur, ffn_inp);
  5991. cb(cur, "l_out", il);
  5992. // input for next layer
  5993. inpL = cur;
  5994. }
  5995. cur = inpL;
  5996. cur = llm_build_norm(ctx0, cur, hparams,
  5997. model.output_norm, NULL,
  5998. LLM_NORM_RMS, cb, -1);
  5999. cb(cur, "result_norm", -1);
  6000. // lm_head
  6001. cur = ggml_mul_mat(ctx0, model.output, cur);
  6002. cb(cur, "result_output", -1);
  6003. ggml_build_forward_expand(gf, cur);
  6004. return gf;
  6005. }
  6006. struct ggml_cgraph * build_phi2() {
  6007. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6008. const int64_t n_embd_head = hparams.n_embd_head_v;
  6009. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6010. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6011. struct ggml_tensor * cur;
  6012. struct ggml_tensor * attn_norm_output;
  6013. struct ggml_tensor * ffn_output;
  6014. struct ggml_tensor * inpL;
  6015. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6016. // inp_pos - contains the positions
  6017. struct ggml_tensor * inp_pos = build_inp_pos();
  6018. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6019. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6020. for (int il = 0; il < n_layer; ++il) {
  6021. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  6022. model.layers[il].attn_norm,
  6023. model.layers[il].attn_norm_b,
  6024. LLM_NORM, cb, il);
  6025. cb(attn_norm_output, "attn_norm", il);
  6026. // self-attention
  6027. {
  6028. struct ggml_tensor * Qcur = nullptr;
  6029. struct ggml_tensor * Kcur = nullptr;
  6030. struct ggml_tensor * Vcur = nullptr;
  6031. if (model.layers[il].wqkv) {
  6032. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  6033. cb(cur, "wqkv", il);
  6034. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6035. cb(cur, "bqkv", il);
  6036. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6037. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6038. 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)));
  6039. } else {
  6040. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  6041. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  6042. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  6043. }
  6044. cb(Qcur, "Qcur", il);
  6045. cb(Kcur, "Kcur", il);
  6046. cb(Vcur, "Vcur", il);
  6047. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6048. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6049. Qcur = ggml_rope_custom(
  6050. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6051. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6052. );
  6053. cb(Qcur, "Qcur", il);
  6054. // with phi2, we scale the Q to avoid precision issues
  6055. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  6056. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  6057. cb(Qcur, "Qcur", il);
  6058. Kcur = ggml_rope_custom(
  6059. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6060. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6061. );
  6062. cb(Kcur, "Kcur", il);
  6063. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6064. model.layers[il].wo, model.layers[il].bo,
  6065. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  6066. }
  6067. // FF
  6068. {
  6069. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  6070. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6071. NULL, NULL,
  6072. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6073. NULL,
  6074. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6075. cb(ffn_output, "ffn_out", il);
  6076. }
  6077. cur = ggml_add(ctx0, cur, ffn_output);
  6078. cb(cur, "l_out", il);
  6079. cur = ggml_add(ctx0, cur, inpL);
  6080. cb(cur, "l_out", il);
  6081. inpL = cur;
  6082. }
  6083. cur = llm_build_norm(ctx0, inpL, hparams,
  6084. model.output_norm,
  6085. model.output_norm_b,
  6086. LLM_NORM, cb, -1);
  6087. cb(cur, "result_norm", -1);
  6088. cur = ggml_mul_mat(ctx0, model.output, cur);
  6089. cb(cur, "result_output_no_bias", -1);
  6090. cur = ggml_add(ctx0, cur, model.output_b);
  6091. cb(cur, "result_output", -1);
  6092. ggml_build_forward_expand(gf, cur);
  6093. return gf;
  6094. }
  6095. struct ggml_cgraph * build_plamo() {
  6096. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  6097. const int64_t n_embd_head = hparams.n_embd_head_v;
  6098. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6099. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6100. struct ggml_tensor * cur;
  6101. struct ggml_tensor * inpL;
  6102. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6103. // inp_pos - contains the positions
  6104. struct ggml_tensor * inp_pos = build_inp_pos();
  6105. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6106. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6107. for (int il = 0; il < n_layer; ++il) {
  6108. // norm
  6109. cur = llm_build_norm(ctx0, inpL, hparams,
  6110. model.layers[il].attn_norm, NULL,
  6111. LLM_NORM_RMS, cb, il);
  6112. cb(cur, "attn_norm", il);
  6113. struct ggml_tensor * attention_norm = cur;
  6114. // self-attention
  6115. {
  6116. // compute Q and K and RoPE them
  6117. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6118. cb(Qcur, "Qcur", il);
  6119. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6120. cb(Kcur, "Kcur", il);
  6121. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6122. cb(Vcur, "Vcur", il);
  6123. Qcur = ggml_rope_custom(
  6124. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos,
  6125. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6126. ext_factor, attn_factor, beta_fast, beta_slow);
  6127. cb(Qcur, "Qcur", il);
  6128. Kcur = ggml_rope_custom(
  6129. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos,
  6130. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6131. ext_factor, attn_factor, beta_fast, beta_slow);
  6132. cb(Kcur, "Kcur", il);
  6133. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6134. model.layers[il].wo, NULL,
  6135. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6136. }
  6137. struct ggml_tensor * sa_out = cur;
  6138. cur = attention_norm;
  6139. // feed-forward network
  6140. {
  6141. cur = llm_build_ffn(ctx0, cur,
  6142. model.layers[il].ffn_up, NULL,
  6143. model.layers[il].ffn_gate, NULL,
  6144. model.layers[il].ffn_down, NULL,
  6145. NULL,
  6146. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6147. cb(cur, "ffn_out", il);
  6148. }
  6149. cur = ggml_add(ctx0, cur, sa_out);
  6150. cb(cur, "l_out", il);
  6151. cur = ggml_add(ctx0, cur, inpL);
  6152. cb(cur, "l_out", il);
  6153. // input for next layer
  6154. inpL = cur;
  6155. }
  6156. cur = inpL;
  6157. cur = llm_build_norm(ctx0, cur, hparams,
  6158. model.output_norm, NULL,
  6159. LLM_NORM_RMS, cb, -1);
  6160. cb(cur, "result_norm", -1);
  6161. // lm_head
  6162. cur = ggml_mul_mat(ctx0, model.output, cur);
  6163. cb(cur, "result_output", -1);
  6164. ggml_build_forward_expand(gf, cur);
  6165. return gf;
  6166. }
  6167. struct ggml_cgraph * build_gpt2() {
  6168. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6169. const int64_t n_embd_head = hparams.n_embd_head_v;
  6170. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6171. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6172. struct ggml_tensor * cur;
  6173. struct ggml_tensor * pos;
  6174. struct ggml_tensor * inpL;
  6175. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6176. // inp_pos - contains the positions
  6177. struct ggml_tensor * inp_pos = build_inp_pos();
  6178. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6179. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6180. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  6181. cb(pos, "pos_embd", -1);
  6182. inpL = ggml_add(ctx0, inpL, pos);
  6183. cb(inpL, "inpL", -1);
  6184. for (int il = 0; il < n_layer; ++il) {
  6185. cur = llm_build_norm(ctx0, inpL, hparams,
  6186. model.layers[il].attn_norm,
  6187. model.layers[il].attn_norm_b,
  6188. LLM_NORM, cb, il);
  6189. cb(cur, "attn_norm", il);
  6190. // self-attention
  6191. {
  6192. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6193. cb(cur, "wqkv", il);
  6194. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6195. cb(cur, "bqkv", il);
  6196. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6197. 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)));
  6198. 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)));
  6199. cb(Qcur, "Qcur", il);
  6200. cb(Kcur, "Kcur", il);
  6201. cb(Vcur, "Vcur", il);
  6202. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6203. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6204. model.layers[il].wo, model.layers[il].bo,
  6205. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6206. }
  6207. // add the input
  6208. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6209. cb(ffn_inp, "ffn_inp", il);
  6210. // FF
  6211. {
  6212. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6213. model.layers[il].ffn_norm,
  6214. model.layers[il].ffn_norm_b,
  6215. LLM_NORM, cb, il);
  6216. cb(cur, "ffn_norm", il);
  6217. cur = llm_build_ffn(ctx0, cur,
  6218. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6219. NULL, NULL,
  6220. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6221. NULL,
  6222. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6223. cb(cur, "ffn_out", il);
  6224. }
  6225. inpL = ggml_add(ctx0, cur, ffn_inp);
  6226. cb(inpL, "l_out", il);
  6227. }
  6228. cur = llm_build_norm(ctx0, inpL, hparams,
  6229. model.output_norm,
  6230. model.output_norm_b,
  6231. LLM_NORM, cb, -1);
  6232. cb(cur, "result_norm", -1);
  6233. cur = ggml_mul_mat(ctx0, model.output, cur);
  6234. cb(cur, "result_output", -1);
  6235. ggml_build_forward_expand(gf, cur);
  6236. return gf;
  6237. }
  6238. struct ggml_cgraph * build_codeshell() {
  6239. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6240. const int64_t n_embd_head = hparams.n_embd_head_v;
  6241. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6242. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6243. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6244. struct ggml_tensor * cur;
  6245. struct ggml_tensor * inpL;
  6246. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6247. // inp_pos - contains the positions
  6248. struct ggml_tensor * inp_pos = build_inp_pos();
  6249. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6250. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6251. for (int il = 0; il < n_layer; ++il) {
  6252. cur = llm_build_norm(ctx0, inpL, hparams,
  6253. model.layers[il].attn_norm,
  6254. model.layers[il].attn_norm_b,
  6255. LLM_NORM, cb, il);
  6256. cb(cur, "attn_norm", il);
  6257. // self-attention
  6258. {
  6259. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6260. cb(cur, "wqkv", il);
  6261. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6262. cb(cur, "bqkv", il);
  6263. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6264. struct ggml_tensor * tmpk = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6265. 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)));
  6266. cb(tmpq, "tmpq", il);
  6267. cb(tmpk, "tmpk", il);
  6268. cb(Vcur, "Vcur", il);
  6269. struct ggml_tensor * Qcur = ggml_rope_custom(
  6270. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  6271. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6272. ext_factor, attn_factor, beta_fast, beta_slow
  6273. );
  6274. cb(Qcur, "Qcur", il);
  6275. struct ggml_tensor * Kcur = ggml_rope_custom(
  6276. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6277. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6278. ext_factor, attn_factor, beta_fast, beta_slow
  6279. );
  6280. cb(Kcur, "Kcur", il);
  6281. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6282. model.layers[il].wo, model.layers[il].bo,
  6283. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6284. }
  6285. // add the input
  6286. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6287. cb(ffn_inp, "ffn_inp", il);
  6288. // FF
  6289. {
  6290. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6291. model.layers[il].ffn_norm,
  6292. model.layers[il].ffn_norm_b,
  6293. LLM_NORM, cb, il);
  6294. cb(cur, "ffn_norm", il);
  6295. cur = llm_build_ffn(ctx0, cur,
  6296. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6297. NULL, NULL,
  6298. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6299. NULL,
  6300. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6301. cb(cur, "ffn_out", il);
  6302. }
  6303. inpL = ggml_add(ctx0, cur, ffn_inp);
  6304. cb(inpL, "l_out", il);
  6305. }
  6306. cur = llm_build_norm(ctx0, inpL, hparams,
  6307. model.output_norm,
  6308. model.output_norm_b,
  6309. LLM_NORM, cb, -1);
  6310. cb(cur, "result_norm", -1);
  6311. cur = ggml_mul_mat(ctx0, model.output, cur);
  6312. cb(cur, "result_output", -1);
  6313. ggml_build_forward_expand(gf, cur);
  6314. return gf;
  6315. }
  6316. struct ggml_cgraph * build_orion() {
  6317. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6318. const int64_t n_embd_head = hparams.n_embd_head_v;
  6319. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6320. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6321. struct ggml_tensor * cur;
  6322. struct ggml_tensor * inpL;
  6323. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6324. // inp_pos - contains the positions
  6325. struct ggml_tensor * inp_pos = build_inp_pos();
  6326. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6327. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6328. for (int il = 0; il < n_layer; ++il) {
  6329. struct ggml_tensor * inpSA = inpL;
  6330. // norm
  6331. cur = llm_build_norm(ctx0, inpL, hparams,
  6332. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  6333. LLM_NORM, cb, il);
  6334. cb(cur, "attn_norm", il);
  6335. // self-attention
  6336. {
  6337. // compute Q and K and RoPE them
  6338. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6339. cb(Qcur, "Qcur", il);
  6340. // if (model.layers[il].bq) {
  6341. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6342. // cb(Qcur, "Qcur", il);
  6343. // }
  6344. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6345. cb(Kcur, "Kcur", il);
  6346. // if (model.layers[il].bk) {
  6347. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6348. // cb(Kcur, "Kcur", il);
  6349. // }
  6350. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6351. cb(Vcur, "Vcur", il);
  6352. // if (model.layers[il].bv) {
  6353. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6354. // cb(Vcur, "Vcur", il);
  6355. // }
  6356. Qcur = ggml_rope_custom(
  6357. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6358. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6359. ext_factor, attn_factor, beta_fast, beta_slow
  6360. );
  6361. cb(Qcur, "Qcur", il);
  6362. Kcur = ggml_rope_custom(
  6363. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6364. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6365. ext_factor, attn_factor, beta_fast, beta_slow
  6366. );
  6367. cb(Kcur, "Kcur", il);
  6368. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6369. model.layers[il].wo, NULL,
  6370. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6371. }
  6372. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6373. cb(ffn_inp, "ffn_inp", il);
  6374. // feed-forward network
  6375. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6376. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  6377. LLM_NORM, cb, il);
  6378. cb(cur, "ffn_norm", il);
  6379. cur = llm_build_ffn(ctx0, cur,
  6380. model.layers[il].ffn_up, NULL,
  6381. model.layers[il].ffn_gate, NULL,
  6382. model.layers[il].ffn_down, NULL,
  6383. NULL,
  6384. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6385. cb(cur, "ffn_out", il);
  6386. cur = ggml_add(ctx0, cur, ffn_inp);
  6387. cb(cur, "l_out", il);
  6388. // input for next layer
  6389. inpL = cur;
  6390. }
  6391. cur = inpL;
  6392. cur = llm_build_norm(ctx0, cur, hparams,
  6393. model.output_norm, model.output_norm_b,
  6394. LLM_NORM, cb, -1);
  6395. cb(cur, "result_norm", -1);
  6396. // lm_head
  6397. cur = ggml_mul_mat(ctx0, model.output, cur);
  6398. cb(cur, "result_output", -1);
  6399. ggml_build_forward_expand(gf, cur);
  6400. return gf;
  6401. }
  6402. struct ggml_cgraph * build_internlm2() {
  6403. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6404. const int64_t n_embd_head = hparams.n_embd_head_v;
  6405. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6406. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6407. struct ggml_tensor * cur;
  6408. struct ggml_tensor * inpL;
  6409. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6410. // inp_pos - contains the positions
  6411. struct ggml_tensor * inp_pos = build_inp_pos();
  6412. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6413. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6414. for (int il = 0; il < n_layer; ++il) {
  6415. struct ggml_tensor * inpSA = inpL;
  6416. // norm
  6417. cur = llm_build_norm(ctx0, inpL, hparams,
  6418. model.layers[il].attn_norm, NULL,
  6419. LLM_NORM_RMS, cb, il);
  6420. cb(cur, "attn_norm", il);
  6421. // self-attention
  6422. {
  6423. // compute Q and K and RoPE them
  6424. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6425. cb(Qcur, "Qcur", il);
  6426. if (model.layers[il].bq) {
  6427. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6428. cb(Qcur, "Qcur", il);
  6429. }
  6430. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6431. cb(Kcur, "Kcur", il);
  6432. if (model.layers[il].bk) {
  6433. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6434. cb(Kcur, "Kcur", il);
  6435. }
  6436. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6437. cb(Vcur, "Vcur", il);
  6438. if (model.layers[il].bv) {
  6439. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6440. cb(Vcur, "Vcur", il);
  6441. }
  6442. Qcur = ggml_rope_custom(
  6443. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6444. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6445. ext_factor, attn_factor, beta_fast, beta_slow
  6446. );
  6447. cb(Qcur, "Qcur", il);
  6448. Kcur = ggml_rope_custom(
  6449. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6450. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6451. ext_factor, attn_factor, beta_fast, beta_slow
  6452. );
  6453. cb(Kcur, "Kcur", il);
  6454. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6455. model.layers[il].wo, model.layers[il].bo,
  6456. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6457. }
  6458. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6459. cb(ffn_inp, "ffn_inp", il);
  6460. // feed-forward network
  6461. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6462. model.layers[il].ffn_norm, NULL,
  6463. LLM_NORM_RMS, cb, il);
  6464. cb(cur, "ffn_norm", il);
  6465. cur = llm_build_ffn(ctx0, cur,
  6466. model.layers[il].ffn_up, NULL,
  6467. model.layers[il].ffn_gate, NULL,
  6468. model.layers[il].ffn_down, NULL,
  6469. NULL,
  6470. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6471. cb(cur, "ffn_out", il);
  6472. cur = ggml_add(ctx0, cur, ffn_inp);
  6473. cb(cur, "l_out", il);
  6474. // input for next layer
  6475. inpL = cur;
  6476. }
  6477. cur = inpL;
  6478. cur = llm_build_norm(ctx0, cur, hparams,
  6479. model.output_norm, NULL,
  6480. LLM_NORM_RMS, cb, -1);
  6481. cb(cur, "result_norm", -1);
  6482. // lm_head
  6483. cur = ggml_mul_mat(ctx0, model.output, cur);
  6484. cb(cur, "result_output", -1);
  6485. ggml_build_forward_expand(gf, cur);
  6486. return gf;
  6487. }
  6488. // ref: https://arxiv.org/abs/2203.03466
  6489. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  6490. // based on the original build_llama() function
  6491. struct ggml_cgraph * build_minicpm() {
  6492. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6493. const int64_t n_embd_head = hparams.n_embd_head_v;
  6494. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6495. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6496. const int64_t n_embd = hparams.n_embd;
  6497. //TODO: if the model varies, these parameters need to be read from the model
  6498. const int64_t n_embd_base = 256;
  6499. const float scale_embd = 12.0f;
  6500. const float scale_depth = 1.4f;
  6501. struct ggml_tensor * cur;
  6502. struct ggml_tensor * inpL;
  6503. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6504. // scale the input embeddings
  6505. inpL = ggml_scale(ctx0, inpL, scale_embd);
  6506. cb(inpL, "inp_scaled", -1);
  6507. // inp_pos - contains the positions
  6508. struct ggml_tensor * inp_pos = build_inp_pos();
  6509. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6510. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6511. for (int il = 0; il < n_layer; ++il) {
  6512. struct ggml_tensor * inpSA = inpL;
  6513. // norm
  6514. cur = llm_build_norm(ctx0, inpL, hparams,
  6515. model.layers[il].attn_norm, NULL,
  6516. LLM_NORM_RMS, cb, il);
  6517. cb(cur, "attn_norm", il);
  6518. // self-attention
  6519. {
  6520. // compute Q and K and RoPE them
  6521. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6522. cb(Qcur, "Qcur", il);
  6523. if (model.layers[il].bq) {
  6524. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6525. cb(Qcur, "Qcur", il);
  6526. }
  6527. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6528. cb(Kcur, "Kcur", il);
  6529. if (model.layers[il].bk) {
  6530. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6531. cb(Kcur, "Kcur", il);
  6532. }
  6533. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6534. cb(Vcur, "Vcur", il);
  6535. if (model.layers[il].bv) {
  6536. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6537. cb(Vcur, "Vcur", il);
  6538. }
  6539. Qcur = ggml_rope_custom(
  6540. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6541. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6542. ext_factor, attn_factor, beta_fast, beta_slow
  6543. );
  6544. cb(Qcur, "Qcur", il);
  6545. Kcur = ggml_rope_custom(
  6546. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6547. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6548. ext_factor, attn_factor, beta_fast, beta_slow
  6549. );
  6550. cb(Kcur, "Kcur", il);
  6551. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6552. model.layers[il].wo, model.layers[il].bo,
  6553. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6554. }
  6555. // scale_res - scale the hidden states for residual connection
  6556. const float scale_res = scale_depth/sqrtf(float(n_layer));
  6557. cur = ggml_scale(ctx0, cur, scale_res);
  6558. cb(cur, "hidden_scaled", -1);
  6559. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6560. cb(ffn_inp, "ffn_inp", il);
  6561. // feed-forward network
  6562. {
  6563. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6564. model.layers[il].ffn_norm, NULL,
  6565. LLM_NORM_RMS, cb, il);
  6566. cb(cur, "ffn_norm", il);
  6567. cur = llm_build_ffn(ctx0, cur,
  6568. model.layers[il].ffn_up, NULL,
  6569. model.layers[il].ffn_gate, NULL,
  6570. model.layers[il].ffn_down, NULL,
  6571. NULL,
  6572. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6573. cb(cur, "ffn_out", il);
  6574. }
  6575. // scale the hidden states for residual connection
  6576. cur = ggml_scale(ctx0, cur, scale_res);
  6577. cb(cur, "hidden_scaled_ffn", -1);
  6578. cur = ggml_add(ctx0, cur, ffn_inp);
  6579. cb(cur, "l_out", il);
  6580. // input for next layer
  6581. inpL = cur;
  6582. }
  6583. cur = inpL;
  6584. cur = llm_build_norm(ctx0, cur, hparams,
  6585. model.output_norm, NULL,
  6586. LLM_NORM_RMS, cb, -1);
  6587. cb(cur, "result_norm", -1);
  6588. // lm_head scaling
  6589. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  6590. cur = ggml_scale(ctx0, cur, scale_lmhead);
  6591. cb(cur, "lmhead_scaling", -1);
  6592. // lm_head
  6593. cur = ggml_mul_mat(ctx0, model.tok_embd, cur);
  6594. cb(cur, "result_output", -1);
  6595. ggml_build_forward_expand(gf, cur);
  6596. return gf;
  6597. }
  6598. struct ggml_cgraph * build_gemma() {
  6599. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6600. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  6601. struct ggml_tensor * cur;
  6602. struct ggml_tensor * inpL;
  6603. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6604. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  6605. cb(inpL, "inp_scaled", -1);
  6606. // inp_pos - contains the positions
  6607. struct ggml_tensor * inp_pos = build_inp_pos();
  6608. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6609. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6610. for (int il = 0; il < n_layer; ++il) {
  6611. // norm
  6612. cur = llm_build_norm(ctx0, inpL, hparams,
  6613. model.layers[il].attn_norm, NULL,
  6614. LLM_NORM_RMS, cb, il);
  6615. cb(cur, "attn_norm", il);
  6616. // self-attention
  6617. {
  6618. // compute Q and K and RoPE them
  6619. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6620. cb(Qcur, "Qcur", il);
  6621. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6622. cb(Kcur, "Kcur", il);
  6623. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6624. cb(Vcur, "Vcur", il);
  6625. Qcur = ggml_rope_custom(
  6626. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos,
  6627. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6628. ext_factor, attn_factor, beta_fast, beta_slow);
  6629. cb(Qcur, "Qcur", il);
  6630. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  6631. cb(Qcur, "Qcur_scaled", il);
  6632. Kcur = ggml_rope_custom(
  6633. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos,
  6634. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6635. ext_factor, attn_factor, beta_fast, beta_slow);
  6636. cb(Kcur, "Kcur", il);
  6637. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6638. model.layers[il].wo, NULL,
  6639. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  6640. }
  6641. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  6642. cb(sa_out, "sa_out", il);
  6643. cur = llm_build_norm(ctx0, sa_out, hparams,
  6644. model.layers[il].ffn_norm, NULL,
  6645. LLM_NORM_RMS, cb, il);
  6646. cb(cur, "ffn_norm", il);
  6647. // feed-forward network
  6648. {
  6649. cur = llm_build_ffn(ctx0, cur,
  6650. model.layers[il].ffn_up, NULL,
  6651. model.layers[il].ffn_gate, NULL,
  6652. model.layers[il].ffn_down, NULL,
  6653. NULL,
  6654. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  6655. cb(cur, "ffn_out", il);
  6656. }
  6657. cur = ggml_add(ctx0, cur, sa_out);
  6658. cb(cur, "l_out", il);
  6659. // input for next layer
  6660. inpL = cur;
  6661. }
  6662. cur = inpL;
  6663. cur = llm_build_norm(ctx0, cur, hparams,
  6664. model.output_norm, NULL,
  6665. LLM_NORM_RMS, cb, -1);
  6666. cb(cur, "result_norm", -1);
  6667. // lm_head
  6668. cur = ggml_mul_mat(ctx0, model.output, cur);
  6669. cb(cur, "result_output", -1);
  6670. ggml_build_forward_expand(gf, cur);
  6671. return gf;
  6672. }
  6673. struct ggml_cgraph * build_starcoder2() {
  6674. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6675. const int64_t n_embd_head = hparams.n_embd_head_v;
  6676. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6677. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6678. struct ggml_tensor * cur;
  6679. struct ggml_tensor * inpL;
  6680. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6681. // inp_pos - contains the positions
  6682. struct ggml_tensor * inp_pos = build_inp_pos();
  6683. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6684. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6685. for (int il = 0; il < n_layer; ++il) {
  6686. struct ggml_tensor * inpSA = inpL;
  6687. // norm
  6688. cur = llm_build_norm(ctx0, inpL, hparams,
  6689. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  6690. LLM_NORM, cb, il);
  6691. cb(cur, "attn_norm", il);
  6692. // self-attention
  6693. {
  6694. // compute Q and K and RoPE them
  6695. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6696. cb(Qcur, "Qcur", il);
  6697. if (model.layers[il].bq) {
  6698. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6699. cb(Qcur, "Qcur", il);
  6700. }
  6701. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6702. cb(Kcur, "Kcur", il);
  6703. if (model.layers[il].bk) {
  6704. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6705. cb(Kcur, "Kcur", il);
  6706. }
  6707. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6708. cb(Vcur, "Vcur", il);
  6709. if (model.layers[il].bv) {
  6710. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6711. cb(Vcur, "Vcur", il);
  6712. }
  6713. Qcur = ggml_rope_custom(
  6714. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6715. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6716. ext_factor, attn_factor, beta_fast, beta_slow
  6717. );
  6718. cb(Qcur, "Qcur", il);
  6719. Kcur = ggml_rope_custom(
  6720. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6721. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6722. ext_factor, attn_factor, beta_fast, beta_slow
  6723. );
  6724. cb(Kcur, "Kcur", il);
  6725. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6726. model.layers[il].wo, model.layers[il].bo,
  6727. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6728. cb(cur, "kqv_out", il);
  6729. }
  6730. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6731. cb(ffn_inp, "ffn_inp", il);
  6732. // feed-forward network
  6733. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6734. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  6735. LLM_NORM, cb, il);
  6736. cb(cur, "ffn_norm", il);
  6737. cur = llm_build_ffn(ctx0, cur,
  6738. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6739. NULL, NULL,
  6740. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6741. NULL,
  6742. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6743. cb(cur, "ffn_out", il);
  6744. cur = ggml_add(ctx0, cur, ffn_inp);
  6745. cb(cur, "l_out", il);
  6746. // input for next layer
  6747. inpL = cur;
  6748. }
  6749. cur = inpL;
  6750. cur = llm_build_norm(ctx0, cur, hparams,
  6751. model.output_norm, model.output_norm_b,
  6752. LLM_NORM, cb, -1);
  6753. cb(cur, "result_norm", -1);
  6754. // lm_head
  6755. cur = ggml_mul_mat(ctx0, model.output, cur);
  6756. cb(cur, "result_output", -1);
  6757. ggml_build_forward_expand(gf, cur);
  6758. return gf;
  6759. }
  6760. struct ggml_cgraph * build_mamba() {
  6761. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6762. const int64_t d_model = n_embd;
  6763. const int64_t d_conv = hparams.ssm_d_conv;
  6764. const int64_t d_inner = hparams.ssm_d_inner;
  6765. GGML_ASSERT(2 * d_model == d_inner);
  6766. const int64_t d_state = hparams.ssm_d_state;
  6767. const int64_t dt_rank = hparams.ssm_dt_rank;
  6768. struct ggml_tensor * cur;
  6769. struct ggml_tensor * inpL;
  6770. // {n_embd, n_tokens}
  6771. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6772. struct ggml_tensor * state_mask = build_inp_s_mask();
  6773. struct ggml_tensor * state_seq = build_inp_s_seq();
  6774. for (int il = 0; il < n_layer; ++il) {
  6775. // (ab)using the KV cache to store the states
  6776. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  6777. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  6778. // clear states of sequences which are starting at the beginning of this batch
  6779. {
  6780. conv_states = ggml_mul(ctx0,
  6781. ggml_view_2d(ctx0, conv_states, conv_states->ne[0], n_kv, conv_states->nb[1], kv_head*conv_states->nb[1]),
  6782. state_mask);
  6783. ssm_states = ggml_mul(ctx0,
  6784. ggml_view_2d(ctx0, ssm_states, ssm_states->ne[0], n_kv, ssm_states->nb[1], kv_head*ssm_states->nb[1]),
  6785. state_mask);
  6786. }
  6787. conv_states = ggml_reshape_3d(ctx0, conv_states, d_conv - 1, d_inner, n_kv);
  6788. ssm_states = ggml_reshape_3d(ctx0, ssm_states, d_state, d_inner, n_kv);
  6789. // norm
  6790. cur = llm_build_norm(ctx0, inpL, hparams,
  6791. model.layers[il].attn_norm, NULL,
  6792. LLM_NORM_RMS, cb, il);
  6793. cb(cur, "attn_norm", il);
  6794. // {n_embd, 2*d_inner} * {n_embd, n_tokens} => {2*d_inner, n_tokens}
  6795. struct ggml_tensor * xz = ggml_mul_mat(ctx0, model.layers[il].ssm_in, cur);
  6796. // split the above in two
  6797. // => {d_inner, n_tokens}
  6798. struct ggml_tensor * x = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], 0);
  6799. struct ggml_tensor * z = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], ggml_element_size(xz)*d_inner);
  6800. // conv
  6801. {
  6802. // Custom operator which is needed only to ease simultaneous sequence processing.
  6803. // For a single sequence, the equivalent is to concatenate the columns of conv_states and x,
  6804. // then make a self-overlapping view of that over d_conv columns at each stride in the 3rd dimension,
  6805. // then element-wise multiply that with the conv1d weigth,
  6806. // then sum the elements of each row,
  6807. // (the last two steps are a dot product over rows (also doable with mul_mat))
  6808. // then permute away the ne[0] dimension,
  6809. // and then you're left with the resulting x tensor.
  6810. // The new conv_states is the last (d_conv - 1) columns
  6811. // of the last 3rd dimensional "layer" of the self-overlapping view.
  6812. // For simultaneous sequences, it's more complicated.
  6813. struct ggml_tensor * x_conv = ggml_ssm_conv(ctx0, conv_states, x, model.layers[il].ssm_conv1d, state_seq);
  6814. // store last (d_conv - 1) columns of the conv_state part of x_conv back into the KV cache
  6815. ggml_build_forward_expand(gf,
  6816. ggml_cpy(ctx0,
  6817. ggml_view_2d(ctx0, x_conv, d_conv - 1, d_inner*n_kv, d_conv*ggml_element_size(x_conv), (1+d_inner*n_tokens)*ggml_element_size(x_conv)),
  6818. ggml_view_1d(ctx0, kv_self.k_l[il], (d_conv - 1)*(d_inner)*(n_kv), kv_head*(d_conv - 1)*(d_inner)*ggml_element_size(x_conv))));
  6819. // extract x from x_conv
  6820. x = ggml_view_2d(ctx0, x_conv, d_inner, n_tokens, d_inner*ggml_element_size(x_conv), 0);
  6821. // bias
  6822. x = ggml_add(ctx0, x, model.layers[il].ssm_conv1d_b);
  6823. x = ggml_silu(ctx0, x);
  6824. }
  6825. // ssm
  6826. {
  6827. // {d_inner, dt_rank + 2*d_state} * {d_inner, n_tokens} => {dt_rank + 2*d_state, n_tokens}
  6828. struct ggml_tensor * x_db = ggml_mul_mat(ctx0, model.layers[il].ssm_x, x);
  6829. // split
  6830. struct ggml_tensor * dt = ggml_view_2d(ctx0, x_db, dt_rank, n_tokens, x_db->nb[1], 0);
  6831. struct ggml_tensor * B = ggml_view_2d(ctx0, x_db, d_state, n_tokens, x_db->nb[1], ggml_element_size(x_db)*dt_rank);
  6832. struct ggml_tensor * C = ggml_view_2d(ctx0, x_db, d_state, n_tokens, x_db->nb[1], ggml_element_size(x_db)*(dt_rank+d_state));
  6833. // {dt_rank, d_inner} * {dt_rank, n_tokens} => {d_inner, n_tokens}
  6834. dt = ggml_mul_mat(ctx0, model.layers[il].ssm_dt, dt);
  6835. dt = ggml_add(ctx0, dt, model.layers[il].ssm_dt_b);
  6836. // Custom operator to optimize the parallel associative scan
  6837. // as described in the Annex D of the Mamba paper.
  6838. // => {d_inner, n_tokens} and {d_state, d_inner, n_kv} combined,
  6839. // because only a single tensor can be returned.
  6840. struct ggml_tensor * y_ssm_states = ggml_ssm_scan(ctx0, ssm_states, x, dt, model.layers[il].ssm_a, B, C, state_seq);
  6841. // store last states (the second part of y_ssm_states)
  6842. ggml_build_forward_expand(gf,
  6843. ggml_cpy(ctx0,
  6844. ggml_view_1d(ctx0, y_ssm_states, d_state*d_inner*n_kv, d_inner*n_tokens*ggml_element_size(y_ssm_states)),
  6845. ggml_view_1d(ctx0, kv_self.v_l[il], d_state*d_inner*n_kv, kv_head*d_state*d_inner*ggml_element_size(ssm_states))));
  6846. struct ggml_tensor * y = ggml_view_2d(ctx0, y_ssm_states, d_inner, n_tokens, d_inner*ggml_element_size(y_ssm_states), 0);
  6847. // {d_inner, n_tokens} * {d_inner} => {d_inner, n_tokens}
  6848. y = ggml_add(ctx0, y, ggml_mul(ctx0, x, model.layers[il].ssm_d));
  6849. y = ggml_mul(ctx0, y, ggml_silu(ctx0, z));
  6850. // {d_inner, n_embd} * {d_inner, n_tokens} => {n_embd, n_tokens}
  6851. cur = ggml_mul_mat(ctx0, model.layers[il].ssm_out, y);
  6852. }
  6853. // residual
  6854. cur = ggml_add(ctx0, cur, inpL);
  6855. cb(cur, "l_out", il);
  6856. // input for next layer
  6857. inpL = cur;
  6858. }
  6859. // final rmsnorm
  6860. cur = llm_build_norm(ctx0, inpL, hparams,
  6861. model.output_norm, NULL,
  6862. LLM_NORM_RMS, cb, -1);
  6863. cb(cur, "result_norm", -1);
  6864. // lm_head
  6865. cur = ggml_mul_mat(ctx0, model.output, cur);
  6866. cb(cur, "result_output", -1);
  6867. ggml_build_forward_expand(gf, cur);
  6868. return gf;
  6869. }
  6870. };
  6871. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  6872. llama_batch dummy;
  6873. dummy.n_tokens = 0;
  6874. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  6875. struct llm_build_context llm(lctx, dummy, cb, false);
  6876. llm.init();
  6877. struct ggml_cgraph * result = llm.build_defrag(ids);
  6878. llm.free();
  6879. return result;
  6880. }
  6881. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  6882. llama_batch dummy;
  6883. dummy.n_tokens = 0;
  6884. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  6885. struct llm_build_context llm(lctx, dummy, cb, false);
  6886. llm.init();
  6887. struct ggml_cgraph * result = llm.build_k_shift();
  6888. llm.free();
  6889. return result;
  6890. }
  6891. static struct ggml_cgraph * llama_build_graph_s_copy(llama_context & lctx) {
  6892. llama_batch dummy;
  6893. dummy.n_tokens = 0;
  6894. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  6895. struct llm_build_context llm(lctx, dummy, cb, false);
  6896. llm.init();
  6897. struct ggml_cgraph * result = llm.build_s_copy();
  6898. llm.free();
  6899. return result;
  6900. }
  6901. static struct ggml_cgraph * llama_build_graph(
  6902. llama_context & lctx,
  6903. const llama_batch & batch,
  6904. bool worst_case) {
  6905. const auto & model = lctx.model;
  6906. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  6907. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  6908. if (il >= 0) {
  6909. ggml_format_name(cur, "%s-%d", name, il);
  6910. } else {
  6911. ggml_set_name(cur, name);
  6912. }
  6913. if (!lctx.cparams.offload_kqv) {
  6914. if (strcmp(name, "kqv_merged_cont") == 0) {
  6915. // all nodes between the KV store and the attention output are run on the CPU
  6916. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, lctx.backend_cpu);
  6917. }
  6918. }
  6919. // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
  6920. // to fix this, we assign the norm layer manually to the backend of its layer
  6921. if (il != -1 && strcmp(name, "norm") == 0) {
  6922. for (auto * backend : lctx.backends) {
  6923. if (ggml_backend_buft_supports_backend(lctx.model.buft_layer[il].buft, backend)) {
  6924. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, backend);
  6925. break;
  6926. }
  6927. }
  6928. }
  6929. };
  6930. struct ggml_cgraph * result = NULL;
  6931. struct llm_build_context llm(lctx, batch, cb, worst_case);
  6932. llm.init();
  6933. switch (model.arch) {
  6934. case LLM_ARCH_LLAMA:
  6935. {
  6936. result = llm.build_llama();
  6937. } break;
  6938. case LLM_ARCH_BAICHUAN:
  6939. {
  6940. result = llm.build_baichuan();
  6941. } break;
  6942. case LLM_ARCH_FALCON:
  6943. {
  6944. result = llm.build_falcon();
  6945. } break;
  6946. case LLM_ARCH_STARCODER:
  6947. {
  6948. result = llm.build_starcoder();
  6949. } break;
  6950. case LLM_ARCH_PERSIMMON:
  6951. {
  6952. result = llm.build_persimmon();
  6953. } break;
  6954. case LLM_ARCH_REFACT:
  6955. {
  6956. result = llm.build_refact();
  6957. } break;
  6958. case LLM_ARCH_BERT:
  6959. case LLM_ARCH_NOMIC_BERT:
  6960. {
  6961. result = llm.build_bert();
  6962. } break;
  6963. case LLM_ARCH_BLOOM:
  6964. {
  6965. result = llm.build_bloom();
  6966. } break;
  6967. case LLM_ARCH_MPT:
  6968. {
  6969. result = llm.build_mpt();
  6970. } break;
  6971. case LLM_ARCH_STABLELM:
  6972. {
  6973. result = llm.build_stablelm();
  6974. } break;
  6975. case LLM_ARCH_QWEN:
  6976. {
  6977. result = llm.build_qwen();
  6978. } break;
  6979. case LLM_ARCH_QWEN2:
  6980. {
  6981. result = llm.build_qwen2();
  6982. } break;
  6983. case LLM_ARCH_PHI2:
  6984. {
  6985. result = llm.build_phi2();
  6986. } break;
  6987. case LLM_ARCH_PLAMO:
  6988. {
  6989. result = llm.build_plamo();
  6990. } break;
  6991. case LLM_ARCH_GPT2:
  6992. {
  6993. result = llm.build_gpt2();
  6994. } break;
  6995. case LLM_ARCH_CODESHELL:
  6996. {
  6997. result = llm.build_codeshell();
  6998. } break;
  6999. case LLM_ARCH_ORION:
  7000. {
  7001. result = llm.build_orion();
  7002. } break;
  7003. case LLM_ARCH_INTERNLM2:
  7004. {
  7005. result = llm.build_internlm2();
  7006. } break;
  7007. case LLM_ARCH_MINICPM:
  7008. {
  7009. result = llm.build_minicpm();
  7010. } break;
  7011. case LLM_ARCH_GEMMA:
  7012. {
  7013. result = llm.build_gemma();
  7014. } break;
  7015. case LLM_ARCH_STARCODER2:
  7016. {
  7017. result = llm.build_starcoder2();
  7018. } break;
  7019. case LLM_ARCH_MAMBA:
  7020. {
  7021. result = llm.build_mamba();
  7022. } break;
  7023. default:
  7024. GGML_ASSERT(false);
  7025. }
  7026. llm.free();
  7027. return result;
  7028. }
  7029. static void llama_set_k_shift(llama_context & lctx) {
  7030. const int64_t kv_size = lctx.kv_self.size;
  7031. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  7032. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  7033. for (int i = 0; i < kv_size; ++i) {
  7034. data[i] = lctx.kv_self.cells[i].delta;
  7035. }
  7036. }
  7037. static void llama_set_s_copy(llama_context & lctx) {
  7038. const int64_t kv_size = lctx.kv_self.size;
  7039. assert(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  7040. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  7041. for (int i = 0; i < kv_size; ++i) {
  7042. data[i] = lctx.kv_self.cells[i].src;
  7043. }
  7044. }
  7045. static void llama_set_inputs(llama_context & lctx, const llama_batch & batch) {
  7046. //
  7047. // set input data
  7048. //
  7049. const auto & hparams = lctx.model.hparams;
  7050. const auto & cparams = lctx.cparams;
  7051. const auto & kv_self = lctx.kv_self;
  7052. if (batch.token) {
  7053. const int64_t n_tokens = batch.n_tokens;
  7054. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  7055. }
  7056. if (batch.embd) {
  7057. const int64_t n_embd = hparams.n_embd;
  7058. const int64_t n_tokens = batch.n_tokens;
  7059. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  7060. }
  7061. if (batch.pos && lctx.inp_pos) {
  7062. const int64_t n_tokens = batch.n_tokens;
  7063. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  7064. }
  7065. GGML_ASSERT(
  7066. (hparams.causal_attn || !cparams.causal_attn) &&
  7067. "non-causal attention with generative models is not supported"
  7068. );
  7069. if (lctx.inp_KQ_mask) {
  7070. // NOTE: hparams.causal_attn indicates the model is capable of generation and uses the kv cache.
  7071. if (cparams.causal_attn) {
  7072. const int64_t n_kv = kv_self.n;
  7073. const int64_t n_tokens = batch.n_tokens;
  7074. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  7075. float * data = (float *) lctx.inp_KQ_mask->data;
  7076. // For causal attention, use only the previous KV cells
  7077. // of the correct sequence for each token of the batch.
  7078. // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
  7079. for (int h = 0; h < 1; ++h) {
  7080. for (int j = 0; j < n_tokens; ++j) {
  7081. const llama_pos pos = batch.pos[j];
  7082. const llama_seq_id seq_id = batch.seq_id[j][0];
  7083. for (int i = 0; i < n_kv; ++i) {
  7084. float f;
  7085. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  7086. f = -INFINITY;
  7087. } else {
  7088. f = 0.0f;
  7089. }
  7090. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  7091. }
  7092. }
  7093. }
  7094. } else {
  7095. // when using kv cache, the mask needs to match the kv cache size
  7096. const int64_t n_tokens = batch.n_tokens;
  7097. const int64_t n_stride = hparams.causal_attn ? kv_self.n : n_tokens;
  7098. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  7099. float * data = (float *) lctx.inp_KQ_mask->data;
  7100. for (int h = 0; h < 1; ++h) {
  7101. for (int j = 0; j < n_tokens; ++j) {
  7102. const llama_seq_id seq_id = batch.seq_id[j][0];
  7103. for (int i = 0; i < n_tokens; ++i) {
  7104. float f = -INFINITY;
  7105. for (int s = 0; s < batch.n_seq_id[i]; ++s) {
  7106. if (batch.seq_id[i][s] == seq_id) {
  7107. f = 0.0f;
  7108. break;
  7109. }
  7110. }
  7111. data[h*(n_tokens*n_tokens) + j*n_stride + i] = f;
  7112. }
  7113. for (int i = n_tokens; i < n_stride; ++i) {
  7114. data[h*(n_tokens*n_tokens) + j*n_stride + i] = -INFINITY;
  7115. }
  7116. }
  7117. }
  7118. }
  7119. }
  7120. if (hparams.need_kq_pos) {
  7121. const int64_t n_kv = kv_self.n;
  7122. GGML_ASSERT(lctx.inp_KQ_pos);
  7123. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_pos->buffer));
  7124. float * data = (float *) lctx.inp_KQ_pos->data;
  7125. for (int i = 0; i < n_kv; ++i) {
  7126. data[i] = float(lctx.kv_self.cells[i].pos);
  7127. }
  7128. }
  7129. if (cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  7130. const int64_t n_tokens = batch.n_tokens;
  7131. GGML_ASSERT(lctx.inp_mean);
  7132. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  7133. float * data = (float *) lctx.inp_mean->data;
  7134. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  7135. std::vector<uint64_t> sum(n_tokens, 0);
  7136. for (int i = 0; i < n_tokens; ++i) {
  7137. const llama_seq_id seq_id = batch.seq_id[i][0];
  7138. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
  7139. sum[seq_id] += 1;
  7140. }
  7141. std::vector<float> div(n_tokens, 0.0f);
  7142. for (int i = 0; i < n_tokens; ++i) {
  7143. const uint64_t s = sum[i];
  7144. if (s > 0) {
  7145. div[i] = 1.0f/float(s);
  7146. }
  7147. }
  7148. for (int i = 0; i < n_tokens; ++i) {
  7149. const llama_seq_id seq_id = batch.seq_id[i][0];
  7150. data[seq_id*n_tokens + i] = div[seq_id];
  7151. }
  7152. }
  7153. if (cparams.pooling_type == LLAMA_POOLING_TYPE_CLS) {
  7154. const int64_t n_tokens = batch.n_tokens;
  7155. GGML_ASSERT(lctx.inp_cls);
  7156. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  7157. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  7158. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  7159. for (int i = 0; i < n_tokens; ++i) {
  7160. const llama_seq_id seq_id = batch.seq_id[i][0];
  7161. const llama_pos pos = batch.pos[i];
  7162. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS");
  7163. if (pos == 0) {
  7164. data[seq_id] = i;
  7165. }
  7166. }
  7167. }
  7168. if (kv_self.recurrent) {
  7169. const int64_t n_kv = kv_self.n;
  7170. if (lctx.inp_s_mask) {
  7171. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_mask->buffer));
  7172. float * data = (float *) lctx.inp_s_mask->data;
  7173. // states which are not affected by the current batch are left untouched
  7174. for (int i = 0; i < n_kv; ++i) {
  7175. llama_seq_id seq_id = i + lctx.kv_self.head;
  7176. llama_kv_cell & kv_cell = lctx.kv_self.cells[seq_id];
  7177. bool has_self_seq = kv_cell.has_seq_id(seq_id);
  7178. data[i] = (float) has_self_seq;
  7179. // ensure current sequences will be kept
  7180. if (!has_self_seq && kv_cell.pos >= 0) {
  7181. kv_cell.seq_id.insert(seq_id);
  7182. }
  7183. }
  7184. }
  7185. // For Mamba (and other recurrent architectures),
  7186. // update the correct state(s)/sequence(s) for each token of the batch.
  7187. // Like with the KQ_mask, if a token in the batch has multiple sequences,
  7188. // they are assumed to be equivalent (not here, but in ggml_ssm_scan and ggml_ssm_conv).
  7189. if (lctx.inp_s_seq) {
  7190. const int64_t n_tokens = batch.n_tokens;
  7191. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_seq->buffer));
  7192. int32_t * data = (int32_t *) lctx.inp_s_seq->data;
  7193. for (int j = 0; j < n_tokens; ++j) {
  7194. const int32_t n_seq = batch.n_seq_id[j];
  7195. GGML_ASSERT(0 < n_seq); // a token should be part of at least 1 sequence
  7196. for (int i = 0; i < n_kv; ++i) {
  7197. if (i < n_seq) {
  7198. // for this type of model, the head is the minimum seq_id of the batch
  7199. data[j*n_kv + i] = batch.seq_id[j][i] - kv_self.head;
  7200. } else {
  7201. data[j*n_kv + i] = -1;
  7202. }
  7203. }
  7204. }
  7205. }
  7206. }
  7207. }
  7208. static void llama_graph_compute(
  7209. llama_context & lctx,
  7210. ggml_cgraph * gf,
  7211. int n_threads) {
  7212. #ifdef GGML_USE_MPI
  7213. const int64_t n_layer = lctx.model.hparams.n_layer;
  7214. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  7215. #endif
  7216. #ifdef GGML_USE_METAL
  7217. if (ggml_backend_is_metal(lctx.backend_metal)) {
  7218. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  7219. }
  7220. #endif
  7221. if (lctx.backend_cpu != nullptr) {
  7222. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  7223. ggml_backend_cpu_set_abort_callback(lctx.backend_cpu, lctx.abort_callback, lctx.abort_callback_data);
  7224. }
  7225. ggml_backend_sched_graph_compute_async(lctx.sched, gf);
  7226. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  7227. #ifdef GGML_USE_MPI
  7228. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  7229. #endif
  7230. }
  7231. // decode a batch of tokens by evaluating the transformer
  7232. //
  7233. // - lctx: llama context
  7234. // - batch: batch to evaluate
  7235. //
  7236. // return 0 on success
  7237. // return positive int on warning
  7238. // return negative int on error
  7239. //
  7240. static int llama_decode_internal(
  7241. llama_context & lctx,
  7242. llama_batch batch_all) { // TODO: rename back to batch
  7243. const uint32_t n_tokens_all = batch_all.n_tokens;
  7244. if (n_tokens_all == 0) {
  7245. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  7246. return -1;
  7247. }
  7248. const auto & model = lctx.model;
  7249. const auto & hparams = model.hparams;
  7250. const auto & cparams = lctx.cparams;
  7251. GGML_ASSERT((!batch_all.token && batch_all.embd) || (batch_all.token && !batch_all.embd)); // NOLINT
  7252. GGML_ASSERT(n_tokens_all <= cparams.n_batch);
  7253. GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
  7254. if (lctx.t_compute_start_us == 0) {
  7255. lctx.t_compute_start_us = ggml_time_us();
  7256. }
  7257. lctx.n_queued_tokens += n_tokens_all;
  7258. #ifdef GGML_USE_MPI
  7259. // TODO: needs fix after #3228
  7260. GGML_ASSERT(false && "not implemented");
  7261. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  7262. #endif
  7263. auto & kv_self = lctx.kv_self;
  7264. const int64_t n_embd = hparams.n_embd;
  7265. const int64_t n_vocab = hparams.n_vocab;
  7266. auto * logits_out = lctx.logits;
  7267. #ifndef NDEBUG
  7268. auto & logits_valid = lctx.logits_valid;
  7269. logits_valid.clear();
  7270. logits_valid.resize(n_tokens_all);
  7271. memset(logits_out, 0, lctx.logits_size*sizeof(float));
  7272. #endif
  7273. const auto n_ubatch = cparams.n_ubatch;
  7274. std::vector<llama_pos> pos;
  7275. std::vector<int32_t> n_seq_id;
  7276. std::vector<llama_seq_id *> seq_id_arr;
  7277. std::vector<std::vector<llama_seq_id>> seq_id;
  7278. for (uint32_t cur_token = 0; cur_token < n_tokens_all; cur_token += n_ubatch) {
  7279. const uint32_t n_tokens = std::min(n_ubatch, n_tokens_all - cur_token);
  7280. llama_batch u_batch = {
  7281. /* .n_tokens = */ (int32_t) n_tokens,
  7282. /* .token = */ batch_all.token ? batch_all.token + cur_token : nullptr,
  7283. /* .embd = */ batch_all.embd ? batch_all.embd + cur_token*n_embd : nullptr,
  7284. /* .pos = */ batch_all.pos ? batch_all.pos + cur_token : nullptr,
  7285. /* .n_seq_id = */ batch_all.n_seq_id ? batch_all.n_seq_id + cur_token : nullptr,
  7286. /* .seq_id = */ batch_all.seq_id ? batch_all.seq_id + cur_token : nullptr,
  7287. /* .logits = */ batch_all.logits ? batch_all.logits + cur_token : nullptr,
  7288. /* .all_pos_0 = */ batch_all.all_pos_0 + (llama_pos) cur_token*batch_all.all_pos_1,
  7289. /* .all_pos_1 = */ batch_all.all_pos_1,
  7290. /* .all_seq_id = */ batch_all.all_seq_id,
  7291. };
  7292. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  7293. GGML_ASSERT(n_threads > 0);
  7294. // helpers for smoother batch API transition
  7295. // after deprecating the llama_eval calls, these will be removed
  7296. if (u_batch.pos == nullptr) {
  7297. pos.resize(n_tokens);
  7298. for (uint32_t i = 0; i < n_tokens; i++) {
  7299. pos[i] = u_batch.all_pos_0 + i*u_batch.all_pos_1;
  7300. }
  7301. u_batch.pos = pos.data();
  7302. }
  7303. if (u_batch.seq_id == nullptr) {
  7304. n_seq_id.resize(n_tokens);
  7305. seq_id.resize(n_tokens);
  7306. seq_id_arr.resize(n_tokens);
  7307. for (uint32_t i = 0; i < n_tokens; i++) {
  7308. n_seq_id[i] = 1;
  7309. seq_id[i].resize(1);
  7310. seq_id[i][0] = u_batch.all_seq_id;
  7311. seq_id_arr[i] = seq_id[i].data();
  7312. }
  7313. u_batch.n_seq_id = n_seq_id.data();
  7314. u_batch.seq_id = seq_id_arr.data();
  7315. }
  7316. // non-causal masks do not use the KV cache
  7317. if (hparams.causal_attn) {
  7318. llama_kv_cache_update(&lctx);
  7319. // if we have enough unused cells before the current head ->
  7320. // better to start searching from the beginning of the cache, hoping to fill it
  7321. if (kv_self.head > kv_self.used + 2*n_tokens) {
  7322. kv_self.head = 0;
  7323. }
  7324. if (!llama_kv_cache_find_slot(kv_self, u_batch)) {
  7325. return 1;
  7326. }
  7327. if (!kv_self.recurrent) {
  7328. // a heuristic, to avoid attending the full cache if it is not yet utilized
  7329. // after enough generations, the benefit from this heuristic disappears
  7330. // if we start defragmenting the cache, the benefit from this will be more important
  7331. kv_self.n = std::min(kv_self.size, std::max(32u, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  7332. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  7333. }
  7334. }
  7335. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  7336. ggml_backend_sched_reset(lctx.sched);
  7337. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  7338. ggml_cgraph * gf = llama_build_graph(lctx, u_batch, false);
  7339. // the output is always the last tensor in the graph
  7340. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  7341. struct ggml_tensor * embd = gf->nodes[gf->n_nodes - 2];
  7342. if (!hparams.causal_attn) {
  7343. res = nullptr; // do not extract logits for embedding models such as BERT
  7344. // token or sequence embeddings
  7345. embd = gf->nodes[gf->n_nodes - 1];
  7346. GGML_ASSERT(strcmp(embd->name, "result_embd") == 0 || strcmp(embd->name, "result_embd_pooled") == 0);
  7347. } else {
  7348. if (strcmp(res->name, "result_output") == 0) {
  7349. // the token embeddings could be the second to last tensor, or the third to last tensor
  7350. if (strcmp(embd->name, "result_norm") != 0) {
  7351. embd = gf->nodes[gf->n_nodes - 3];
  7352. GGML_ASSERT(strcmp(embd->name, "result_norm") == 0);
  7353. }
  7354. } else {
  7355. GGML_ASSERT(false && "missing result_output tensor");
  7356. }
  7357. }
  7358. // 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);
  7359. // for big prompts, if BLAS is enabled, it is better to use only one thread
  7360. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  7361. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  7362. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  7363. // with the BLAS calls. need a better solution
  7364. // MoE Special Case: This logic applies when hparams.n_expert == 0, i.e. the model is NOT an MoE model. When an MoE is
  7365. // being processed then Accelerate/BLAS will not be involved, so capping would limit performance.
  7366. if (n_tokens >= 32 && hparams.n_expert == 0 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  7367. n_threads = std::min(4, n_threads);
  7368. }
  7369. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  7370. llama_set_inputs(lctx, u_batch);
  7371. llama_graph_compute(lctx, gf, n_threads);
  7372. // update the kv ring buffer
  7373. {
  7374. kv_self.head += n_tokens;
  7375. // Ensure kv cache head points to a valid index.
  7376. if (kv_self.head >= kv_self.size) {
  7377. kv_self.head = 0;
  7378. }
  7379. }
  7380. #ifdef GGML_PERF
  7381. // print timing information per ggml operation (for debugging purposes)
  7382. // requires GGML_PERF to be defined
  7383. ggml_graph_print(gf);
  7384. #endif
  7385. // plot the computation graph in dot format (for debugging purposes)
  7386. //if (n_past%100 == 0) {
  7387. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  7388. //}
  7389. // extract logits
  7390. // TODO: do not compute and extract logits if only embeddings are needed
  7391. // update the graphs to skip "result_output" if logits are not needed
  7392. if (res) {
  7393. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(lctx.sched, res);
  7394. GGML_ASSERT(backend_res != nullptr);
  7395. if (u_batch.logits) {
  7396. int32_t i_first = -1;
  7397. for (uint32_t i = 0; i < n_tokens; i++) {
  7398. if (u_batch.logits[i] && i_first == -1) {
  7399. i_first = (int32_t) i;
  7400. }
  7401. if (u_batch.logits[i] == 0 || i == n_tokens - 1) {
  7402. if (i_first != -1) {
  7403. int i_last = u_batch.logits[i] == 0 ? i : i + 1;
  7404. // extract logits for the range [i_first, i_last)
  7405. // group the requests to minimize the number of calls to the backend
  7406. ggml_backend_tensor_get_async(backend_res, res,
  7407. logits_out + n_vocab*(cur_token + i_first),
  7408. i_first*n_vocab*sizeof(float),
  7409. (i_last - i_first)*n_vocab*sizeof(float));
  7410. i_first = -1;
  7411. }
  7412. }
  7413. #ifndef NDEBUG
  7414. logits_valid[cur_token + i] = u_batch.logits[i] != 0;;
  7415. #endif
  7416. }
  7417. } else if (lctx.logits_all) {
  7418. ggml_backend_tensor_get_async(backend_res, res, logits_out + n_vocab*cur_token, 0, n_vocab*n_tokens*sizeof(float));
  7419. #ifndef NDEBUG
  7420. std::fill(logits_valid.begin() + cur_token, logits_valid.begin() + cur_token + n_tokens, true);
  7421. #endif
  7422. } else {
  7423. if (cur_token + n_tokens >= n_tokens_all) {
  7424. ggml_backend_tensor_get_async(backend_res, res, logits_out, n_vocab*(n_tokens - 1)*sizeof(float), n_vocab*sizeof(float));
  7425. #ifndef NDEBUG
  7426. logits_valid[0] = true;
  7427. #endif
  7428. }
  7429. }
  7430. }
  7431. // extract embeddings
  7432. if (cparams.embeddings && embd) {
  7433. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched, embd);
  7434. GGML_ASSERT(backend_embd != nullptr);
  7435. switch (cparams.pooling_type) {
  7436. case LLAMA_POOLING_TYPE_NONE:
  7437. {
  7438. // extract token embeddings
  7439. auto & embd_out = lctx.embd;
  7440. if (u_batch.logits) {
  7441. //embd_out.resize(n_embd * n_tokens);
  7442. for (uint32_t i = 0; i < n_tokens; i++) {
  7443. if (u_batch.logits[i] == 0) {
  7444. continue;
  7445. }
  7446. ggml_backend_tensor_get_async(backend_embd, embd, embd_out + n_embd*(i + cur_token), (n_embd*i)*sizeof(float), n_embd*sizeof(float));
  7447. }
  7448. }
  7449. } break;
  7450. case LLAMA_POOLING_TYPE_CLS:
  7451. case LLAMA_POOLING_TYPE_MEAN:
  7452. {
  7453. GGML_ASSERT(strcmp(embd->name, "result_embd_pooled") == 0);
  7454. // extract sequence embeddings
  7455. auto & embd_seq_out = lctx.embd_seq;
  7456. embd_seq_out.clear();
  7457. for (uint32_t i = 0; i < n_tokens; i++) {
  7458. const llama_seq_id seq_id = u_batch.seq_id[i][0];
  7459. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  7460. continue;
  7461. }
  7462. embd_seq_out[seq_id].resize(n_embd);
  7463. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  7464. }
  7465. } break;
  7466. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  7467. {
  7468. GGML_ASSERT(false && "unknown pooling type");
  7469. } break;
  7470. }
  7471. }
  7472. }
  7473. // wait for the computation to finish (automatically done when obtaining the model output)
  7474. //llama_synchronize(&lctx);
  7475. // decide if we need to defrag the kv cache
  7476. if (cparams.causal_attn && cparams.defrag_thold >= 0.0f) {
  7477. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used)/float(kv_self.n) : 0.0f;
  7478. // queue defragmentation for next llama_kv_cache_update
  7479. if (fragmentation > cparams.defrag_thold) {
  7480. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  7481. llama_kv_cache_defrag(kv_self);
  7482. }
  7483. }
  7484. return 0;
  7485. }
  7486. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  7487. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  7488. auto & kv_self = lctx.kv_self;
  7489. const auto & hparams = lctx.model.hparams;
  7490. const uint32_t n_layer = hparams.n_layer;
  7491. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  7492. const uint32_t n_used = kv_self.used;
  7493. assert(n_used <= n_kv);
  7494. //const int64_t t_start = ggml_time_us();
  7495. // number of cells moved
  7496. uint32_t n_moves = 0;
  7497. // each move requires 6*n_layer tensors (see build_defrag)
  7498. // - source view, destination view, copy operation
  7499. // - x2 for keys and values
  7500. const uint32_t max_moves = LLAMA_MAX_NODES/(6*n_layer);
  7501. // determine which KV cells to move where
  7502. //
  7503. // cell i moves to ids[i]
  7504. //
  7505. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  7506. //
  7507. std::vector<uint32_t> ids(n_kv, n_kv);
  7508. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  7509. const auto & cell0 = kv_self.cells[i0];
  7510. if (!cell0.is_empty()) {
  7511. ids[i0] = i0;
  7512. continue;
  7513. }
  7514. // found a hole - fill it with data from the end of the cache
  7515. uint32_t nh = 1;
  7516. // determine the size of the hole
  7517. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  7518. nh++;
  7519. }
  7520. uint32_t nf = 0;
  7521. uint32_t is = n_kv - 1;
  7522. // starting from the end, find nh non-empty cells
  7523. for (; is > i0; --is) {
  7524. const auto & cell1 = kv_self.cells[is];
  7525. if (cell1.is_empty() || ids[is] != n_kv) {
  7526. continue;
  7527. }
  7528. // non-empty cell which is not yet moved
  7529. nf++;
  7530. if (nf == nh) {
  7531. break;
  7532. }
  7533. }
  7534. // this can only happen if `n_used` is not accurate, which would be a bug
  7535. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  7536. nf = 0;
  7537. uint32_t i1 = is;
  7538. // are we moving a continuous block of memory?
  7539. bool cont = false;
  7540. // should we stop searching for the next move?
  7541. bool stop = false;
  7542. // go back and move the nf cells to the hole
  7543. for (; i1 < n_kv; ++i1) {
  7544. auto & cell1 = kv_self.cells[i1];
  7545. if (cell1.is_empty() || ids[i1] != n_kv) {
  7546. if (n_moves == max_moves) {
  7547. stop = true;
  7548. break;
  7549. }
  7550. cont = false;
  7551. continue;
  7552. }
  7553. // this cell goes to (i0 + nf)
  7554. ids[i1] = i0 + nf;
  7555. // move the cell meta data
  7556. kv_self.cells[i0 + nf] = cell1;
  7557. // clear the old cell and move the head there
  7558. cell1 = llama_kv_cell();
  7559. kv_self.head = n_used;
  7560. if (!cont) {
  7561. n_moves++;
  7562. cont = true;
  7563. }
  7564. nf++;
  7565. if (nf == nh) {
  7566. break;
  7567. }
  7568. }
  7569. if (stop || n_moves == max_moves) {
  7570. break;
  7571. }
  7572. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  7573. i0 += nh - 1;
  7574. }
  7575. if (n_moves == 0) {
  7576. return;
  7577. }
  7578. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  7579. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  7580. #if 0
  7581. // CPU defrag
  7582. //
  7583. // TODO: optimizations are possible:
  7584. // - multiple threads
  7585. // - avoid copying to the host memory when already there
  7586. //
  7587. // likely not worth the effort, as we have ggml_graph based defrag
  7588. //
  7589. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  7590. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  7591. const uint32_t kv_size = kv_self.size;
  7592. std::vector<uint8_t> buf_k;
  7593. std::vector<uint8_t> buf_v;
  7594. for (uint32_t il = 0; il < n_layer; ++il) {
  7595. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  7596. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  7597. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  7598. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  7599. buf_k.resize(k_size);
  7600. buf_v.resize(v_size);
  7601. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  7602. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  7603. // batch move [i, i+nm) to [id, id+nm)
  7604. // note: cells can move only to a lower index
  7605. for (uint32_t i = 0; i < n_kv; ++i) {
  7606. const uint32_t id = ids[i];
  7607. if (i == id || id == n_kv) {
  7608. continue;
  7609. }
  7610. uint32_t nm = 1;
  7611. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  7612. nm++;
  7613. }
  7614. // move keys
  7615. {
  7616. const int64_t os = i*k_size_row;
  7617. const int64_t od = id*k_size_row;
  7618. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  7619. }
  7620. // move values (note: they are transposed)
  7621. {
  7622. const int64_t os = i;
  7623. const int64_t od = id;
  7624. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  7625. memcpy(buf_v.data() + (od + j*kv_size)*v_size_el, buf_v.data() + (os + j*kv_size)*v_size_el, nm*v_size_el);
  7626. }
  7627. }
  7628. i += nm - 1;
  7629. }
  7630. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  7631. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  7632. }
  7633. #else
  7634. // ggml_graph defrag
  7635. ggml_backend_sched_reset(lctx.sched);
  7636. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  7637. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  7638. #endif
  7639. //const int64_t t_end = ggml_time_us();
  7640. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  7641. }
  7642. static void llama_kv_cache_update_internal(struct llama_context & lctx) {
  7643. bool need_reserve = false;
  7644. // apply K-shift if needed
  7645. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE && lctx.kv_self.has_shift) {
  7646. {
  7647. ggml_backend_sched_reset(lctx.sched);
  7648. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  7649. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  7650. llama_set_k_shift(lctx);
  7651. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  7652. need_reserve = true;
  7653. }
  7654. {
  7655. auto & kv_self = lctx.kv_self;
  7656. kv_self.has_shift = false;
  7657. for (uint32_t i = 0; i < kv_self.size; ++i) {
  7658. kv_self.cells[i].delta = 0;
  7659. }
  7660. }
  7661. }
  7662. if (lctx.kv_self.recurrent && lctx.kv_self.do_copy) {
  7663. {
  7664. ggml_backend_sched_reset(lctx.sched);
  7665. ggml_cgraph * gf = llama_build_graph_s_copy(lctx);
  7666. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  7667. llama_set_s_copy(lctx);
  7668. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  7669. need_reserve = true;
  7670. }
  7671. {
  7672. auto & kv_self = lctx.kv_self;
  7673. kv_self.do_copy = false;
  7674. for (uint32_t i = 0; i < kv_self.size; ++i) {
  7675. kv_self.cells[i].src = i;
  7676. }
  7677. }
  7678. }
  7679. // defragment the KV cache if needed
  7680. if (lctx.kv_self.do_defrag) {
  7681. llama_kv_cache_defrag_internal(lctx);
  7682. need_reserve = true;
  7683. lctx.kv_self.do_defrag = false;
  7684. }
  7685. // reserve a worst case graph again
  7686. if (need_reserve) {
  7687. // TODO: extract to a function
  7688. // build worst-case graph
  7689. int n_tokens = (int)std::min(lctx.cparams.n_ctx, lctx.cparams.n_ubatch);
  7690. int n_past = lctx.cparams.n_ctx - n_tokens;
  7691. llama_token token = llama_token_bos(&lctx.model); // not actually used by llama_build_graph, but required to choose between token and embedding inputs graph
  7692. ggml_cgraph * gf = llama_build_graph(lctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  7693. // initialize scheduler with the worst-case graph
  7694. ggml_backend_sched_reset(lctx.sched);
  7695. if (!ggml_backend_sched_reserve(lctx.sched, gf)) {
  7696. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  7697. }
  7698. }
  7699. }
  7700. //
  7701. // tokenizer
  7702. //
  7703. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  7704. return vocab.type;
  7705. }
  7706. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  7707. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  7708. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  7709. }
  7710. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  7711. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  7712. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  7713. }
  7714. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  7715. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  7716. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  7717. }
  7718. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  7719. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  7720. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  7721. }
  7722. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  7723. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  7724. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  7725. }
  7726. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  7727. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  7728. GGML_ASSERT(llama_is_byte_token(vocab, id));
  7729. const auto& token_data = vocab.id_to_token.at(id);
  7730. switch (llama_vocab_get_type(vocab)) {
  7731. case LLAMA_VOCAB_TYPE_SPM: {
  7732. auto buf = token_data.text.substr(3, 2);
  7733. return strtol(buf.c_str(), NULL, 16);
  7734. }
  7735. case LLAMA_VOCAB_TYPE_BPE: {
  7736. GGML_ASSERT(false);
  7737. return unicode_utf8_to_byte(token_data.text);
  7738. }
  7739. case LLAMA_VOCAB_TYPE_WPM: {
  7740. GGML_ASSERT(false);
  7741. }
  7742. default:
  7743. GGML_ASSERT(false);
  7744. }
  7745. }
  7746. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  7747. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  7748. static const char * hex = "0123456789ABCDEF";
  7749. switch (llama_vocab_get_type(vocab)) {
  7750. case LLAMA_VOCAB_TYPE_SPM: {
  7751. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  7752. auto token = vocab.token_to_id.find(buf);
  7753. if (token != vocab.token_to_id.end()) {
  7754. return (*token).second;
  7755. }
  7756. // Try to fall back to just the byte as a string
  7757. const char buf2[2] = { (char)ch, 0 };
  7758. return vocab.token_to_id.at(buf2);
  7759. }
  7760. case LLAMA_VOCAB_TYPE_WPM:
  7761. case LLAMA_VOCAB_TYPE_BPE: {
  7762. return vocab.token_to_id.at(unicode_byte_to_utf8(ch));
  7763. }
  7764. default:
  7765. GGML_ASSERT(false);
  7766. }
  7767. }
  7768. static void llama_escape_whitespace(std::string & text) {
  7769. replace_all(text, " ", "\xe2\x96\x81");
  7770. }
  7771. static void llama_unescape_whitespace(std::string & word) {
  7772. replace_all(word, "\xe2\x96\x81", " ");
  7773. }
  7774. struct llm_symbol {
  7775. using index = int;
  7776. index prev;
  7777. index next;
  7778. const char * text;
  7779. size_t n;
  7780. };
  7781. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  7782. // SPM tokenizer
  7783. // original implementation:
  7784. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  7785. struct llm_bigram_spm {
  7786. struct comparator {
  7787. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  7788. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  7789. }
  7790. };
  7791. using queue_storage = std::vector<llm_bigram_spm>;
  7792. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  7793. llm_symbol::index left;
  7794. llm_symbol::index right;
  7795. float score;
  7796. size_t size;
  7797. };
  7798. struct llm_tokenizer_spm {
  7799. llm_tokenizer_spm(const llama_vocab & vocab) : vocab(vocab) {}
  7800. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  7801. // split string into utf8 chars
  7802. int index = 0;
  7803. size_t offs = 0;
  7804. while (offs < text.size()) {
  7805. llm_symbol sym;
  7806. size_t len = utf8_len(text[offs]);
  7807. sym.text = text.c_str() + offs;
  7808. sym.n = std::min(len, text.size() - offs);
  7809. offs += sym.n;
  7810. sym.prev = index - 1;
  7811. sym.next = offs == text.size() ? -1 : index + 1;
  7812. index++;
  7813. symbols.emplace_back(sym);
  7814. }
  7815. // seed the work queue with all possible 2-character tokens.
  7816. for (size_t i = 1; i < symbols.size(); ++i) {
  7817. try_add_bigram(i - 1, i);
  7818. }
  7819. // keep substituting the highest frequency pairs for as long as we can.
  7820. while (!work_queue.empty()) {
  7821. auto bigram = work_queue.top();
  7822. work_queue.pop();
  7823. auto & left_sym = symbols[bigram.left];
  7824. auto & right_sym = symbols[bigram.right];
  7825. // if one of the symbols already got merged, skip it.
  7826. if (left_sym.n == 0 || right_sym.n == 0 ||
  7827. left_sym.n + right_sym.n != bigram.size) {
  7828. continue;
  7829. }
  7830. // merge the right sym into the left one
  7831. left_sym.n += right_sym.n;
  7832. right_sym.n = 0;
  7833. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  7834. // remove the right sym from the chain
  7835. left_sym.next = right_sym.next;
  7836. if (right_sym.next >= 0) {
  7837. symbols[right_sym.next].prev = bigram.left;
  7838. }
  7839. // find more substitutions
  7840. try_add_bigram(left_sym.prev, bigram.left);
  7841. try_add_bigram(bigram.left, left_sym.next);
  7842. }
  7843. for (int i = 0; i != -1; i = symbols[i].next) {
  7844. auto & symbol = symbols[i];
  7845. resegment(symbol, output);
  7846. }
  7847. }
  7848. private:
  7849. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  7850. auto text = std::string(symbol.text, symbol.n);
  7851. auto token = vocab.token_to_id.find(text);
  7852. // Do we need to support is_unused?
  7853. if (token != vocab.token_to_id.end()) {
  7854. output.push_back((*token).second);
  7855. return;
  7856. }
  7857. const auto p = rev_merge.find(text);
  7858. if (p == rev_merge.end()) {
  7859. // output any symbols that did not form tokens as bytes.
  7860. output.reserve(output.size() + symbol.n);
  7861. for (int j = 0; j < (int)symbol.n; ++j) {
  7862. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  7863. output.push_back(token_id);
  7864. }
  7865. return;
  7866. }
  7867. resegment(symbols[p->second.first], output);
  7868. resegment(symbols[p->second.second], output);
  7869. }
  7870. void try_add_bigram(int left, int right) {
  7871. if (left == -1 || right == -1) {
  7872. return;
  7873. }
  7874. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  7875. auto token = vocab.token_to_id.find(text);
  7876. if (token == vocab.token_to_id.end()) {
  7877. return;
  7878. }
  7879. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  7880. return;
  7881. }
  7882. const auto & tok_data = vocab.id_to_token[(*token).second];
  7883. llm_bigram_spm bigram;
  7884. bigram.left = left;
  7885. bigram.right = right;
  7886. bigram.score = tok_data.score;
  7887. bigram.size = text.size();
  7888. work_queue.push(bigram);
  7889. // Do we need to support is_unused?
  7890. rev_merge[text] = std::make_pair(left, right);
  7891. }
  7892. const llama_vocab & vocab;
  7893. std::vector<llm_symbol> symbols;
  7894. llm_bigram_spm::queue work_queue;
  7895. std::map<std::string, std::pair<int, int>> rev_merge;
  7896. };
  7897. // BPE tokenizer
  7898. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  7899. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  7900. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  7901. struct llm_bigram_bpe {
  7902. struct comparator {
  7903. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  7904. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  7905. }
  7906. };
  7907. using queue_storage = std::vector<llm_bigram_bpe>;
  7908. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  7909. llm_symbol::index left;
  7910. llm_symbol::index right;
  7911. std::string text;
  7912. int rank;
  7913. size_t size;
  7914. };
  7915. struct llm_tokenizer_bpe {
  7916. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  7917. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  7918. int final_prev_index = -1;
  7919. auto word_collection = bpe_gpt2_preprocess(text);
  7920. symbols_final.clear();
  7921. for (auto & word : word_collection) {
  7922. work_queue = llm_bigram_bpe::queue();
  7923. symbols.clear();
  7924. int index = 0;
  7925. size_t offset = 0;
  7926. while (offset < word.size()) {
  7927. llm_symbol sym;
  7928. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  7929. sym.text = word.c_str() + offset;
  7930. sym.n = char_len;
  7931. offset += sym.n;
  7932. sym.prev = index - 1;
  7933. sym.next = offset == word.size() ? -1 : index + 1;
  7934. index++;
  7935. symbols.emplace_back(sym);
  7936. }
  7937. for (size_t i = 1; i < symbols.size(); ++i) {
  7938. add_new_bigram(i - 1, i);
  7939. }
  7940. // build token(s)
  7941. while (!work_queue.empty()) {
  7942. auto bigram = work_queue.top();
  7943. work_queue.pop();
  7944. auto & left_symbol = symbols[bigram.left];
  7945. auto & right_symbol = symbols[bigram.right];
  7946. if (left_symbol.n == 0 || right_symbol.n == 0) {
  7947. continue;
  7948. }
  7949. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  7950. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  7951. if (left_token + right_token != bigram.text) {
  7952. continue; // Skip this bigram if it's outdated
  7953. }
  7954. // merge the right sym into the left one
  7955. left_symbol.n += right_symbol.n;
  7956. right_symbol.n = 0;
  7957. // remove the right sym from the chain
  7958. left_symbol.next = right_symbol.next;
  7959. if (right_symbol.next >= 0) {
  7960. symbols[right_symbol.next].prev = bigram.left;
  7961. }
  7962. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  7963. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  7964. }
  7965. // add the fnished tokens to the final list keeping correct order for next and prev
  7966. for (auto & sym : symbols) {
  7967. if (sym.n > 0) {
  7968. sym.prev = final_prev_index;
  7969. sym.next = -1;
  7970. if (final_prev_index != -1) {
  7971. symbols_final[final_prev_index].next = symbols_final.size();
  7972. }
  7973. symbols_final.emplace_back(sym);
  7974. final_prev_index = symbols_final.size() - 1;
  7975. }
  7976. }
  7977. }
  7978. symbols = symbols_final;
  7979. if (!symbols.empty()) {
  7980. for (int i = 0; i != -1; i = symbols[i].next) {
  7981. auto & symbol = symbols[i];
  7982. if (symbol.n == 0) {
  7983. continue;
  7984. }
  7985. const std::string str = std::string(symbol.text, symbol.n);
  7986. const auto token = vocab.token_to_id.find(str);
  7987. if (token == vocab.token_to_id.end()) {
  7988. for (auto j = str.begin(); j != str.end(); ++j) {
  7989. std::string byte_str(1, *j);
  7990. auto token_multibyte = vocab.token_to_id.find(byte_str);
  7991. if (token_multibyte == vocab.token_to_id.end()) {
  7992. throw std::runtime_error("ERROR: byte not found in vocab");
  7993. }
  7994. output.push_back((*token_multibyte).second);
  7995. }
  7996. } else {
  7997. output.push_back((*token).second);
  7998. }
  7999. }
  8000. }
  8001. }
  8002. private:
  8003. void add_new_bigram(int left, int right) {
  8004. if (left == -1 || right == -1) {
  8005. return;
  8006. }
  8007. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  8008. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  8009. int rank_found = -1;
  8010. rank_found = vocab.find_bpe_rank(left_token, right_token);
  8011. if (rank_found < 0) {
  8012. return;
  8013. }
  8014. llm_bigram_bpe bigram;
  8015. bigram.left = left;
  8016. bigram.right = right;
  8017. bigram.text = left_token + right_token;
  8018. bigram.size = left_token.size() + right_token.size();
  8019. bigram.rank = rank_found;
  8020. work_queue.push(bigram);
  8021. }
  8022. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  8023. std::vector<std::string> bpe_words;
  8024. std::vector<std::string> bpe_encoded_words;
  8025. std::string token = "";
  8026. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  8027. bool collecting_numeric = false;
  8028. bool collecting_letter = false;
  8029. bool collecting_special = false;
  8030. bool collecting_whitespace_lookahead = false;
  8031. bool collecting = false;
  8032. std::vector<std::string> text_utf;
  8033. text_utf.reserve(text.size());
  8034. bpe_words.reserve(text.size());
  8035. bpe_encoded_words.reserve(text.size());
  8036. const auto cpts = unicode_cpts_from_utf8(text);
  8037. for (size_t i = 0; i < cpts.size(); ++i)
  8038. text_utf.emplace_back(unicode_cpt_to_utf8(cpts[i]));
  8039. for (int i = 0; i < (int)text_utf.size(); i++) {
  8040. const std::string & utf_char = text_utf[i];
  8041. bool split_condition = false;
  8042. int bytes_remain = text_utf.size() - i;
  8043. // forward backward lookups
  8044. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  8045. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  8046. // handling contractions
  8047. if (!split_condition && bytes_remain >= 2) {
  8048. // 's|'t|'m|'d
  8049. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  8050. split_condition = true;
  8051. }
  8052. if (split_condition) {
  8053. if (token.size()) {
  8054. bpe_words.emplace_back(token); // push previous content as token
  8055. }
  8056. token = utf_char + utf_char_next;
  8057. bpe_words.emplace_back(token);
  8058. token = "";
  8059. i++;
  8060. continue;
  8061. }
  8062. }
  8063. if (!split_condition && bytes_remain >= 3) {
  8064. // 're|'ve|'ll
  8065. if (utf_char == "\'" && (
  8066. (utf_char_next == "r" && utf_char_next_next == "e") ||
  8067. (utf_char_next == "v" && utf_char_next_next == "e") ||
  8068. (utf_char_next == "l" && utf_char_next_next == "l"))
  8069. ) {
  8070. split_condition = true;
  8071. }
  8072. if (split_condition) {
  8073. // current token + next token can be defined
  8074. if (token.size()) {
  8075. bpe_words.emplace_back(token); // push previous content as token
  8076. }
  8077. token = utf_char + utf_char_next + utf_char_next_next;
  8078. bpe_words.emplace_back(token); // the contraction
  8079. token = "";
  8080. i += 2;
  8081. continue;
  8082. }
  8083. }
  8084. if (!split_condition && !collecting) {
  8085. if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  8086. collecting_letter = true;
  8087. collecting = true;
  8088. }
  8089. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  8090. collecting_numeric = true;
  8091. collecting = true;
  8092. }
  8093. else if (
  8094. ((unicode_cpt_type(utf_char) != CODEPOINT_TYPE_LETTER && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (unicode_cpt_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  8095. (!token.size() && utf_char == " " && unicode_cpt_type(utf_char_next) != CODEPOINT_TYPE_LETTER && unicode_cpt_type(utf_char_next) != CODEPOINT_TYPE_DIGIT && unicode_cpt_type(utf_char_next) != CODEPOINT_TYPE_WHITESPACE)
  8096. ) {
  8097. collecting_special = true;
  8098. collecting = true;
  8099. }
  8100. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  8101. collecting_whitespace_lookahead = true;
  8102. collecting = true;
  8103. }
  8104. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  8105. split_condition = true;
  8106. }
  8107. }
  8108. else if (!split_condition && collecting) {
  8109. if (collecting_letter && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  8110. split_condition = true;
  8111. }
  8112. else if (collecting_numeric && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  8113. split_condition = true;
  8114. }
  8115. else if (collecting_special && (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_LETTER || unicode_cpt_type(utf_char) == CODEPOINT_TYPE_DIGIT || unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE)) {
  8116. split_condition = true;
  8117. }
  8118. else if (collecting_whitespace_lookahead && (unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_LETTER || unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  8119. split_condition = true;
  8120. }
  8121. }
  8122. if (utf_char_next == "") {
  8123. split_condition = true; // final
  8124. token += utf_char;
  8125. }
  8126. if (split_condition) {
  8127. if (token.size()) {
  8128. bpe_words.emplace_back(token);
  8129. }
  8130. token = utf_char;
  8131. collecting = false;
  8132. collecting_letter = false;
  8133. collecting_numeric = false;
  8134. collecting_special = false;
  8135. collecting_whitespace_lookahead = false;
  8136. }
  8137. else {
  8138. token += utf_char;
  8139. }
  8140. }
  8141. for (std::string & word : bpe_words) {
  8142. std::string encoded_token = "";
  8143. for (char & c : word) {
  8144. encoded_token += unicode_byte_to_utf8(c);
  8145. }
  8146. bpe_encoded_words.emplace_back(encoded_token);
  8147. }
  8148. return bpe_encoded_words;
  8149. }
  8150. const llama_vocab & vocab;
  8151. std::vector<llm_symbol> symbols;
  8152. std::vector<llm_symbol> symbols_final;
  8153. llm_bigram_bpe::queue work_queue;
  8154. };
  8155. struct llm_tokenizer_wpm {
  8156. llm_tokenizer_wpm(const llama_vocab & vocab): vocab(vocab) {}
  8157. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  8158. auto * token_map = &vocab.token_to_id;
  8159. // normalize and split by whitespace
  8160. std::vector<std::string> words = preprocess(text);
  8161. // bos token prepended already
  8162. // find the longest tokens that form the words
  8163. for (const std::string &word : words) {
  8164. // skip empty words
  8165. if (word.size() == 0) {
  8166. continue;
  8167. }
  8168. // prepend phantom space
  8169. std::string word1 = "\xe2\x96\x81" + word;
  8170. int n = word1.size();
  8171. // we're at the start of a new word
  8172. int i = 0;
  8173. bool match_any = false;
  8174. // move through character position in word
  8175. while (i < n) {
  8176. // loop through possible match length
  8177. bool match = false;
  8178. for (int j = n; j > i; j--) {
  8179. auto it = token_map->find(word1.substr(i, j - i));
  8180. if (it != token_map->end()) {
  8181. output.push_back(it->second);
  8182. match = true;
  8183. match_any = true;
  8184. i = j;
  8185. break;
  8186. }
  8187. }
  8188. // must be an unknown character
  8189. if (!match) {
  8190. i++;
  8191. }
  8192. }
  8193. // we didn't find any matches for this word
  8194. if (!match_any) {
  8195. output.push_back(vocab.special_unk_id);
  8196. }
  8197. }
  8198. // append eos token
  8199. output.push_back(vocab.special_eos_id);
  8200. }
  8201. std::vector<std::string> preprocess(const std::string & text) {
  8202. std::vector<uint32_t> cpts_nfd = unicode_cpts_normalize_nfd(unicode_cpts_from_utf8(text));
  8203. // strip accents, strip control, uniformize whitespace,
  8204. // to lowercase, pad chinese characters, pad punctuation
  8205. std::string new_str = "";
  8206. for (uint32_t code : cpts_nfd) {
  8207. int type = unicode_cpt_type(code);
  8208. if (type == CODEPOINT_TYPE_ACCENT_MARK || type == CODEPOINT_TYPE_CONTROL) {
  8209. continue;
  8210. }
  8211. code = to_lower(code);
  8212. if (type == CODEPOINT_TYPE_WHITESPACE) {
  8213. code = ' ';
  8214. }
  8215. std::string s = unicode_cpt_to_utf8(code);
  8216. if (type == CODEPOINT_TYPE_PUNCTUATION || is_ascii_punct(code) || is_chinese_char(code)) {
  8217. new_str += " ";
  8218. new_str += s;
  8219. new_str += " ";
  8220. } else {
  8221. new_str += s;
  8222. }
  8223. }
  8224. // split by whitespace
  8225. uint64_t l = 0;
  8226. uint64_t r = 0;
  8227. std::vector<std::string> words;
  8228. while (r < new_str.size()) {
  8229. // if is whitespace
  8230. if (isspace(new_str[r])) {
  8231. if (r > l) words.push_back(new_str.substr(l, (r - l)));
  8232. l = r + 1;
  8233. r = l;
  8234. } else {
  8235. r += 1;
  8236. }
  8237. }
  8238. if (r > l) {
  8239. words.push_back(new_str.substr(l, (r - l)));
  8240. }
  8241. return words;
  8242. }
  8243. uint32_t to_lower(uint32_t code) {
  8244. static const std::locale locale("en_US.UTF-8");
  8245. #if defined(_WIN32)
  8246. if (code > 0xFFFF) {
  8247. return code;
  8248. }
  8249. #endif
  8250. return std::tolower(wchar_t(code), locale);
  8251. }
  8252. bool is_ascii_punct(uint32_t code) {
  8253. return code < 256 && ispunct(code);
  8254. }
  8255. bool is_chinese_char(uint32_t cpt) {
  8256. if ((cpt >= 0x4E00 && cpt <= 0x9FFF) ||
  8257. (cpt >= 0x3400 && cpt <= 0x4DBF) ||
  8258. (cpt >= 0x20000 && cpt <= 0x2A6DF) ||
  8259. (cpt >= 0x2A700 && cpt <= 0x2B73F) ||
  8260. (cpt >= 0x2B740 && cpt <= 0x2B81F) ||
  8261. (cpt >= 0x2B920 && cpt <= 0x2CEAF) || // this should be 0x2B820 but in hf rust code it is 0x2B920
  8262. (cpt >= 0xF900 && cpt <= 0xFAFF) ||
  8263. (cpt >= 0x2F800 && cpt <= 0x2FA1F) ||
  8264. (cpt >= 0x3000 && cpt <= 0x303F) ||
  8265. (cpt >= 0xFF00 && cpt <= 0xFFEF)) {
  8266. return true; // NOLINT
  8267. }
  8268. return false;
  8269. }
  8270. const llama_vocab & vocab;
  8271. };
  8272. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE {
  8273. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  8274. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  8275. } FRAGMENT_BUFFER_VARIANT_TYPE;
  8276. struct fragment_buffer_variant {
  8277. fragment_buffer_variant(llama_vocab::id _token)
  8278. :
  8279. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  8280. token(_token),
  8281. raw_text(_dummy),
  8282. offset(0),
  8283. length(0) {}
  8284. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  8285. :
  8286. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  8287. token((llama_vocab::id) - 1),
  8288. raw_text(_raw_text),
  8289. offset(_offset),
  8290. length(_length){
  8291. GGML_ASSERT(_offset >= 0);
  8292. GGML_ASSERT(_length >= 1);
  8293. GGML_ASSERT(offset + length <= raw_text.length());
  8294. }
  8295. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  8296. const llama_vocab::id token;
  8297. const std::string _dummy;
  8298. const std::string & raw_text;
  8299. const uint64_t offset;
  8300. const uint64_t length;
  8301. };
  8302. // #define PRETOKENIZERDEBUG
  8303. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer) {
  8304. // for each special token
  8305. for (const auto & st: vocab.special_tokens_cache) {
  8306. const auto & special_token = st.first;
  8307. const auto & special_id = st.second;
  8308. // for each text fragment
  8309. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  8310. while (it != buffer.end()) {
  8311. auto & fragment = (*it);
  8312. // if a fragment is text ( not yet processed )
  8313. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  8314. auto * raw_text = &(fragment.raw_text);
  8315. auto raw_text_base_offset = fragment.offset;
  8316. auto raw_text_base_length = fragment.length;
  8317. // loop over the text
  8318. while (true) {
  8319. // find the first occurrence of a given special token in this fragment
  8320. // passing offset argument only limit the "search area" but match coordinates
  8321. // are still relative to the source full raw_text
  8322. auto match = raw_text->find(special_token, raw_text_base_offset);
  8323. // no occurrences found, stop processing this fragment for a given special token
  8324. if (match == std::string::npos) break;
  8325. // check if match is within bounds of offset <-> length
  8326. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  8327. #ifdef PRETOKENIZERDEBUG
  8328. LLAMA_LOG_WARN("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());
  8329. #endif
  8330. auto source = std::distance(buffer.begin(), it);
  8331. // if match is further than base offset
  8332. // then we have some text to the left of it
  8333. if (match > raw_text_base_offset) {
  8334. // left
  8335. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  8336. const int64_t left_reminder_length = match - raw_text_base_offset;
  8337. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  8338. #ifdef PRETOKENIZERDEBUG
  8339. LLAMA_LOG_WARN("FL: (%ld %ld) '%s'\n", left_reminder_offset, left_reminder_length, raw_text->substr(left_reminder_offset, left_reminder_length).c_str());
  8340. #endif
  8341. it++;
  8342. }
  8343. // special token
  8344. buffer.emplace_after(it, special_id);
  8345. it++;
  8346. // right
  8347. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  8348. const int64_t right_reminder_offset = match + special_token.length();
  8349. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  8350. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  8351. #ifdef PRETOKENIZERDEBUG
  8352. LLAMA_LOG_WARN("FR: (%ld %ld) '%s'\n", right_reminder_offset, right_reminder_length, raw_text->substr(right_reminder_offset, right_reminder_length).c_str());
  8353. #endif
  8354. it++;
  8355. if (source == 0) {
  8356. buffer.erase_after(buffer.before_begin());
  8357. } else {
  8358. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  8359. }
  8360. // repeat for the right side
  8361. raw_text_base_offset = right_reminder_offset;
  8362. raw_text_base_length = right_reminder_length;
  8363. #ifdef PRETOKENIZERDEBUG
  8364. LLAMA_LOG_WARN("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());
  8365. #endif
  8366. } else {
  8367. if (source == 0) {
  8368. buffer.erase_after(buffer.before_begin());
  8369. } else {
  8370. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  8371. }
  8372. break;
  8373. }
  8374. }
  8375. }
  8376. it++;
  8377. }
  8378. }
  8379. }
  8380. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  8381. std::vector<llama_vocab::id> output;
  8382. // OG tokenizer behavior:
  8383. //
  8384. // tokenizer.encode('', add_bos=True) returns [1]
  8385. // tokenizer.encode('', add_bos=False) returns []
  8386. if (bos && vocab.special_bos_id != -1) {
  8387. output.push_back(vocab.special_bos_id);
  8388. }
  8389. if (raw_text.empty()) {
  8390. return output;
  8391. }
  8392. std::forward_list<fragment_buffer_variant> fragment_buffer;
  8393. fragment_buffer.emplace_front(raw_text, 0, raw_text.length());
  8394. if (special) tokenizer_st_partition(vocab, fragment_buffer);
  8395. switch (vocab.type) {
  8396. case LLAMA_VOCAB_TYPE_SPM:
  8397. {
  8398. for (const auto & fragment : fragment_buffer) {
  8399. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  8400. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  8401. // TODO: It's likely possible to get rid of this string copy entirely
  8402. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  8403. // and passing 'add space prefix' as bool argument
  8404. //
  8405. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  8406. if (&fragment == &fragment_buffer.front()) {
  8407. if (vocab.add_space_prefix) {
  8408. raw_text = " " + raw_text; // prefix with space if the first token is not special
  8409. }
  8410. }
  8411. #ifdef PRETOKENIZERDEBUG
  8412. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  8413. #endif
  8414. llm_tokenizer_spm tokenizer(vocab);
  8415. llama_escape_whitespace(raw_text);
  8416. tokenizer.tokenize(raw_text, output);
  8417. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  8418. output.push_back(fragment.token);
  8419. }
  8420. }
  8421. } break;
  8422. case LLAMA_VOCAB_TYPE_BPE:
  8423. {
  8424. for (const auto & fragment : fragment_buffer) {
  8425. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  8426. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  8427. #ifdef PRETOKENIZERDEBUG
  8428. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  8429. #endif
  8430. llm_tokenizer_bpe tokenizer(vocab);
  8431. tokenizer.tokenize(raw_text, output);
  8432. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  8433. output.push_back(fragment.token);
  8434. }
  8435. }
  8436. } break;
  8437. case LLAMA_VOCAB_TYPE_WPM:
  8438. {
  8439. for (const auto & fragment : fragment_buffer) {
  8440. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  8441. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  8442. #ifdef PRETOKENIZERDEBUG
  8443. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  8444. #endif
  8445. llm_tokenizer_wpm tokenizer(vocab);
  8446. tokenizer.tokenize(raw_text, output);
  8447. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  8448. output.push_back(fragment.token);
  8449. }
  8450. }
  8451. } break;
  8452. case LLAMA_VOCAB_TYPE_NONE:
  8453. GGML_ASSERT(false);
  8454. }
  8455. return output;
  8456. }
  8457. //
  8458. // grammar - internal
  8459. //
  8460. struct llama_partial_utf8 {
  8461. uint32_t value; // bit value so far (unshifted)
  8462. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  8463. };
  8464. struct llama_grammar {
  8465. const std::vector<std::vector<llama_grammar_element>> rules;
  8466. std::vector<std::vector<const llama_grammar_element *>> stacks;
  8467. // buffer for partially generated UTF-8 sequence from accepted tokens
  8468. llama_partial_utf8 partial_utf8;
  8469. };
  8470. struct llama_grammar_candidate {
  8471. size_t index;
  8472. const uint32_t * code_points;
  8473. llama_partial_utf8 partial_utf8;
  8474. };
  8475. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  8476. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  8477. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  8478. const std::string & src,
  8479. llama_partial_utf8 partial_start) {
  8480. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  8481. const char * pos = src.c_str();
  8482. std::vector<uint32_t> code_points;
  8483. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  8484. code_points.reserve(src.size() + 1);
  8485. uint32_t value = partial_start.value;
  8486. int n_remain = partial_start.n_remain;
  8487. // continue previous decode, if applicable
  8488. while (*pos != 0 && n_remain > 0) {
  8489. uint8_t next_byte = static_cast<uint8_t>(*pos);
  8490. if ((next_byte >> 6) != 2) {
  8491. // invalid sequence, abort
  8492. code_points.push_back(0);
  8493. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  8494. }
  8495. value = (value << 6) + (next_byte & 0x3F);
  8496. ++pos;
  8497. --n_remain;
  8498. }
  8499. if (partial_start.n_remain > 0 && n_remain == 0) {
  8500. code_points.push_back(value);
  8501. }
  8502. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  8503. while (*pos != 0) {
  8504. uint8_t first_byte = static_cast<uint8_t>(*pos);
  8505. uint8_t highbits = first_byte >> 4;
  8506. n_remain = lookup[highbits] - 1;
  8507. if (n_remain < 0) {
  8508. // invalid sequence, abort
  8509. code_points.clear();
  8510. code_points.push_back(0);
  8511. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  8512. }
  8513. uint8_t mask = (1 << (7 - n_remain)) - 1;
  8514. value = first_byte & mask;
  8515. ++pos;
  8516. while (*pos != 0 && n_remain > 0) {
  8517. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  8518. ++pos;
  8519. --n_remain;
  8520. }
  8521. if (n_remain == 0) {
  8522. code_points.push_back(value);
  8523. }
  8524. }
  8525. code_points.push_back(0);
  8526. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  8527. }
  8528. // returns true iff pos points to the end of one of the definitions of a rule
  8529. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  8530. switch (pos->type) {
  8531. case LLAMA_GRETYPE_END: return true; // NOLINT
  8532. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  8533. default: return false;
  8534. }
  8535. }
  8536. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  8537. // asserts that pos is pointing to a char range element
  8538. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  8539. const llama_grammar_element * pos,
  8540. const uint32_t chr) {
  8541. bool found = false;
  8542. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  8543. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  8544. do {
  8545. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  8546. // inclusive range, e.g. [a-z]
  8547. found = found || (pos->value <= chr && chr <= pos[1].value);
  8548. pos += 2;
  8549. } else {
  8550. // exact char match, e.g. [a] or "a"
  8551. found = found || pos->value == chr;
  8552. pos += 1;
  8553. }
  8554. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  8555. return std::make_pair(found == is_positive_char, pos);
  8556. }
  8557. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  8558. // range at pos (regular or inverse range)
  8559. // asserts that pos is pointing to a char range element
  8560. static bool llama_grammar_match_partial_char(
  8561. const llama_grammar_element * pos,
  8562. const llama_partial_utf8 partial_utf8) {
  8563. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  8564. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  8565. uint32_t partial_value = partial_utf8.value;
  8566. int n_remain = partial_utf8.n_remain;
  8567. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  8568. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  8569. return false;
  8570. }
  8571. // range of possible code points this partial UTF-8 sequence could complete to
  8572. uint32_t low = partial_value << (n_remain * 6);
  8573. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  8574. if (low == 0) {
  8575. if (n_remain == 2) {
  8576. low = 1 << 11;
  8577. } else if (n_remain == 3) {
  8578. low = 1 << 16;
  8579. }
  8580. }
  8581. do {
  8582. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  8583. // inclusive range, e.g. [a-z]
  8584. if (pos->value <= high && low <= pos[1].value) {
  8585. return is_positive_char;
  8586. }
  8587. pos += 2;
  8588. } else {
  8589. // exact char match, e.g. [a] or "a"
  8590. if (low <= pos->value && pos->value <= high) {
  8591. return is_positive_char;
  8592. }
  8593. pos += 1;
  8594. }
  8595. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  8596. return !is_positive_char;
  8597. }
  8598. // transforms a grammar pushdown stack into N possible stacks, all ending
  8599. // at a character range (terminal element)
  8600. static void llama_grammar_advance_stack(
  8601. const std::vector<std::vector<llama_grammar_element>> & rules,
  8602. const std::vector<const llama_grammar_element *> & stack,
  8603. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  8604. if (stack.empty()) {
  8605. new_stacks.emplace_back(stack);
  8606. return;
  8607. }
  8608. const llama_grammar_element * pos = stack.back();
  8609. switch (pos->type) {
  8610. case LLAMA_GRETYPE_RULE_REF: {
  8611. const size_t rule_id = static_cast<size_t>(pos->value);
  8612. const llama_grammar_element * subpos = rules[rule_id].data();
  8613. do {
  8614. // init new stack without the top (pos)
  8615. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  8616. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  8617. // if this rule ref is followed by another element, add that to stack
  8618. new_stack.push_back(pos + 1);
  8619. }
  8620. if (!llama_grammar_is_end_of_sequence(subpos)) {
  8621. // if alternate is nonempty, add to stack
  8622. new_stack.push_back(subpos);
  8623. }
  8624. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  8625. while (!llama_grammar_is_end_of_sequence(subpos)) {
  8626. // scan to end of alternate def
  8627. subpos++;
  8628. }
  8629. if (subpos->type == LLAMA_GRETYPE_ALT) {
  8630. // there's another alternate def of this rule to process
  8631. subpos++;
  8632. } else {
  8633. break;
  8634. }
  8635. } while (true);
  8636. break;
  8637. }
  8638. case LLAMA_GRETYPE_CHAR:
  8639. case LLAMA_GRETYPE_CHAR_NOT:
  8640. new_stacks.emplace_back(stack);
  8641. break;
  8642. default:
  8643. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  8644. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  8645. // those
  8646. GGML_ASSERT(false);
  8647. }
  8648. }
  8649. // takes a set of possible pushdown stacks on a grammar, which are required to
  8650. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  8651. // produces the N possible stacks if the given char is accepted at those
  8652. // positions
  8653. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  8654. const std::vector<std::vector<llama_grammar_element>> & rules,
  8655. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  8656. const uint32_t chr) {
  8657. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  8658. for (const auto & stack : stacks) {
  8659. if (stack.empty()) {
  8660. continue;
  8661. }
  8662. auto match = llama_grammar_match_char(stack.back(), chr);
  8663. if (match.first) {
  8664. const llama_grammar_element * pos = match.second;
  8665. // update top of stack to next element, if any
  8666. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  8667. if (!llama_grammar_is_end_of_sequence(pos)) {
  8668. new_stack.push_back(pos);
  8669. }
  8670. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  8671. }
  8672. }
  8673. return new_stacks;
  8674. }
  8675. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  8676. const std::vector<std::vector<llama_grammar_element>> & rules,
  8677. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  8678. const std::vector<llama_grammar_candidate> & candidates);
  8679. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  8680. const std::vector<std::vector<llama_grammar_element>> & rules,
  8681. const std::vector<const llama_grammar_element *> & stack,
  8682. const std::vector<llama_grammar_candidate> & candidates) {
  8683. std::vector<llama_grammar_candidate> rejects;
  8684. if (stack.empty()) {
  8685. for (const auto & tok : candidates) {
  8686. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  8687. rejects.push_back(tok);
  8688. }
  8689. }
  8690. return rejects;
  8691. }
  8692. const llama_grammar_element * stack_pos = stack.back();
  8693. std::vector<llama_grammar_candidate> next_candidates;
  8694. for (const auto & tok : candidates) {
  8695. if (*tok.code_points == 0) {
  8696. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  8697. // that cannot satisfy this position in grammar
  8698. if (tok.partial_utf8.n_remain != 0 &&
  8699. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  8700. rejects.push_back(tok);
  8701. }
  8702. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  8703. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  8704. } else {
  8705. rejects.push_back(tok);
  8706. }
  8707. }
  8708. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  8709. // update top of stack to next element, if any
  8710. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  8711. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  8712. stack_after.push_back(stack_pos_after);
  8713. }
  8714. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  8715. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  8716. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  8717. for (const auto & tok : next_rejects) {
  8718. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  8719. }
  8720. return rejects;
  8721. }
  8722. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  8723. const std::vector<std::vector<llama_grammar_element>> & rules,
  8724. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  8725. const std::vector<llama_grammar_candidate> & candidates) {
  8726. GGML_ASSERT(!stacks.empty()); // REVIEW
  8727. if (candidates.empty()) {
  8728. return std::vector<llama_grammar_candidate>();
  8729. }
  8730. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  8731. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  8732. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  8733. }
  8734. return rejects;
  8735. }
  8736. //
  8737. // grammar - external
  8738. //
  8739. struct llama_grammar * llama_grammar_init(
  8740. const llama_grammar_element ** rules,
  8741. size_t n_rules,
  8742. size_t start_rule_index) {
  8743. const llama_grammar_element * pos;
  8744. // copy rule definitions into vectors
  8745. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  8746. for (size_t i = 0; i < n_rules; i++) {
  8747. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  8748. vec_rules[i].push_back(*pos);
  8749. }
  8750. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  8751. }
  8752. // loop over alternates of start rule to build initial stacks
  8753. std::vector<std::vector<const llama_grammar_element *>> stacks;
  8754. pos = vec_rules[start_rule_index].data();
  8755. do {
  8756. std::vector<const llama_grammar_element *> stack;
  8757. if (!llama_grammar_is_end_of_sequence(pos)) {
  8758. // if alternate is nonempty, add to stack
  8759. stack.push_back(pos);
  8760. }
  8761. llama_grammar_advance_stack(vec_rules, stack, stacks);
  8762. while (!llama_grammar_is_end_of_sequence(pos)) {
  8763. // scan to end of alternate def
  8764. pos++;
  8765. }
  8766. if (pos->type == LLAMA_GRETYPE_ALT) {
  8767. // there's another alternate def of this rule to process
  8768. pos++;
  8769. } else {
  8770. break;
  8771. }
  8772. } while (true);
  8773. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  8774. }
  8775. void llama_grammar_free(struct llama_grammar * grammar) {
  8776. delete grammar;
  8777. }
  8778. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  8779. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  8780. // redirect elements in stacks to point to new rules
  8781. for (size_t is = 0; is < result->stacks.size(); is++) {
  8782. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  8783. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  8784. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  8785. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  8786. result->stacks[is][ie] = &result->rules[ir0][ir1];
  8787. }
  8788. }
  8789. }
  8790. }
  8791. }
  8792. return result;
  8793. }
  8794. //
  8795. // sampling
  8796. //
  8797. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  8798. if (seed == LLAMA_DEFAULT_SEED) {
  8799. seed = time(NULL);
  8800. }
  8801. ctx->rng.seed(seed);
  8802. }
  8803. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  8804. GGML_ASSERT(candidates->size > 0);
  8805. const int64_t t_start_sample_us = ggml_time_us();
  8806. // Sort the logits in descending order
  8807. if (!candidates->sorted) {
  8808. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  8809. return a.logit > b.logit;
  8810. });
  8811. candidates->sorted = true;
  8812. }
  8813. float max_l = candidates->data[0].logit;
  8814. float cum_sum = 0.0f;
  8815. for (size_t i = 0; i < candidates->size; ++i) {
  8816. float p = expf(candidates->data[i].logit - max_l);
  8817. candidates->data[i].p = p;
  8818. cum_sum += p;
  8819. }
  8820. for (size_t i = 0; i < candidates->size; ++i) {
  8821. candidates->data[i].p /= cum_sum;
  8822. }
  8823. if (ctx) {
  8824. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8825. }
  8826. }
  8827. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  8828. // TODO: move bucket sort to separate function so that top_p/tail_free/typical/softmax first is equally fast
  8829. // if (k >= (int32_t)candidates->size) {
  8830. // return;
  8831. // }
  8832. const int64_t t_start_sample_us = ggml_time_us();
  8833. if (k <= 0) {
  8834. k = candidates->size;
  8835. }
  8836. k = std::max(k, (int) min_keep);
  8837. k = std::min(k, (int) candidates->size);
  8838. // Sort scores in descending order
  8839. if (!candidates->sorted) {
  8840. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  8841. return a.logit > b.logit;
  8842. };
  8843. if (k <= 128) {
  8844. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  8845. } else {
  8846. constexpr int nbuckets = 128;
  8847. constexpr float bucket_low = -10.0f;
  8848. constexpr float bucket_high = 10.0f;
  8849. constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
  8850. constexpr float bucker_inter = -bucket_low * bucket_scale;
  8851. std::vector<int> bucket_idx(candidates->size);
  8852. std::vector<int> histo(nbuckets, 0);
  8853. for (int i = 0; i < (int)candidates->size; ++i) {
  8854. const float val = candidates->data[i].logit;
  8855. int ib = int(bucket_scale * val + bucker_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
  8856. ib = std::max(0, std::min(nbuckets-1, ib));
  8857. bucket_idx[i] = ib;
  8858. ++histo[ib];
  8859. }
  8860. int nhave = 0;
  8861. int ib = nbuckets - 1;
  8862. for ( ; ib >= 0; --ib) {
  8863. nhave += histo[ib];
  8864. if (nhave >= k) break;
  8865. }
  8866. std::vector<llama_token_data> tmp_tokens(nhave);
  8867. auto ptr = tmp_tokens.data();
  8868. std::vector<llama_token_data*> bucket_ptrs;
  8869. bucket_ptrs.reserve(nbuckets - ib);
  8870. for (int j = nbuckets - 1; j >= ib; --j) {
  8871. bucket_ptrs.push_back(ptr);
  8872. ptr += histo[j];
  8873. }
  8874. for (int i = 0; i < (int)candidates->size; ++i) {
  8875. int j = bucket_idx[i];
  8876. if (j >= ib) {
  8877. *bucket_ptrs[nbuckets-1-j]++ = candidates->data[i];
  8878. }
  8879. }
  8880. ptr = tmp_tokens.data();
  8881. int ndone = 0;
  8882. for (int j = nbuckets-1; j > ib; --j) {
  8883. std::sort(ptr, ptr + histo[j], comp);
  8884. ptr += histo[j];
  8885. ndone += histo[j];
  8886. }
  8887. std::partial_sort(ptr, ptr + k - ndone, ptr + histo[ib], comp);
  8888. std::memcpy(candidates->data, tmp_tokens.data(), k*sizeof(llama_token_data));
  8889. }
  8890. candidates->sorted = true;
  8891. }
  8892. candidates->size = k;
  8893. if (ctx) {
  8894. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8895. }
  8896. }
  8897. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  8898. if (p >= 1.0f) {
  8899. return;
  8900. }
  8901. llama_sample_softmax(ctx, candidates);
  8902. const int64_t t_start_sample_us = ggml_time_us();
  8903. // Compute the cumulative probabilities
  8904. float cum_sum = 0.0f;
  8905. size_t last_idx = candidates->size;
  8906. for (size_t i = 0; i < candidates->size; ++i) {
  8907. cum_sum += candidates->data[i].p;
  8908. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  8909. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  8910. if (cum_sum >= p && i + 1 >= min_keep) {
  8911. last_idx = i + 1;
  8912. break;
  8913. }
  8914. }
  8915. // Resize the output vector to keep only the top-p tokens
  8916. candidates->size = last_idx;
  8917. if (ctx) {
  8918. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8919. }
  8920. }
  8921. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  8922. if (p <= 0.0f || !candidates->size) {
  8923. return;
  8924. }
  8925. const int64_t t_start_sample_us = ggml_time_us();
  8926. bool min_p_applied = false;
  8927. // if the candidates aren't sorted, try the unsorted implementation first
  8928. if (!candidates->sorted) {
  8929. std::vector<llama_token_data> filtered_tokens;
  8930. float max_logit = -FLT_MAX;
  8931. for (size_t i = 0; i < candidates->size; ++i) {
  8932. max_logit = std::max(max_logit, candidates->data[i].logit);
  8933. }
  8934. const float min_logit = max_logit + logf(p); // min logit for p_i >= p * p_max
  8935. for (size_t i = 0; i < candidates->size; ++i) {
  8936. if (candidates->data[i].logit >= min_logit) {
  8937. filtered_tokens.push_back(candidates->data[i]);
  8938. }
  8939. }
  8940. // if we have enough values the operation was a success
  8941. if (filtered_tokens.size() >= min_keep) {
  8942. memcpy(candidates->data, filtered_tokens.data(), filtered_tokens.size()*sizeof(llama_token_data));
  8943. candidates->size = filtered_tokens.size();
  8944. min_p_applied = true;
  8945. }
  8946. }
  8947. // if the candidates are sorted or the unsorted implementation failed, use this implementation
  8948. if (!min_p_applied) {
  8949. // Sort the logits in descending order
  8950. if (!candidates->sorted) {
  8951. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  8952. return a.logit > b.logit;
  8953. });
  8954. candidates->sorted = true;
  8955. }
  8956. const float min_logit = candidates->data[0].logit + logf(p); // min logit for p_i >= p * p_max
  8957. size_t i = 1; // first token always matches
  8958. for (; i < candidates->size; ++i) {
  8959. if (candidates->data[i].logit < min_logit && i >= min_keep) {
  8960. break; // prob too small
  8961. }
  8962. }
  8963. // Resize the output vector to keep only the matching tokens
  8964. candidates->size = i;
  8965. }
  8966. if (ctx) {
  8967. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8968. }
  8969. }
  8970. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  8971. if (z >= 1.0f || candidates->size <= 2) {
  8972. return;
  8973. }
  8974. llama_sample_softmax(nullptr, candidates);
  8975. const int64_t t_start_sample_us = ggml_time_us();
  8976. // Compute the first and second derivatives
  8977. std::vector<float> first_derivatives(candidates->size - 1);
  8978. std::vector<float> second_derivatives(candidates->size - 2);
  8979. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  8980. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  8981. }
  8982. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  8983. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  8984. }
  8985. // Calculate absolute value of second derivatives
  8986. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  8987. second_derivatives[i] = std::abs(second_derivatives[i]);
  8988. }
  8989. // Normalize the second derivatives
  8990. {
  8991. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  8992. if (second_derivatives_sum > 1e-6f) {
  8993. for (float & value : second_derivatives) {
  8994. value /= second_derivatives_sum;
  8995. }
  8996. } else {
  8997. for (float & value : second_derivatives) {
  8998. value = 1.0f / second_derivatives.size();
  8999. }
  9000. }
  9001. }
  9002. float cum_sum = 0.0f;
  9003. size_t last_idx = candidates->size;
  9004. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  9005. cum_sum += second_derivatives[i];
  9006. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  9007. if (cum_sum > z && i >= min_keep) {
  9008. last_idx = i;
  9009. break;
  9010. }
  9011. }
  9012. // Resize the output vector to keep only the tokens above the tail location
  9013. candidates->size = last_idx;
  9014. if (ctx) {
  9015. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9016. }
  9017. }
  9018. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  9019. // Reference implementation:
  9020. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  9021. if (p >= 1.0f) {
  9022. return;
  9023. }
  9024. // Compute the softmax of logits and calculate entropy
  9025. llama_sample_softmax(nullptr, candidates);
  9026. const int64_t t_start_sample_us = ggml_time_us();
  9027. float entropy = 0.0f;
  9028. for (size_t i = 0; i < candidates->size; ++i) {
  9029. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  9030. }
  9031. // Compute the absolute difference between negative log probability and entropy for each candidate
  9032. std::vector<float> shifted_scores;
  9033. for (size_t i = 0; i < candidates->size; ++i) {
  9034. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  9035. shifted_scores.push_back(shifted_score);
  9036. }
  9037. // Sort tokens based on the shifted_scores and their corresponding indices
  9038. std::vector<size_t> indices(candidates->size);
  9039. std::iota(indices.begin(), indices.end(), 0);
  9040. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  9041. return shifted_scores[a] < shifted_scores[b];
  9042. });
  9043. // Compute the cumulative probabilities
  9044. float cum_sum = 0.0f;
  9045. size_t last_idx = indices.size();
  9046. for (size_t i = 0; i < indices.size(); ++i) {
  9047. size_t idx = indices[i];
  9048. cum_sum += candidates->data[idx].p;
  9049. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  9050. if (cum_sum > p && i >= min_keep - 1) {
  9051. last_idx = i + 1;
  9052. break;
  9053. }
  9054. }
  9055. // Resize the output vector to keep only the locally typical tokens
  9056. std::vector<llama_token_data> new_candidates;
  9057. for (size_t i = 0; i < last_idx; ++i) {
  9058. size_t idx = indices[i];
  9059. new_candidates.push_back(candidates->data[idx]);
  9060. }
  9061. // Replace the data in candidates with the new_candidates data
  9062. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  9063. candidates->size = new_candidates.size();
  9064. candidates->sorted = false;
  9065. if (ctx) {
  9066. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9067. }
  9068. }
  9069. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  9070. const int64_t t_start_sample_us = ggml_time_us();
  9071. // no need to do anything if there is only one (or zero) candidates
  9072. if(candidates_p->size <= 1) {
  9073. return;
  9074. }
  9075. // Calculate maximum possible entropy
  9076. float max_entropy = -logf(1.0f / candidates_p->size);
  9077. llama_sample_softmax(nullptr, candidates_p);
  9078. // Calculate entropy of the softmax probabilities
  9079. float entropy = 0.0f;
  9080. for (size_t i = 0; i < candidates_p->size; ++i) {
  9081. float prob = candidates_p->data[i].p;
  9082. if (prob > 0.0f) { // Ensure no log(0)
  9083. entropy -= prob * logf(prob);
  9084. }
  9085. }
  9086. // Normalize the entropy (max_entropy cannot be 0 here because we checked candidates_p->size != 1 above)
  9087. float normalized_entropy = entropy / max_entropy;
  9088. // Map the normalized entropy to the desired temperature range using the power function
  9089. float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);
  9090. #ifdef DEBUG
  9091. LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
  9092. LLAMA_LOG_INFO("Entropy: %f\n", entropy);
  9093. LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
  9094. LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
  9095. LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
  9096. LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
  9097. #endif
  9098. // Apply the dynamically calculated temperature scaling
  9099. for (size_t i = 0; i < candidates_p->size; ++i) {
  9100. candidates_p->data[i].logit /= dyn_temp;
  9101. }
  9102. // Re-compute softmax probabilities after scaling logits with dynamic temperature
  9103. double max_l_double = candidates_p->data[0].logit;
  9104. double cum_sum_double = 0.0;
  9105. for (size_t i = 0; i < candidates_p->size; ++i) {
  9106. double p = exp(candidates_p->data[i].logit - max_l_double);
  9107. candidates_p->data[i].p = p; // Store the scaled probability
  9108. cum_sum_double += p;
  9109. }
  9110. for (size_t i = 0; i < candidates_p->size; ++i) {
  9111. candidates_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
  9112. }
  9113. #ifdef DEBUG
  9114. // Print the updated top 25 probabilities after temperature scaling
  9115. LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
  9116. for (size_t i = 0; i < 25 && i < candidates_p->size; ++i) {
  9117. LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, candidates_p->data[i].p * 100.0f);
  9118. }
  9119. #endif
  9120. if (ctx) {
  9121. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9122. }
  9123. }
  9124. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  9125. const int64_t t_start_sample_us = ggml_time_us();
  9126. for (size_t i = 0; i < candidates_p->size; ++i) {
  9127. candidates_p->data[i].logit /= temp;
  9128. }
  9129. if (ctx) {
  9130. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9131. }
  9132. }
  9133. void llama_sample_repetition_penalties(
  9134. struct llama_context * ctx,
  9135. llama_token_data_array * candidates,
  9136. const llama_token * last_tokens,
  9137. size_t penalty_last_n,
  9138. float penalty_repeat,
  9139. float penalty_freq,
  9140. float penalty_present) {
  9141. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  9142. return;
  9143. }
  9144. const int64_t t_start_sample_us = ggml_time_us();
  9145. // Create a frequency map to count occurrences of each token in last_tokens
  9146. std::unordered_map<llama_token, int> token_count;
  9147. for (size_t i = 0; i < penalty_last_n; ++i) {
  9148. token_count[last_tokens[i]]++;
  9149. }
  9150. // Apply frequency and presence penalties to the candidates
  9151. for (size_t i = 0; i < candidates->size; ++i) {
  9152. const auto token_iter = token_count.find(candidates->data[i].id);
  9153. if (token_iter == token_count.end()) {
  9154. continue;
  9155. }
  9156. const int count = token_iter->second;
  9157. // 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.
  9158. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  9159. if (candidates->data[i].logit <= 0) {
  9160. candidates->data[i].logit *= penalty_repeat;
  9161. } else {
  9162. candidates->data[i].logit /= penalty_repeat;
  9163. }
  9164. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  9165. }
  9166. candidates->sorted = false;
  9167. if (ctx) {
  9168. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9169. }
  9170. }
  9171. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  9172. GGML_ASSERT(ctx);
  9173. const int64_t t_start_sample_us = ggml_time_us();
  9174. bool allow_eos = false;
  9175. for (const auto & stack : grammar->stacks) {
  9176. if (stack.empty()) {
  9177. allow_eos = true;
  9178. break;
  9179. }
  9180. }
  9181. const llama_token eos = llama_token_eos(&ctx->model);
  9182. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  9183. candidates_decoded.reserve(candidates->size);
  9184. std::vector<llama_grammar_candidate> candidates_grammar;
  9185. candidates_grammar.reserve(candidates->size);
  9186. for (size_t i = 0; i < candidates->size; ++i) {
  9187. const llama_token id = candidates->data[i].id;
  9188. const std::string piece = llama_token_to_piece(ctx, id);
  9189. if (id == eos) {
  9190. if (!allow_eos) {
  9191. candidates->data[i].logit = -INFINITY;
  9192. }
  9193. } else if (piece.empty() || piece[0] == 0) {
  9194. candidates->data[i].logit = -INFINITY;
  9195. } else {
  9196. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  9197. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  9198. }
  9199. }
  9200. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  9201. for (const auto & reject : rejects) {
  9202. candidates->data[reject.index].logit = -INFINITY;
  9203. }
  9204. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9205. }
  9206. static void llama_log_softmax(float * array, size_t size) {
  9207. float max_l = *std::max_element(array, array + size);
  9208. float sum = 0.f;
  9209. for (size_t i = 0; i < size; ++i) {
  9210. float p = expf(array[i] - max_l);
  9211. sum += p;
  9212. array[i] = p;
  9213. }
  9214. for (size_t i = 0; i < size; ++i) {
  9215. array[i] = logf(array[i] / sum);
  9216. }
  9217. }
  9218. void llama_sample_apply_guidance(
  9219. struct llama_context * ctx,
  9220. float * logits,
  9221. float * logits_guidance,
  9222. float scale) {
  9223. GGML_ASSERT(ctx);
  9224. const auto t_start_sample_us = ggml_time_us();
  9225. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  9226. llama_log_softmax(logits, n_vocab);
  9227. llama_log_softmax(logits_guidance, n_vocab);
  9228. for (int i = 0; i < n_vocab; ++i) {
  9229. auto & l = logits[i];
  9230. const auto & g = logits_guidance[i];
  9231. l = scale * (l - g) + g;
  9232. }
  9233. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9234. }
  9235. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  9236. GGML_ASSERT(ctx);
  9237. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  9238. int64_t t_start_sample_us;
  9239. t_start_sample_us = ggml_time_us();
  9240. llama_sample_softmax(nullptr, candidates);
  9241. // Estimate s_hat using the most probable m tokens
  9242. float s_hat = 0.0;
  9243. float sum_ti_bi = 0.0;
  9244. float sum_ti_sq = 0.0;
  9245. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  9246. float t_i = logf(float(i + 2) / float(i + 1));
  9247. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  9248. sum_ti_bi += t_i * b_i;
  9249. sum_ti_sq += t_i * t_i;
  9250. }
  9251. s_hat = sum_ti_bi / sum_ti_sq;
  9252. // Compute k from the estimated s_hat and target surprise value
  9253. float epsilon_hat = s_hat - 1;
  9254. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  9255. // Sample the next word X using top-k sampling
  9256. llama_sample_top_k(nullptr, candidates, int(k), 1);
  9257. if (ctx) {
  9258. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9259. }
  9260. llama_token X = llama_sample_token(ctx, candidates);
  9261. t_start_sample_us = ggml_time_us();
  9262. // Compute error as the difference between observed surprise and target surprise value
  9263. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  9264. return candidate.id == X;
  9265. }));
  9266. float observed_surprise = -log2f(candidates->data[X_idx].p);
  9267. float e = observed_surprise - tau;
  9268. // Update mu using the learning rate and error
  9269. *mu = *mu - eta * e;
  9270. if (ctx) {
  9271. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9272. }
  9273. return X;
  9274. }
  9275. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  9276. int64_t t_start_sample_us;
  9277. t_start_sample_us = ggml_time_us();
  9278. llama_sample_softmax(ctx, candidates);
  9279. // Truncate the words with surprise values greater than mu
  9280. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  9281. return -log2f(candidate.p) > *mu;
  9282. }));
  9283. if (candidates->size == 0) {
  9284. candidates->size = 1;
  9285. }
  9286. if (ctx) {
  9287. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9288. }
  9289. // Normalize the probabilities of the remaining words
  9290. llama_sample_softmax(ctx, candidates);
  9291. // Sample the next word X from the remaining words
  9292. llama_token X = llama_sample_token(ctx, candidates);
  9293. t_start_sample_us = ggml_time_us();
  9294. // Compute error as the difference between observed surprise and target surprise value
  9295. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  9296. return candidate.id == X;
  9297. }));
  9298. float observed_surprise = -log2f(candidates->data[X_idx].p);
  9299. float e = observed_surprise - tau;
  9300. // Update mu using the learning rate and error
  9301. *mu = *mu - eta * e;
  9302. if (ctx) {
  9303. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9304. }
  9305. return X;
  9306. }
  9307. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  9308. const int64_t t_start_sample_us = ggml_time_us();
  9309. // Find max element
  9310. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  9311. return a.logit < b.logit;
  9312. });
  9313. llama_token result = max_iter->id;
  9314. if (ctx) {
  9315. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9316. ctx->n_sample++;
  9317. }
  9318. return result;
  9319. }
  9320. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  9321. GGML_ASSERT(ctx);
  9322. const int64_t t_start_sample_us = ggml_time_us();
  9323. llama_sample_softmax(nullptr, candidates);
  9324. std::vector<float> probs;
  9325. probs.reserve(candidates->size);
  9326. for (size_t i = 0; i < candidates->size; ++i) {
  9327. probs.push_back(candidates->data[i].p);
  9328. }
  9329. std::discrete_distribution<> dist(probs.begin(), probs.end());
  9330. auto & rng = ctx->rng;
  9331. int idx = dist(rng);
  9332. llama_token result = candidates->data[idx].id;
  9333. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9334. ctx->n_sample++;
  9335. return result;
  9336. }
  9337. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  9338. const int64_t t_start_sample_us = ggml_time_us();
  9339. if (token == llama_token_eos(&ctx->model)) {
  9340. for (const auto & stack : grammar->stacks) {
  9341. if (stack.empty()) {
  9342. return;
  9343. }
  9344. }
  9345. GGML_ASSERT(false);
  9346. }
  9347. const std::string piece = llama_token_to_piece(ctx, token);
  9348. // Note terminating 0 in decoded string
  9349. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  9350. const auto & code_points = decoded.first;
  9351. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  9352. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  9353. }
  9354. grammar->partial_utf8 = decoded.second;
  9355. GGML_ASSERT(!grammar->stacks.empty());
  9356. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9357. }
  9358. //
  9359. // Beam search
  9360. //
  9361. struct llama_beam {
  9362. std::vector<llama_token> tokens;
  9363. float p; // Cumulative beam probability (renormalized relative to all beams)
  9364. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  9365. // Sort beams by probability. In case of ties, prefer beams at eob.
  9366. bool operator<(const llama_beam & rhs) const {
  9367. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  9368. }
  9369. // Shift off first n tokens and discard them.
  9370. void shift_tokens(const size_t n) {
  9371. if (n) {
  9372. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  9373. tokens.resize(tokens.size() - n);
  9374. }
  9375. }
  9376. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  9377. };
  9378. // A struct for calculating logit-related info.
  9379. struct llama_logit_info {
  9380. const float * const logits;
  9381. const int n_vocab;
  9382. const float max_l;
  9383. const float normalizer;
  9384. struct sum_exp {
  9385. float max_l;
  9386. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  9387. };
  9388. llama_logit_info(llama_context * ctx)
  9389. : logits(llama_get_logits(ctx))
  9390. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  9391. , max_l(*std::max_element(logits, logits + n_vocab))
  9392. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  9393. { }
  9394. llama_token_data get_token_data(const llama_token token_id) const {
  9395. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  9396. return {token_id, logits[token_id], p};
  9397. }
  9398. // Return top k token_data by logit.
  9399. std::vector<llama_token_data> top_k(size_t k) {
  9400. std::vector<llama_token_data> min_heap; // min-heap by logit
  9401. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  9402. min_heap.reserve(k_min);
  9403. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  9404. min_heap.push_back(get_token_data(token_id));
  9405. }
  9406. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  9407. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  9408. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  9409. if (min_heap.front().logit < logits[token_id]) {
  9410. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  9411. min_heap.back().id = token_id;
  9412. min_heap.back().logit = logits[token_id];
  9413. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  9414. }
  9415. }
  9416. return min_heap;
  9417. }
  9418. float probability_from_logit(float logit) const {
  9419. return normalizer * std::exp(logit - max_l);
  9420. }
  9421. };
  9422. struct llama_beam_search_data {
  9423. llama_context * ctx;
  9424. size_t n_beams;
  9425. int n_past;
  9426. int n_predict;
  9427. std::vector<llama_beam> beams;
  9428. std::vector<llama_beam> next_beams;
  9429. // Re-calculated on each loop iteration
  9430. size_t common_prefix_length;
  9431. // Used to communicate to/from callback on beams state.
  9432. std::vector<llama_beam_view> beam_views;
  9433. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  9434. : ctx(ctx)
  9435. , n_beams(n_beams)
  9436. , n_past(n_past)
  9437. , n_predict(n_predict)
  9438. , beam_views(n_beams) {
  9439. beams.reserve(n_beams);
  9440. next_beams.reserve(n_beams);
  9441. }
  9442. // Collapse beams to a single beam given by index.
  9443. void collapse_beams(const size_t beam_idx) {
  9444. if (0u < beam_idx) {
  9445. std::swap(beams[0], beams[beam_idx]);
  9446. }
  9447. beams.resize(1);
  9448. }
  9449. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  9450. // The repetitive patterns below reflect the 2 stages of heaps:
  9451. // * Gather elements until the vector is full, then call std::make_heap() on it.
  9452. // * If the heap is full and a new element is found that should be included, pop the
  9453. // least element to the back(), replace it with the new, then push it into the heap.
  9454. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  9455. // Min-heaps use a greater-than comparator.
  9456. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  9457. if (beam.eob) {
  9458. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  9459. if (next_beams.size() < n_beams) {
  9460. next_beams.push_back(std::move(beam));
  9461. if (next_beams.size() == n_beams) {
  9462. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  9463. }
  9464. } else if (next_beams.front().p < beam.p) {
  9465. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  9466. next_beams.back() = std::move(beam);
  9467. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  9468. }
  9469. } else {
  9470. // beam is not at end-of-sentence, so branch with next top_k tokens.
  9471. if (!beam.tokens.empty()) {
  9472. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  9473. }
  9474. llama_logit_info logit_info(ctx);
  9475. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  9476. size_t i=0;
  9477. if (next_beams.size() < n_beams) {
  9478. for (; next_beams.size() < n_beams ; ++i) {
  9479. llama_beam next_beam = beam;
  9480. next_beam.tokens.push_back(next_tokens[i].id);
  9481. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  9482. next_beams.push_back(std::move(next_beam));
  9483. }
  9484. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  9485. } else {
  9486. for (; next_beams.front().p == 0.0f ; ++i) {
  9487. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  9488. next_beams.back() = beam;
  9489. next_beams.back().tokens.push_back(next_tokens[i].id);
  9490. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  9491. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  9492. }
  9493. }
  9494. for (; i < n_beams ; ++i) {
  9495. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  9496. if (next_beams.front().p < next_p) {
  9497. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  9498. next_beams.back() = beam;
  9499. next_beams.back().tokens.push_back(next_tokens[i].id);
  9500. next_beams.back().p = next_p;
  9501. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  9502. }
  9503. }
  9504. }
  9505. }
  9506. // Find common_prefix_length based on beams.
  9507. // Requires beams is not empty.
  9508. size_t find_common_prefix_length() {
  9509. size_t common_prefix_length = beams[0].tokens.size();
  9510. for (size_t i = 1 ; i < beams.size() ; ++i) {
  9511. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  9512. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  9513. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  9514. common_prefix_length = j;
  9515. break;
  9516. }
  9517. }
  9518. }
  9519. return common_prefix_length;
  9520. }
  9521. // Construct beams_state to send back to caller via the callback function.
  9522. // Side effect: set common_prefix_length = find_common_prefix_length();
  9523. llama_beams_state get_beams_state(const bool last_call) {
  9524. for (size_t i = 0 ; i < beams.size() ; ++i) {
  9525. beam_views[i] = beams[i].view();
  9526. }
  9527. common_prefix_length = find_common_prefix_length();
  9528. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  9529. }
  9530. // Loop:
  9531. // * while i < n_predict, AND
  9532. // * any of the beams have not yet reached end-of-beam (eob), AND
  9533. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  9534. // (since all other beam probabilities can only decrease)
  9535. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  9536. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  9537. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  9538. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  9539. !beams[top_beam_index()].eob ; ++i) {
  9540. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  9541. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  9542. if (common_prefix_length) {
  9543. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  9544. n_past += common_prefix_length;
  9545. }
  9546. // Zero-out next_beam probabilities to place them last in following min-heap.
  9547. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  9548. for (llama_beam & beam : beams) {
  9549. beam.shift_tokens(common_prefix_length);
  9550. fill_next_beams_by_top_probabilities(beam);
  9551. }
  9552. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  9553. beams.swap(next_beams);
  9554. renormalize_beam_probabilities(beams);
  9555. }
  9556. collapse_beams(top_beam_index());
  9557. callback(callback_data, get_beams_state(true));
  9558. }
  9559. // As beams grow, the cumulative probabilities decrease.
  9560. // Renormalize them to avoid floating point underflow.
  9561. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  9562. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  9563. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  9564. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  9565. }
  9566. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  9567. size_t top_beam_index() {
  9568. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  9569. }
  9570. // Copy (p,eob) for each beam which may have been changed by the callback.
  9571. void update_beams_from_beam_views() {
  9572. for (size_t i = 0 ; i < beams.size() ; ++i) {
  9573. beams[i].p = beam_views[i].p;
  9574. beams[i].eob = beam_views[i].eob;
  9575. }
  9576. }
  9577. };
  9578. void llama_beam_search(llama_context * ctx,
  9579. llama_beam_search_callback_fn_t callback, void * callback_data,
  9580. size_t n_beams, int n_past, int n_predict) {
  9581. assert(ctx);
  9582. const int64_t t_start_sample_us = ggml_time_us();
  9583. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  9584. beam_search_data.loop(callback, callback_data);
  9585. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9586. ctx->n_sample++;
  9587. }
  9588. //
  9589. // quantization
  9590. //
  9591. struct quantize_state_internal {
  9592. const llama_model & model;
  9593. const llama_model_quantize_params * params;
  9594. int n_attention_wv = 0;
  9595. int n_ffn_down = 0;
  9596. int n_ffn_gate = 0;
  9597. int n_ffn_up = 0;
  9598. int i_attention_wv = 0;
  9599. int i_ffn_down = 0;
  9600. int i_ffn_gate = 0;
  9601. int i_ffn_up = 0;
  9602. int n_k_quantized = 0;
  9603. int n_fallback = 0;
  9604. bool has_imatrix = false;
  9605. // used to figure out if a model shares tok_embd with the output weight
  9606. bool has_output = false;
  9607. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  9608. : model(model)
  9609. , params(params)
  9610. {}
  9611. };
  9612. static void llama_tensor_dequantize_internal(
  9613. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  9614. const size_t nelements, const int nthread
  9615. ) {
  9616. if (output.size() < nelements) {
  9617. output.resize(nelements);
  9618. }
  9619. float * f32_output = (float *) output.data();
  9620. ggml_type_traits_t qtype;
  9621. if (ggml_is_quantized(tensor->type)) {
  9622. qtype = ggml_internal_get_type_traits(tensor->type);
  9623. if (qtype.to_float == NULL) {
  9624. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  9625. }
  9626. } else if (tensor->type != GGML_TYPE_F16) {
  9627. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  9628. }
  9629. if (nthread < 2) {
  9630. if (tensor->type == GGML_TYPE_F16) {
  9631. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  9632. } else if (ggml_is_quantized(tensor->type)) {
  9633. qtype.to_float(tensor->data, f32_output, nelements);
  9634. } else {
  9635. GGML_ASSERT(false); // unreachable
  9636. }
  9637. return;
  9638. }
  9639. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  9640. size_t block_size_bytes = ggml_type_size(tensor->type);
  9641. GGML_ASSERT(nelements % block_size == 0);
  9642. size_t nblocks = nelements / block_size;
  9643. size_t blocks_per_thread = nblocks / nthread;
  9644. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  9645. size_t in_buff_offs = 0;
  9646. size_t out_buff_offs = 0;
  9647. for (int tnum = 0; tnum < nthread; tnum++) {
  9648. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  9649. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  9650. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  9651. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  9652. if (typ == GGML_TYPE_F16) {
  9653. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  9654. } else {
  9655. qtype.to_float(inbuf, outbuf, nels);
  9656. }
  9657. };
  9658. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  9659. in_buff_offs += thr_block_bytes;
  9660. out_buff_offs += thr_elems;
  9661. }
  9662. for (auto & w : workers) { w.join(); }
  9663. workers.clear();
  9664. }
  9665. static ggml_type llama_tensor_get_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  9666. const std::string name = ggml_get_name(tensor);
  9667. // TODO: avoid hardcoded tensor names - use the TN_* constants
  9668. const llm_arch arch = qs.model.arch;
  9669. const auto tn = LLM_TN(arch);
  9670. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  9671. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  9672. };
  9673. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  9674. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  9675. if (n_expert > 1) {
  9676. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  9677. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  9678. // for getting the current layer as I initially thought, and we need to resort to parsing the
  9679. // tensor name.
  9680. n_layer /= n_expert;
  9681. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  9682. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  9683. }
  9684. if (i_layer < 0 || i_layer >= n_layer) {
  9685. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  9686. }
  9687. }
  9688. return std::make_pair(i_layer, n_layer);
  9689. };
  9690. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  9691. // with the quantization of the output tensor
  9692. if (name == tn(LLM_TENSOR_OUTPUT, "weight") || (!qs.has_output && name == tn(LLM_TENSOR_TOKEN_EMBD, "weight"))) {
  9693. int nx = tensor->ne[0];
  9694. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  9695. new_type = GGML_TYPE_Q8_0;
  9696. }
  9697. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  9698. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  9699. new_type = GGML_TYPE_Q5_K;
  9700. }
  9701. else if (new_type != GGML_TYPE_Q8_0) {
  9702. new_type = GGML_TYPE_Q6_K;
  9703. }
  9704. } else if (name == "token_embd.weight") {
  9705. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
  9706. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) {
  9707. new_type = GGML_TYPE_Q2_K;
  9708. }
  9709. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  9710. new_type = GGML_TYPE_IQ3_S;
  9711. }
  9712. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  9713. new_type = GGML_TYPE_IQ3_S;
  9714. }
  9715. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  9716. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  9717. if (name.find("attn_v.weight") != std::string::npos) {
  9718. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  9719. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  9720. ++qs.i_attention_wv;
  9721. }
  9722. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  9723. new_type = GGML_TYPE_Q4_K;
  9724. }
  9725. else if (name.find("ffn_down") != std::string::npos) {
  9726. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  9727. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  9728. }
  9729. ++qs.i_ffn_down;
  9730. }
  9731. else if (name.find("attn_output.weight") != std::string::npos) {
  9732. if (qs.model.hparams.n_expert == 8) {
  9733. new_type = GGML_TYPE_Q5_K;
  9734. } else {
  9735. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) new_type = GGML_TYPE_IQ2_XXS;
  9736. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  9737. }
  9738. }
  9739. } else if (name.find("attn_v.weight") != std::string::npos) {
  9740. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  9741. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  9742. }
  9743. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  9744. new_type = GGML_TYPE_Q4_K;
  9745. }
  9746. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  9747. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  9748. }
  9749. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_S && qs.model.hparams.n_gqa() >= 4) {
  9750. new_type = GGML_TYPE_Q4_K;
  9751. }
  9752. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  9753. new_type = GGML_TYPE_Q4_K;
  9754. }
  9755. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_S && qs.model.hparams.n_gqa() >= 4) {
  9756. new_type = GGML_TYPE_Q4_K;
  9757. }
  9758. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  9759. new_type = GGML_TYPE_Q4_K;
  9760. }
  9761. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  9762. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  9763. }
  9764. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  9765. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  9766. new_type = GGML_TYPE_Q5_K;
  9767. }
  9768. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  9769. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  9770. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  9771. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  9772. (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;
  9773. if (qs.model.type == MODEL_70B) {
  9774. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  9775. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  9776. // nearly negligible increase in model size by quantizing this tensor with more bits:
  9777. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  9778. }
  9779. if (qs.model.hparams.n_expert == 8) {
  9780. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  9781. // TODO: explore better strategies
  9782. new_type = GGML_TYPE_Q8_0;
  9783. }
  9784. ++qs.i_attention_wv;
  9785. } else if (name.find("attn_k.weight") != std::string::npos) {
  9786. if (qs.model.hparams.n_expert == 8) {
  9787. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  9788. // TODO: explore better strategies
  9789. new_type = GGML_TYPE_Q8_0;
  9790. }
  9791. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  9792. new_type = GGML_TYPE_IQ3_XXS;
  9793. }
  9794. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  9795. new_type = GGML_TYPE_IQ2_S;
  9796. }
  9797. } else if (name.find("attn_q.weight") != std::string::npos) {
  9798. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  9799. new_type = GGML_TYPE_IQ3_XXS;
  9800. }
  9801. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  9802. new_type = GGML_TYPE_IQ2_S;
  9803. }
  9804. } else if (name.find("ffn_down") != std::string::npos) {
  9805. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  9806. int i_layer = info.first, n_layer = info.second;
  9807. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  9808. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  9809. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  9810. }
  9811. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  9812. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  9813. }
  9814. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  9815. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  9816. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  9817. : GGML_TYPE_Q3_K;
  9818. }
  9819. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  9820. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  9821. new_type = GGML_TYPE_Q4_K;
  9822. }
  9823. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  9824. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  9825. }
  9826. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  9827. if (arch == LLM_ARCH_FALCON) {
  9828. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  9829. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  9830. } else {
  9831. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  9832. }
  9833. }
  9834. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  9835. new_type = GGML_TYPE_Q5_K;
  9836. }
  9837. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  9838. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  9839. new_type = GGML_TYPE_Q5_K;
  9840. }
  9841. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  9842. && qs.has_imatrix && i_layer < n_layer/8) {
  9843. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  9844. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  9845. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  9846. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  9847. }
  9848. ++qs.i_ffn_down;
  9849. } else if (name.find("attn_output.weight") != std::string::npos) {
  9850. if (arch != LLM_ARCH_FALCON) {
  9851. if (qs.model.hparams.n_expert == 8) {
  9852. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  9853. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  9854. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  9855. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  9856. new_type = GGML_TYPE_Q5_K;
  9857. }
  9858. } else {
  9859. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  9860. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  9861. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  9862. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  9863. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  9864. }
  9865. } else {
  9866. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  9867. }
  9868. }
  9869. else if (name.find("attn_qkv.weight") != std::string::npos) {
  9870. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  9871. new_type = GGML_TYPE_Q4_K;
  9872. }
  9873. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  9874. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  9875. }
  9876. else if (name.find("ffn_gate") != std::string::npos) {
  9877. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  9878. int i_layer = info.first, n_layer = info.second;
  9879. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  9880. new_type = GGML_TYPE_IQ3_XXS;
  9881. }
  9882. ++qs.i_ffn_gate;
  9883. }
  9884. else if (name.find("ffn_up") != std::string::npos) {
  9885. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  9886. int i_layer = info.first, n_layer = info.second;
  9887. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  9888. new_type = GGML_TYPE_IQ3_XXS;
  9889. }
  9890. ++qs.i_ffn_up;
  9891. }
  9892. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  9893. //}
  9894. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  9895. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  9896. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  9897. //}
  9898. // This can be used to reduce the size of the Q5_K_S model.
  9899. // The associated PPL increase is fully in line with the size reduction
  9900. //else {
  9901. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  9902. //}
  9903. bool convert_incompatible_tensor = false;
  9904. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  9905. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  9906. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  9907. new_type == GGML_TYPE_IQ3_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || new_type == GGML_TYPE_IQ3_S) {
  9908. int nx = tensor->ne[0];
  9909. int ny = tensor->ne[1];
  9910. if (nx % QK_K != 0) {
  9911. 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));
  9912. convert_incompatible_tensor = true;
  9913. } else {
  9914. ++qs.n_k_quantized;
  9915. }
  9916. }
  9917. if (convert_incompatible_tensor) {
  9918. switch (new_type) {
  9919. case GGML_TYPE_IQ2_XXS:
  9920. case GGML_TYPE_IQ2_XS:
  9921. case GGML_TYPE_IQ2_S:
  9922. case GGML_TYPE_IQ3_XXS:
  9923. case GGML_TYPE_IQ3_S:
  9924. case GGML_TYPE_IQ1_S:
  9925. case GGML_TYPE_Q2_K:
  9926. case GGML_TYPE_Q3_K:
  9927. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  9928. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  9929. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  9930. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  9931. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  9932. }
  9933. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  9934. ++qs.n_fallback;
  9935. }
  9936. return new_type;
  9937. }
  9938. static int32_t llama_tensor_quantize_internal(enum ggml_type new_type, const float * f32_data, void * new_data, const int chunk_size, int nrows, int n_per_row, const float * imatrix, std::vector<std::thread> & workers, const int nthread) {
  9939. std::mutex mutex;
  9940. int counter = 0;
  9941. size_t new_size = 0;
  9942. if (nthread < 2) {
  9943. // single-thread
  9944. return ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, imatrix);
  9945. }
  9946. auto compute = [&mutex, &counter, &new_size, new_type, f32_data, new_data, chunk_size,
  9947. nrows, n_per_row, imatrix]() {
  9948. const int nrows_per_chunk = chunk_size / n_per_row;
  9949. size_t local_size = 0;
  9950. while (true) {
  9951. std::unique_lock<std::mutex> lock(mutex);
  9952. int first_row = counter; counter += nrows_per_chunk;
  9953. if (first_row >= nrows) {
  9954. if (local_size > 0) {
  9955. new_size += local_size;
  9956. }
  9957. break;
  9958. }
  9959. lock.unlock();
  9960. const int this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  9961. local_size += ggml_quantize_chunk(new_type, f32_data, new_data, first_row * n_per_row, this_nrow, n_per_row, imatrix);
  9962. }
  9963. };
  9964. for (int it = 0; it < nthread - 1; ++it) {
  9965. workers.emplace_back(compute);
  9966. }
  9967. compute();
  9968. for (auto & w : workers) { w.join(); }
  9969. workers.clear();
  9970. return new_size;
  9971. }
  9972. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  9973. ggml_type default_type;
  9974. llama_ftype ftype = params->ftype;
  9975. switch (params->ftype) {
  9976. case LLAMA_FTYPE_MOSTLY_Q4_0: default_type = GGML_TYPE_Q4_0; break;
  9977. case LLAMA_FTYPE_MOSTLY_Q4_1: default_type = GGML_TYPE_Q4_1; break;
  9978. case LLAMA_FTYPE_MOSTLY_Q5_0: default_type = GGML_TYPE_Q5_0; break;
  9979. case LLAMA_FTYPE_MOSTLY_Q5_1: default_type = GGML_TYPE_Q5_1; break;
  9980. case LLAMA_FTYPE_MOSTLY_Q8_0: default_type = GGML_TYPE_Q8_0; break;
  9981. case LLAMA_FTYPE_MOSTLY_F16: default_type = GGML_TYPE_F16; break;
  9982. case LLAMA_FTYPE_ALL_F32: default_type = GGML_TYPE_F32; break;
  9983. // K-quants
  9984. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  9985. case LLAMA_FTYPE_MOSTLY_Q2_K: default_type = GGML_TYPE_Q2_K; break;
  9986. case LLAMA_FTYPE_MOSTLY_IQ3_XS: default_type = GGML_TYPE_IQ3_S; break;
  9987. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  9988. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  9989. case LLAMA_FTYPE_MOSTLY_Q3_K_L: default_type = GGML_TYPE_Q3_K; break;
  9990. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  9991. case LLAMA_FTYPE_MOSTLY_Q4_K_M: default_type = GGML_TYPE_Q4_K; break;
  9992. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  9993. case LLAMA_FTYPE_MOSTLY_Q5_K_M: default_type = GGML_TYPE_Q5_K; break;
  9994. case LLAMA_FTYPE_MOSTLY_Q6_K: default_type = GGML_TYPE_Q6_K; break;
  9995. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: default_type = GGML_TYPE_IQ2_XXS; break;
  9996. case LLAMA_FTYPE_MOSTLY_IQ2_XS: default_type = GGML_TYPE_IQ2_XS; break;
  9997. case LLAMA_FTYPE_MOSTLY_IQ2_S: default_type = GGML_TYPE_IQ2_XS; break;
  9998. case LLAMA_FTYPE_MOSTLY_IQ2_M: default_type = GGML_TYPE_IQ2_S; break;
  9999. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: default_type = GGML_TYPE_IQ3_XXS; break;
  10000. case LLAMA_FTYPE_MOSTLY_IQ1_S: default_type = GGML_TYPE_IQ1_S; break;
  10001. case LLAMA_FTYPE_MOSTLY_IQ4_NL: default_type = GGML_TYPE_IQ4_NL; break;
  10002. case LLAMA_FTYPE_MOSTLY_IQ4_XS: default_type = GGML_TYPE_IQ4_XS; break;
  10003. case LLAMA_FTYPE_MOSTLY_IQ3_S: default_type = GGML_TYPE_IQ3_S; break;
  10004. case LLAMA_FTYPE_MOSTLY_IQ3_M: default_type = GGML_TYPE_IQ3_S; break;
  10005. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  10006. }
  10007. int nthread = params->nthread;
  10008. if (nthread <= 0) {
  10009. nthread = std::thread::hardware_concurrency();
  10010. }
  10011. // mmap consistently increases speed Linux, and also increases speed on Windows with
  10012. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  10013. #if defined(__linux__) || defined(_WIN32)
  10014. constexpr bool use_mmap = true;
  10015. #else
  10016. constexpr bool use_mmap = false;
  10017. #endif
  10018. llama_model_loader ml(fname_inp, use_mmap, NULL);
  10019. ml.init_mapping(false); // no prefetching?
  10020. llama_model model;
  10021. llm_load_arch(ml, model);
  10022. llm_load_hparams(ml, model);
  10023. struct quantize_state_internal qs(model, params);
  10024. if (params->only_copy) {
  10025. ftype = model.ftype;
  10026. }
  10027. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  10028. if (params->imatrix) {
  10029. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  10030. if (imatrix_data) {
  10031. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  10032. qs.has_imatrix = true;
  10033. }
  10034. }
  10035. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  10036. struct gguf_context * ctx_out = gguf_init_empty();
  10037. // copy the KV pairs from the input file
  10038. gguf_set_kv (ctx_out, ml.ctx_gguf);
  10039. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  10040. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  10041. for (int i = 0; i < ml.n_tensors; ++i) {
  10042. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  10043. const std::string name = ggml_get_name(meta);
  10044. // TODO: avoid hardcoded tensor names - use the TN_* constants
  10045. if (name.find("attn_v.weight") != std::string::npos || name.find("attn_qkv.weight") != std::string::npos) {
  10046. ++qs.n_attention_wv;
  10047. }
  10048. else if (name.find("ffn_down") != std::string::npos) {
  10049. ++qs.n_ffn_down;
  10050. }
  10051. else if (name.find("ffn_gate") != std::string::npos) {
  10052. ++qs.n_ffn_gate;
  10053. }
  10054. else if (name.find("ffn_up") != std::string::npos) {
  10055. ++qs.n_ffn_up;
  10056. }
  10057. else if (name == LLM_TN(model.arch)(LLM_TENSOR_OUTPUT, "weight")) {
  10058. qs.has_output = true;
  10059. }
  10060. }
  10061. if (qs.n_attention_wv != qs.n_ffn_down || (uint32_t)qs.n_attention_wv != model.hparams.n_layer) {
  10062. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_ffn_down = %d, hparams.n_layer = %d\n",
  10063. __func__, qs.n_attention_wv, qs.n_ffn_down, model.hparams.n_layer);
  10064. }
  10065. size_t total_size_org = 0;
  10066. size_t total_size_new = 0;
  10067. std::vector<std::thread> workers;
  10068. workers.reserve(nthread);
  10069. int idx = 0;
  10070. std::vector<no_init<uint8_t>> read_data;
  10071. std::vector<no_init<uint8_t>> work;
  10072. std::vector<no_init<float>> f32_conv_buf;
  10073. // populate the original tensors so we get an initial meta data
  10074. for (int i = 0; i < ml.n_tensors; ++i) {
  10075. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  10076. gguf_add_tensor(ctx_out, meta);
  10077. }
  10078. std::ofstream fout(fname_out, std::ios::binary);
  10079. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  10080. const size_t meta_size = gguf_get_meta_size(ctx_out);
  10081. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  10082. // placeholder for the meta data
  10083. ::zeros(fout, meta_size);
  10084. for (int i = 0; i < ml.n_tensors; ++i) {
  10085. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  10086. const std::string name = ggml_get_name(tensor);
  10087. if (!ml.use_mmap) {
  10088. if (read_data.size() < ggml_nbytes(tensor)) {
  10089. read_data.resize(ggml_nbytes(tensor));
  10090. }
  10091. tensor->data = read_data.data();
  10092. }
  10093. ml.load_data_for(tensor);
  10094. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  10095. ++idx, ml.n_tensors,
  10096. ggml_get_name(tensor),
  10097. llama_format_tensor_shape(tensor).c_str(),
  10098. ggml_type_name(tensor->type));
  10099. // This used to be a regex, but <regex> has an extreme cost to compile times.
  10100. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  10101. // quantize only 2D tensors
  10102. quantize &= (ggml_n_dims(tensor) == 2);
  10103. quantize &= params->quantize_output_tensor || name != "output.weight";
  10104. quantize &= !params->only_copy;
  10105. // do not quantize expert gating tensors
  10106. // NOTE: can't use LLM_TN here because the layer number is not known
  10107. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  10108. // do not quantize positional embeddings and token types (BERT)
  10109. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  10110. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  10111. // do not quantize Mamba's small yet 2D weights
  10112. // NOTE: can't use LLM_TN here because the layer number is not known
  10113. quantize &= name.find("ssm_conv1d.weight") == std::string::npos;
  10114. quantize &= name.find("ssm_x.weight") == std::string::npos;
  10115. quantize &= name.find("ssm_dt.weight") == std::string::npos;
  10116. enum ggml_type new_type;
  10117. void * new_data;
  10118. size_t new_size;
  10119. if (quantize) {
  10120. new_type = default_type;
  10121. // get more optimal quantization type based on the tensor shape, layer, etc.
  10122. if (!params->pure && ggml_is_quantized(default_type)) {
  10123. new_type = llama_tensor_get_type(qs, new_type, tensor, ftype);
  10124. }
  10125. // If we've decided to quantize to the same type the tensor is already
  10126. // in then there's nothing to do.
  10127. quantize = tensor->type != new_type;
  10128. }
  10129. if (!quantize) {
  10130. new_type = tensor->type;
  10131. new_data = tensor->data;
  10132. new_size = ggml_nbytes(tensor);
  10133. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  10134. } else {
  10135. const size_t nelements = ggml_nelements(tensor);
  10136. const float * imatrix = nullptr;
  10137. if (imatrix_data) {
  10138. auto it = imatrix_data->find(tensor->name);
  10139. if (it == imatrix_data->end()) {
  10140. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  10141. } else {
  10142. if (it->second.size() == (size_t)tensor->ne[0]) {
  10143. imatrix = it->second.data();
  10144. } else {
  10145. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  10146. int(it->second.size()), int(tensor->ne[0]), tensor->name);
  10147. }
  10148. }
  10149. }
  10150. if ((new_type == GGML_TYPE_IQ2_XXS ||
  10151. new_type == GGML_TYPE_IQ2_XS ||
  10152. new_type == GGML_TYPE_IQ2_S ||
  10153. new_type == GGML_TYPE_IQ1_S ||
  10154. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  10155. LLAMA_LOG_ERROR("\n\n============================================================\n");
  10156. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  10157. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  10158. LLAMA_LOG_ERROR("============================================================\n\n");
  10159. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  10160. }
  10161. float * f32_data;
  10162. if (tensor->type == GGML_TYPE_F32) {
  10163. f32_data = (float *) tensor->data;
  10164. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  10165. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  10166. } else {
  10167. llama_tensor_dequantize_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  10168. f32_data = (float *) f32_conv_buf.data();
  10169. }
  10170. LLAMA_LOG_INFO("converting to %s .. ", ggml_type_name(new_type));
  10171. fflush(stdout);
  10172. if (work.size() < nelements * 4) {
  10173. work.resize(nelements * 4); // upper bound on size
  10174. }
  10175. new_data = work.data();
  10176. const int n_per_row = tensor->ne[0];
  10177. const int nrows = nelements / n_per_row;
  10178. static const int min_chunk_size = 32 * 512;
  10179. const int chunk_size = n_per_row >= min_chunk_size ? n_per_row : n_per_row * ((min_chunk_size + n_per_row - 1)/n_per_row);
  10180. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  10181. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  10182. new_size = llama_tensor_quantize_internal(new_type, f32_data, new_data, chunk_size, nrows, n_per_row, imatrix, workers, nthread_use);
  10183. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB\n", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  10184. }
  10185. total_size_org += ggml_nbytes(tensor);
  10186. total_size_new += new_size;
  10187. // update the gguf meta data as we go
  10188. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  10189. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  10190. // write tensor data + padding
  10191. fout.write((const char *) new_data, new_size);
  10192. zeros(fout, GGML_PAD(new_size, align) - new_size);
  10193. }
  10194. // go back to beginning of file and write the updated meta data
  10195. {
  10196. fout.seekp(0);
  10197. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  10198. gguf_get_meta_data(ctx_out, data.data());
  10199. fout.write((const char *) data.data(), data.size());
  10200. }
  10201. fout.close();
  10202. gguf_free(ctx_out);
  10203. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  10204. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  10205. if (qs.n_fallback > 0) {
  10206. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n",
  10207. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  10208. }
  10209. }
  10210. static int llama_apply_lora_from_file_internal(
  10211. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  10212. ) {
  10213. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  10214. const int64_t t_start_lora_us = ggml_time_us();
  10215. llama_file fin(path_lora, "rb");
  10216. // verify magic and version
  10217. {
  10218. uint32_t magic = fin.read_u32();
  10219. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  10220. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  10221. return 1;
  10222. }
  10223. uint32_t format_version = fin.read_u32();
  10224. if (format_version != 1) {
  10225. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  10226. return 1;
  10227. }
  10228. }
  10229. int32_t lora_r = fin.read_u32();
  10230. int32_t lora_alpha = fin.read_u32();
  10231. float scaling = scale * (float)lora_alpha / (float)lora_r;
  10232. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  10233. // load base model
  10234. std::unique_ptr<llama_model_loader> ml;
  10235. if (path_base_model) {
  10236. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  10237. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  10238. ml->init_mapping(/*prefetch*/ false); // no prefetching
  10239. }
  10240. struct tensor_meta {
  10241. std::string name;
  10242. ggml_type type;
  10243. int32_t ne[2];
  10244. size_t offset;
  10245. };
  10246. std::map<std::string, tensor_meta> tensor_meta_map;
  10247. // load all tensor meta
  10248. while (true) {
  10249. if (fin.tell() == fin.size) {
  10250. // eof
  10251. break;
  10252. }
  10253. int32_t n_dims;
  10254. int32_t name_len;
  10255. int32_t ftype;
  10256. fin.read_raw(&n_dims, sizeof(n_dims));
  10257. fin.read_raw(&name_len, sizeof(name_len));
  10258. fin.read_raw(&ftype, sizeof(ftype));
  10259. if (n_dims != 1 && n_dims != 2) {
  10260. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  10261. return 1;
  10262. }
  10263. int32_t ne[2] = { 1, 1 };
  10264. for (int i = 0; i < n_dims; ++i) {
  10265. fin.read_raw(&ne[i], sizeof(ne[i]));
  10266. }
  10267. std::string name;
  10268. {
  10269. GGML_ASSERT(name_len < GGML_MAX_NAME);
  10270. char buf[GGML_MAX_NAME];
  10271. fin.read_raw(buf, name_len);
  10272. name = std::string(buf, name_len);
  10273. }
  10274. // check for lora suffix
  10275. std::string lora_suffix;
  10276. if (name.length() > 6) {
  10277. lora_suffix = name.substr(name.length() - 6);
  10278. }
  10279. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  10280. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  10281. return 1;
  10282. }
  10283. // tensor type
  10284. ggml_type wtype;
  10285. switch (ftype) {
  10286. case 0: wtype = GGML_TYPE_F32; break;
  10287. case 1: wtype = GGML_TYPE_F16; break;
  10288. default:
  10289. {
  10290. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  10291. __func__, ftype);
  10292. return 1;
  10293. }
  10294. }
  10295. // data offset
  10296. size_t offset = fin.tell();
  10297. offset = (offset + 31) & -32;
  10298. // skip tensor data
  10299. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  10300. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  10301. }
  10302. bool warned = false;
  10303. int n_tensors = 0;
  10304. // apply
  10305. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  10306. if (backend_cpu == nullptr) {
  10307. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  10308. return 1;
  10309. }
  10310. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  10311. std::vector<no_init<uint8_t>> read_buf;
  10312. for (const auto & it : model.tensors_by_name) {
  10313. const std::string & base_name = it.first;
  10314. ggml_tensor * model_t = it.second;
  10315. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  10316. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  10317. continue;
  10318. }
  10319. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  10320. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  10321. ggml_init_params lora_init_params = {
  10322. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  10323. /* .mem_buffer */ nullptr,
  10324. /* .no_alloc */ true,
  10325. };
  10326. ggml_context * lora_ctx = ggml_init(lora_init_params);
  10327. if (lora_ctx == nullptr) {
  10328. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  10329. ggml_backend_free(backend_cpu);
  10330. return 1;
  10331. }
  10332. // create tensors
  10333. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  10334. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  10335. ggml_set_name(loraA, metaA.name.c_str());
  10336. ggml_set_name(loraB, metaB.name.c_str());
  10337. ggml_tensor * base_t;
  10338. if (ml) {
  10339. if (gguf_find_tensor(ml->ctx_gguf, base_name.c_str()) < 0) {
  10340. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  10341. return 1;
  10342. }
  10343. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  10344. } else {
  10345. base_t = ggml_dup_tensor(lora_ctx, model_t);
  10346. }
  10347. ggml_set_name(base_t, base_name.c_str());
  10348. // allocate in backend buffer
  10349. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  10350. if (lora_buf == nullptr) {
  10351. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  10352. return 1;
  10353. }
  10354. // load tensor data
  10355. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  10356. read_buf.resize(ggml_nbytes(tensor));
  10357. fin.seek(tensor_meta.offset, SEEK_SET);
  10358. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  10359. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  10360. };
  10361. load_tensor(metaA, loraA);
  10362. load_tensor(metaB, loraB);
  10363. // load base model tensor data
  10364. if (ml) {
  10365. ml->load_data_for(base_t);
  10366. } else {
  10367. ggml_backend_tensor_copy(model_t, base_t);
  10368. }
  10369. if (ggml_is_quantized(base_t->type) && !warned) {
  10370. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  10371. "use a f16 or f32 base model with --lora-base\n", __func__);
  10372. warned = true;
  10373. }
  10374. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  10375. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  10376. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  10377. ggml_free(lora_ctx);
  10378. ggml_backend_buffer_free(lora_buf);
  10379. ggml_backend_free(backend_cpu);
  10380. return 1;
  10381. }
  10382. auto build_lora_graph = [&]() {
  10383. // w = w + BA*s
  10384. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  10385. ggml_set_name(BA, "BA");
  10386. if (scaling != 1.0f) {
  10387. BA = ggml_scale(lora_ctx, BA, scaling);
  10388. ggml_set_name(BA, "BA_scaled");
  10389. }
  10390. ggml_tensor * r;
  10391. r = ggml_add_inplace(lora_ctx, base_t, BA);
  10392. ggml_set_name(r, "r_add");
  10393. if (base_t->type != model_t->type) {
  10394. // convert the result to the model type
  10395. r = ggml_cast(lora_ctx, r, model_t->type);
  10396. ggml_set_name(r, "r_cast");
  10397. }
  10398. return r;
  10399. };
  10400. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  10401. ggml_tensor * r = build_lora_graph();
  10402. ggml_build_forward_expand(gf, r);
  10403. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  10404. if (graph_buf == nullptr) {
  10405. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  10406. ggml_free(lora_ctx);
  10407. ggml_backend_buffer_free(lora_buf);
  10408. ggml_backend_free(backend_cpu);
  10409. return 1;
  10410. }
  10411. ggml_backend_graph_compute(backend_cpu, gf);
  10412. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  10413. #if 0
  10414. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  10415. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  10416. // sched compute
  10417. ggml_build_forward_expand(gf, build_graph());
  10418. ggml_backend_sched_init_measure(sched, gf);
  10419. // create the graph again, since the previous one was destroyed by the measure
  10420. ggml_graph_clear(gf);
  10421. ggml_build_forward_expand(gf, build_graph());
  10422. ggml_backend_sched_graph_compute(sched, gf);
  10423. ggml_backend_sched_free(sched);
  10424. #endif
  10425. ggml_backend_buffer_free(lora_buf);
  10426. ggml_backend_buffer_free(graph_buf);
  10427. ggml_free(lora_ctx);
  10428. n_tensors++;
  10429. if (n_tensors % 4 == 0) {
  10430. LLAMA_LOG_INFO(".");
  10431. }
  10432. }
  10433. ggml_backend_free(backend_cpu);
  10434. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  10435. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  10436. return 0;
  10437. }
  10438. //
  10439. // interface implementation
  10440. //
  10441. struct llama_model_params llama_model_default_params() {
  10442. struct llama_model_params result = {
  10443. /*.n_gpu_layers =*/ 0,
  10444. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  10445. /*.main_gpu =*/ 0,
  10446. /*.tensor_split =*/ nullptr,
  10447. /*.progress_callback =*/ nullptr,
  10448. /*.progress_callback_user_data =*/ nullptr,
  10449. /*.kv_overrides =*/ nullptr,
  10450. /*.vocab_only =*/ false,
  10451. /*.use_mmap =*/ true,
  10452. /*.use_mlock =*/ false,
  10453. };
  10454. #ifdef GGML_USE_METAL
  10455. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  10456. result.n_gpu_layers = 999;
  10457. #endif
  10458. return result;
  10459. }
  10460. struct llama_context_params llama_context_default_params() {
  10461. struct llama_context_params result = {
  10462. /*.seed =*/ LLAMA_DEFAULT_SEED,
  10463. /*.n_ctx =*/ 512,
  10464. /*.n_batch =*/ 2048,
  10465. /*.n_ubatch =*/ 512,
  10466. /*.n_seq_max =*/ 1,
  10467. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  10468. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  10469. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  10470. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  10471. /*.rope_freq_base =*/ 0.0f,
  10472. /*.rope_freq_scale =*/ 0.0f,
  10473. /*.yarn_ext_factor =*/ -1.0f,
  10474. /*.yarn_attn_factor =*/ 1.0f,
  10475. /*.yarn_beta_fast =*/ 32.0f,
  10476. /*.yarn_beta_slow =*/ 1.0f,
  10477. /*.yarn_orig_ctx =*/ 0,
  10478. /*.defrag_thold =*/ -1.0f,
  10479. /*.cb_eval =*/ nullptr,
  10480. /*.cb_eval_user_data =*/ nullptr,
  10481. /*.type_k =*/ GGML_TYPE_F16,
  10482. /*.type_v =*/ GGML_TYPE_F16,
  10483. /*.logits_all =*/ false,
  10484. /*.embeddings =*/ false,
  10485. /*.offload_kqv =*/ true,
  10486. /*.abort_callback =*/ nullptr,
  10487. /*.abort_callback_data =*/ nullptr,
  10488. };
  10489. return result;
  10490. }
  10491. struct llama_model_quantize_params llama_model_quantize_default_params() {
  10492. struct llama_model_quantize_params result = {
  10493. /*.nthread =*/ 0,
  10494. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  10495. /*.allow_requantize =*/ false,
  10496. /*.quantize_output_tensor =*/ true,
  10497. /*.only_copy =*/ false,
  10498. /*.pure =*/ false,
  10499. /*.imatrix =*/ nullptr,
  10500. };
  10501. return result;
  10502. }
  10503. size_t llama_max_devices(void) {
  10504. #if defined(GGML_USE_METAL)
  10505. return 1;
  10506. #elif defined(GGML_USE_CUBLAS)
  10507. return GGML_CUDA_MAX_DEVICES;
  10508. #elif defined(GGML_USE_SYCL)
  10509. return GGML_SYCL_MAX_DEVICES;
  10510. #elif defined(GGML_USE_VULKAN)
  10511. return GGML_VK_MAX_DEVICES;
  10512. #else
  10513. return 1;
  10514. #endif
  10515. }
  10516. bool llama_supports_mmap(void) {
  10517. return llama_mmap::SUPPORTED;
  10518. }
  10519. bool llama_supports_mlock(void) {
  10520. return llama_mlock::SUPPORTED;
  10521. }
  10522. bool llama_supports_gpu_offload(void) {
  10523. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  10524. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE)
  10525. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  10526. return true;
  10527. #else
  10528. return false;
  10529. #endif
  10530. }
  10531. void llama_backend_init(void) {
  10532. ggml_time_init();
  10533. // needed to initialize f16 tables
  10534. {
  10535. struct ggml_init_params params = { 0, NULL, false };
  10536. struct ggml_context * ctx = ggml_init(params);
  10537. ggml_free(ctx);
  10538. }
  10539. #ifdef GGML_USE_MPI
  10540. ggml_mpi_backend_init();
  10541. #endif
  10542. }
  10543. void llama_numa_init(enum ggml_numa_strategy numa) {
  10544. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  10545. ggml_numa_init(numa);
  10546. }
  10547. }
  10548. void llama_backend_free(void) {
  10549. #ifdef GGML_USE_MPI
  10550. ggml_mpi_backend_free();
  10551. #endif
  10552. ggml_quantize_free();
  10553. }
  10554. int64_t llama_time_us(void) {
  10555. return ggml_time_us();
  10556. }
  10557. struct llama_model * llama_load_model_from_file(
  10558. const char * path_model,
  10559. struct llama_model_params params) {
  10560. ggml_time_init();
  10561. llama_model * model = new llama_model;
  10562. unsigned cur_percentage = 0;
  10563. if (params.progress_callback == NULL) {
  10564. params.progress_callback_user_data = &cur_percentage;
  10565. params.progress_callback = [](float progress, void * ctx) {
  10566. unsigned * cur_percentage_p = (unsigned *) ctx;
  10567. unsigned percentage = (unsigned) (100 * progress);
  10568. while (percentage > *cur_percentage_p) {
  10569. *cur_percentage_p = percentage;
  10570. LLAMA_LOG_INFO(".");
  10571. if (percentage >= 100) {
  10572. LLAMA_LOG_INFO("\n");
  10573. }
  10574. }
  10575. return true;
  10576. };
  10577. }
  10578. int status = llama_model_load(path_model, *model, params);
  10579. GGML_ASSERT(status <= 0);
  10580. if (status < 0) {
  10581. if (status == -1) {
  10582. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  10583. } else if (status == -2) {
  10584. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  10585. }
  10586. delete model;
  10587. return nullptr;
  10588. }
  10589. return model;
  10590. }
  10591. void llama_free_model(struct llama_model * model) {
  10592. delete model;
  10593. }
  10594. struct llama_context * llama_new_context_with_model(
  10595. struct llama_model * model,
  10596. struct llama_context_params params) {
  10597. if (!model) {
  10598. LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
  10599. return nullptr;
  10600. }
  10601. if (params.n_batch == 0 && params.n_ubatch == 0) {
  10602. LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
  10603. return nullptr;
  10604. }
  10605. if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
  10606. LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
  10607. return nullptr;
  10608. }
  10609. llama_context * ctx = new llama_context(*model);
  10610. const auto & hparams = model->hparams;
  10611. auto & cparams = ctx->cparams;
  10612. // TODO: maybe add n_seq_max here too
  10613. cparams.n_threads = params.n_threads;
  10614. cparams.n_threads_batch = params.n_threads_batch;
  10615. cparams.yarn_ext_factor = params.yarn_ext_factor;
  10616. cparams.yarn_attn_factor = params.yarn_attn_factor;
  10617. cparams.yarn_beta_fast = params.yarn_beta_fast;
  10618. cparams.yarn_beta_slow = params.yarn_beta_slow;
  10619. cparams.defrag_thold = params.defrag_thold;
  10620. cparams.embeddings = params.embeddings;
  10621. cparams.offload_kqv = params.offload_kqv;
  10622. cparams.pooling_type = params.pooling_type;
  10623. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  10624. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  10625. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  10626. // with causal attention, the batch size is limited by the context size
  10627. cparams.n_batch = hparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
  10628. cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
  10629. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  10630. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  10631. hparams.n_ctx_train;
  10632. cparams.cb_eval = params.cb_eval;
  10633. cparams.cb_eval_user_data = params.cb_eval_user_data;
  10634. auto rope_scaling_type = params.rope_scaling_type;
  10635. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  10636. rope_scaling_type = hparams.rope_scaling_type_train;
  10637. }
  10638. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  10639. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  10640. }
  10641. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  10642. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  10643. }
  10644. cparams.causal_attn = hparams.causal_attn;
  10645. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  10646. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  10647. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  10648. } else {
  10649. cparams.pooling_type = hparams.pooling_type;
  10650. }
  10651. }
  10652. if (params.seed == LLAMA_DEFAULT_SEED) {
  10653. params.seed = time(NULL);
  10654. }
  10655. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  10656. LLAMA_LOG_INFO("%s: n_batch = %u\n", __func__, cparams.n_batch);
  10657. LLAMA_LOG_INFO("%s: n_ubatch = %u\n", __func__, cparams.n_ubatch);
  10658. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  10659. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  10660. ctx->abort_callback = params.abort_callback;
  10661. ctx->abort_callback_data = params.abort_callback_data;
  10662. ctx->rng = std::mt19937(params.seed);
  10663. ctx->logits_all = params.logits_all;
  10664. uint32_t kv_size = cparams.n_ctx;
  10665. ggml_type type_k = params.type_k;
  10666. ggml_type type_v = params.type_v;
  10667. // Mamba only needs a constant number of KV cache cells per sequence
  10668. if (model->arch == LLM_ARCH_MAMBA) {
  10669. // Mamba needs at least as many KV cells as there are sequences kept at any time
  10670. kv_size = std::max((uint32_t) 1, params.n_seq_max);
  10671. // it's probably best to keep as much precision as possible for the states
  10672. type_k = GGML_TYPE_F32; // required by ggml_ssm_conv for Mamba's conv_states
  10673. type_v = GGML_TYPE_F32; // required by ggml_ssm_scan for Mamba's ssm_states
  10674. }
  10675. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  10676. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  10677. if (!hparams.vocab_only) {
  10678. // initialize backends
  10679. #ifdef GGML_USE_METAL
  10680. if (model->n_gpu_layers > 0) {
  10681. ctx->backend_metal = ggml_backend_metal_init();
  10682. if (ctx->backend_metal == nullptr) {
  10683. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  10684. llama_free(ctx);
  10685. return nullptr;
  10686. }
  10687. ctx->backends.push_back(ctx->backend_metal);
  10688. }
  10689. #elif defined(GGML_USE_CUBLAS)
  10690. if (model->n_gpu_layers > 0) {
  10691. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  10692. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  10693. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  10694. if (backend == nullptr) {
  10695. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  10696. llama_free(ctx);
  10697. return nullptr;
  10698. }
  10699. ctx->backends.push_back(backend);
  10700. } else {
  10701. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  10702. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  10703. ggml_backend_t backend = ggml_backend_cuda_init(device);
  10704. if (backend == nullptr) {
  10705. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  10706. llama_free(ctx);
  10707. return nullptr;
  10708. }
  10709. ctx->backends.push_back(backend);
  10710. }
  10711. }
  10712. }
  10713. #elif defined(GGML_USE_VULKAN)
  10714. if (model->n_gpu_layers > 0) {
  10715. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  10716. ggml_backend_t backend = ggml_backend_vk_init(device);
  10717. if (backend == nullptr) {
  10718. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  10719. llama_free(ctx);
  10720. return nullptr;
  10721. }
  10722. ctx->backends.push_back(backend);
  10723. }
  10724. }
  10725. #elif defined(GGML_USE_SYCL)
  10726. if (model->n_gpu_layers > 0) {
  10727. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  10728. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  10729. int main_gpu_index = ggml_backend_sycl_get_device_index(model->main_gpu);
  10730. ggml_backend_t backend = ggml_backend_sycl_init(main_gpu_index);
  10731. if (backend == nullptr) {
  10732. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d)backend\n", __func__, model->main_gpu, main_gpu_index);
  10733. llama_free(ctx);
  10734. return nullptr;
  10735. }
  10736. ctx->backends.push_back(backend);
  10737. } else {
  10738. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  10739. int id_list[GGML_SYCL_MAX_DEVICES];
  10740. ggml_sycl_get_gpu_list(id_list, GGML_SYCL_MAX_DEVICES);
  10741. for (int i = 0; i < ggml_backend_sycl_get_device_count(); ++i) {
  10742. int device_id = id_list[i];
  10743. ggml_backend_t backend = ggml_backend_sycl_init(i);
  10744. if (backend == nullptr) {
  10745. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d)backend\n", __func__, device_id, i);
  10746. llama_free(ctx);
  10747. return nullptr;
  10748. }
  10749. ctx->backends.push_back(backend);
  10750. }
  10751. }
  10752. }
  10753. #elif defined(GGML_USE_KOMPUTE)
  10754. if (model->n_gpu_layers > 0) {
  10755. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  10756. if (backend == nullptr) {
  10757. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  10758. llama_free(ctx);
  10759. return nullptr;
  10760. }
  10761. ctx->backends.push_back(backend);
  10762. }
  10763. #endif
  10764. ctx->backend_cpu = ggml_backend_cpu_init();
  10765. if (ctx->backend_cpu == nullptr) {
  10766. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  10767. llama_free(ctx);
  10768. return nullptr;
  10769. }
  10770. ctx->backends.push_back(ctx->backend_cpu);
  10771. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v, kv_size, cparams.offload_kqv)) {
  10772. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  10773. llama_free(ctx);
  10774. return nullptr;
  10775. }
  10776. {
  10777. size_t memory_size_k = 0;
  10778. size_t memory_size_v = 0;
  10779. for (auto & k : ctx->kv_self.k_l) {
  10780. memory_size_k += ggml_nbytes(k);
  10781. }
  10782. for (auto & v : ctx->kv_self.v_l) {
  10783. memory_size_v += ggml_nbytes(v);
  10784. }
  10785. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  10786. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  10787. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  10788. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  10789. }
  10790. // graph outputs buffer
  10791. {
  10792. // resized during inference, reserve maximum
  10793. ctx->logits_size = hparams.n_vocab*cparams.n_batch;
  10794. ctx->embd_size = params.embeddings ? hparams.n_embd*cparams.n_batch : 0;
  10795. const size_t buf_output_size = (ctx->logits_size + ctx->embd_size)*sizeof(float);
  10796. ctx->buf_output = ggml_backend_buft_alloc_buffer(llama_default_buffer_type_cpu(true), buf_output_size);
  10797. if (ctx->buf_output == nullptr) {
  10798. LLAMA_LOG_ERROR("%s: failed to allocate logits buffer\n", __func__);
  10799. llama_free(ctx);
  10800. return nullptr;
  10801. }
  10802. ggml_backend_buffer_clear(ctx->buf_output, 0);
  10803. ctx->logits = (float *) ggml_backend_buffer_get_base(ctx->buf_output);
  10804. if (params.embeddings) {
  10805. ctx->embd = ctx->logits + ctx->logits_size;
  10806. }
  10807. LLAMA_LOG_INFO("%s: %10s output buffer size = %8.2f MiB\n", __func__,
  10808. ggml_backend_buffer_name(ctx->buf_output),
  10809. ggml_backend_buffer_get_size(ctx->buf_output) / 1024.0 / 1024.0);
  10810. }
  10811. // scheduler and compute buffers
  10812. {
  10813. // buffer types used for the compute buffer of each backend
  10814. std::vector<ggml_backend_buffer_type_t> backend_buft;
  10815. for (auto * backend : ctx->backends) {
  10816. if (ggml_backend_is_cpu(backend)) {
  10817. // use host buffers for the CPU backend compute buffer
  10818. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  10819. } else {
  10820. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  10821. }
  10822. }
  10823. // buffer used to store the computation graph and the tensor meta data
  10824. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead_custom(LLAMA_MAX_NODES, false));
  10825. // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
  10826. bool pipeline_parallel = llama_get_device_count() > 1 && model->n_gpu_layers > (int)model->hparams.n_layer && model->split_mode == LLAMA_SPLIT_MODE_LAYER;
  10827. #ifndef GGML_USE_CUBLAS
  10828. // pipeline parallelism requires support for async compute and events
  10829. // currently this is only implemented in the CUDA backend
  10830. pipeline_parallel = false;
  10831. #endif
  10832. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES, pipeline_parallel);
  10833. if (pipeline_parallel) {
  10834. LLAMA_LOG_INFO("%s: pipeline parallelism enabled (n_copies=%d)\n", __func__, ggml_backend_sched_get_n_copies(ctx->sched));
  10835. }
  10836. // build worst-case graph
  10837. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_ubatch);
  10838. int n_past = cparams.n_ctx - n_tokens;
  10839. 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
  10840. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  10841. // initialize scheduler with the worst-case graph
  10842. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  10843. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  10844. llama_free(ctx);
  10845. return nullptr;
  10846. }
  10847. for (size_t i = 0; i < ctx->backends.size(); i++) {
  10848. ggml_backend_t backend = ctx->backends[i];
  10849. ggml_backend_buffer_type_t buft = backend_buft[i];
  10850. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  10851. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  10852. ggml_backend_buft_name(buft),
  10853. size / 1024.0 / 1024.0);
  10854. }
  10855. // note: the number of splits during measure is higher than during inference due to the kv shift
  10856. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  10857. LLAMA_LOG_INFO("%s: graph splits: %d\n", __func__, n_splits);
  10858. }
  10859. }
  10860. #ifdef GGML_USE_MPI
  10861. ctx->ctx_mpi = ggml_mpi_init();
  10862. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  10863. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  10864. // TODO: needs fix after #3228
  10865. GGML_ASSERT(false && "not implemented");
  10866. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  10867. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  10868. llama_backend_free();
  10869. exit(1);
  10870. }
  10871. #endif
  10872. return ctx;
  10873. }
  10874. void llama_free(struct llama_context * ctx) {
  10875. delete ctx;
  10876. }
  10877. const llama_model * llama_get_model(const struct llama_context * ctx) {
  10878. return &ctx->model;
  10879. }
  10880. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  10881. return ctx->cparams.n_ctx;
  10882. }
  10883. uint32_t llama_n_batch(const struct llama_context * ctx) {
  10884. return ctx->cparams.n_batch;
  10885. }
  10886. uint32_t llama_n_ubatch(const struct llama_context * ctx) {
  10887. return ctx->cparams.n_ubatch;
  10888. }
  10889. uint32_t llama_n_seq_max(const struct llama_context * ctx) {
  10890. return ctx->kv_self.size;
  10891. }
  10892. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  10893. return model->vocab.type;
  10894. }
  10895. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  10896. switch (model->arch) {
  10897. // these models do not use RoPE
  10898. case LLM_ARCH_GPT2:
  10899. case LLM_ARCH_GPTJ:
  10900. case LLM_ARCH_GPTNEOX:
  10901. case LLM_ARCH_MPT:
  10902. case LLM_ARCH_REFACT:
  10903. case LLM_ARCH_BLOOM:
  10904. case LLM_ARCH_MAMBA:
  10905. return LLAMA_ROPE_TYPE_NONE;
  10906. // use what we call a normal RoPE, operating on pairs of consecutive head values
  10907. case LLM_ARCH_LLAMA:
  10908. case LLM_ARCH_BAICHUAN:
  10909. case LLM_ARCH_STARCODER:
  10910. case LLM_ARCH_PLAMO:
  10911. case LLM_ARCH_CODESHELL:
  10912. case LLM_ARCH_ORION:
  10913. case LLM_ARCH_INTERNLM2:
  10914. case LLM_ARCH_MINICPM:
  10915. return LLAMA_ROPE_TYPE_NORM;
  10916. // the pairs of head values are offset by n_rot/2
  10917. case LLM_ARCH_FALCON:
  10918. case LLM_ARCH_PERSIMMON:
  10919. case LLM_ARCH_BERT:
  10920. case LLM_ARCH_NOMIC_BERT:
  10921. case LLM_ARCH_STABLELM:
  10922. case LLM_ARCH_QWEN:
  10923. case LLM_ARCH_QWEN2:
  10924. case LLM_ARCH_PHI2:
  10925. case LLM_ARCH_GEMMA:
  10926. case LLM_ARCH_STARCODER2:
  10927. return LLAMA_ROPE_TYPE_NEOX;
  10928. // all model arches should be listed explicitly here
  10929. case LLM_ARCH_UNKNOWN:
  10930. GGML_ASSERT(false && "unknown architecture");
  10931. break;
  10932. }
  10933. return LLAMA_ROPE_TYPE_NONE;
  10934. }
  10935. int32_t llama_n_vocab(const struct llama_model * model) {
  10936. return model->hparams.n_vocab;
  10937. }
  10938. int32_t llama_n_ctx_train(const struct llama_model * model) {
  10939. return model->hparams.n_ctx_train;
  10940. }
  10941. int32_t llama_n_embd(const struct llama_model * model) {
  10942. return model->hparams.n_embd;
  10943. }
  10944. float llama_rope_freq_scale_train(const struct llama_model * model) {
  10945. return model->hparams.rope_freq_scale_train;
  10946. }
  10947. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  10948. const auto & it = model->gguf_kv.find(key);
  10949. if (it == model->gguf_kv.end()) {
  10950. if (buf_size > 0) {
  10951. buf[0] = '\0';
  10952. }
  10953. return -1;
  10954. }
  10955. return snprintf(buf, buf_size, "%s", it->second.c_str());
  10956. }
  10957. int32_t llama_model_meta_count(const struct llama_model * model) {
  10958. return (int)model->gguf_kv.size();
  10959. }
  10960. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  10961. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  10962. if (buf_size > 0) {
  10963. buf[0] = '\0';
  10964. }
  10965. return -1;
  10966. }
  10967. auto it = model->gguf_kv.begin();
  10968. std::advance(it, i);
  10969. return snprintf(buf, buf_size, "%s", it->first.c_str());
  10970. }
  10971. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  10972. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  10973. if (buf_size > 0) {
  10974. buf[0] = '\0';
  10975. }
  10976. return -1;
  10977. }
  10978. auto it = model->gguf_kv.begin();
  10979. std::advance(it, i);
  10980. return snprintf(buf, buf_size, "%s", it->second.c_str());
  10981. }
  10982. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  10983. return snprintf(buf, buf_size, "%s %s %s",
  10984. llama_model_arch_name(model->arch),
  10985. llama_model_type_name(model->type),
  10986. llama_model_ftype_name(model->ftype).c_str());
  10987. }
  10988. uint64_t llama_model_size(const struct llama_model * model) {
  10989. uint64_t size = 0;
  10990. for (const auto & it : model->tensors_by_name) {
  10991. size += ggml_nbytes(it.second);
  10992. }
  10993. return size;
  10994. }
  10995. uint64_t llama_model_n_params(const struct llama_model * model) {
  10996. uint64_t nparams = 0;
  10997. for (const auto & it : model->tensors_by_name) {
  10998. nparams += ggml_nelements(it.second);
  10999. }
  11000. return nparams;
  11001. }
  11002. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  11003. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  11004. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  11005. return it.first == name;
  11006. });
  11007. if (it == model->tensors_by_name.end()) {
  11008. return nullptr;
  11009. }
  11010. return it->second;
  11011. }
  11012. uint32_t llama_model_quantize(
  11013. const char * fname_inp,
  11014. const char * fname_out,
  11015. const llama_model_quantize_params * params) {
  11016. try {
  11017. llama_model_quantize_internal(fname_inp, fname_out, params);
  11018. return 0;
  11019. } catch (const std::exception & err) {
  11020. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  11021. return 1;
  11022. }
  11023. }
  11024. int32_t llama_model_apply_lora_from_file(const struct llama_model * model, const char * path_lora, float scale, const char * path_base_model, int32_t n_threads) {
  11025. try {
  11026. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  11027. } catch (const std::exception & err) {
  11028. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  11029. return 1;
  11030. }
  11031. }
  11032. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_seq_max) {
  11033. struct llama_kv_cache_view result = {
  11034. /*.n_cells = */ 0,
  11035. /*.n_seq_max = */ n_seq_max,
  11036. /*.token_count = */ 0,
  11037. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  11038. /*.max_contiguous = */ 0,
  11039. /*.max_contiguous_idx = */ -1,
  11040. /*.cells = */ nullptr,
  11041. /*.cells_sequences = */ nullptr,
  11042. };
  11043. return result;
  11044. }
  11045. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  11046. if (view->cells != nullptr) {
  11047. free(view->cells);
  11048. view->cells = nullptr;
  11049. }
  11050. if (view->cells_sequences != nullptr) {
  11051. free(view->cells_sequences);
  11052. view->cells_sequences = nullptr;
  11053. }
  11054. }
  11055. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  11056. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  11057. view->n_cells = int32_t(ctx->kv_self.size);
  11058. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  11059. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  11060. view->cells = (struct llama_kv_cache_view_cell *)p;
  11061. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_seq_max * view->n_cells);
  11062. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  11063. view->cells_sequences = (llama_seq_id *)p;
  11064. }
  11065. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  11066. llama_kv_cache_view_cell * c_curr = view->cells;
  11067. llama_seq_id * cs_curr = view->cells_sequences;
  11068. int32_t used_cells = 0;
  11069. int32_t token_count = 0;
  11070. int32_t curr_contig_idx = -1;
  11071. uint32_t max_contig = 0;
  11072. int32_t max_contig_idx = -1;
  11073. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_seq_max) {
  11074. const size_t curr_size = kv_cells[i].seq_id.size();
  11075. token_count += curr_size;
  11076. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  11077. if (curr_size > 0) {
  11078. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  11079. max_contig = i - curr_contig_idx;
  11080. max_contig_idx = curr_contig_idx;
  11081. }
  11082. curr_contig_idx = -1;
  11083. } else if (curr_contig_idx < 0) {
  11084. curr_contig_idx = i;
  11085. }
  11086. int seq_idx = 0;
  11087. for (const llama_seq_id it : kv_cells[i].seq_id) {
  11088. if (seq_idx >= view->n_seq_max) {
  11089. break;
  11090. }
  11091. cs_curr[seq_idx] = it;
  11092. seq_idx++;
  11093. }
  11094. if (seq_idx != 0) {
  11095. used_cells++;
  11096. }
  11097. for (; seq_idx < view->n_seq_max; seq_idx++) {
  11098. cs_curr[seq_idx] = -1;
  11099. }
  11100. }
  11101. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  11102. max_contig_idx = curr_contig_idx;
  11103. max_contig = kv_cells.size() - curr_contig_idx;
  11104. }
  11105. view->max_contiguous = max_contig;
  11106. view->max_contiguous_idx = max_contig_idx;
  11107. view->token_count = token_count;
  11108. view->used_cells = used_cells;
  11109. if (uint32_t(used_cells) != ctx->kv_self.used) {
  11110. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  11111. __func__, ctx->kv_self.used, used_cells);
  11112. }
  11113. }
  11114. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  11115. int result = 0;
  11116. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  11117. result += ctx->kv_self.cells[i].seq_id.size();
  11118. }
  11119. return result;
  11120. }
  11121. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  11122. return ctx->kv_self.used;
  11123. }
  11124. void llama_kv_cache_clear(struct llama_context * ctx) {
  11125. llama_kv_cache_clear(ctx->kv_self);
  11126. }
  11127. bool llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  11128. return llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  11129. }
  11130. 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) {
  11131. if (seq_id_src == seq_id_dst) {
  11132. return;
  11133. }
  11134. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  11135. }
  11136. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  11137. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  11138. }
  11139. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  11140. if (delta == 0) {
  11141. return;
  11142. }
  11143. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  11144. }
  11145. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  11146. if (d == 1) {
  11147. return;
  11148. }
  11149. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  11150. }
  11151. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  11152. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  11153. }
  11154. void llama_kv_cache_defrag(struct llama_context * ctx) {
  11155. llama_kv_cache_defrag(ctx->kv_self);
  11156. }
  11157. void llama_kv_cache_update(struct llama_context * ctx) {
  11158. llama_kv_cache_update_internal(*ctx);
  11159. }
  11160. // Returns the *maximum* size of the state
  11161. size_t llama_get_state_size(const struct llama_context * ctx) {
  11162. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  11163. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  11164. const size_t s_rng_size = sizeof(size_t);
  11165. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  11166. const size_t s_logits_size = sizeof(size_t);
  11167. // assume worst case for logits although only currently set ones are serialized
  11168. const size_t s_logits = ctx->logits_size * sizeof(float);
  11169. const size_t s_embedding_size = sizeof(size_t);
  11170. const size_t s_embedding = ctx->embd_size * sizeof(float);
  11171. const size_t s_kv_buf_size = sizeof(size_t);
  11172. const size_t s_kv_head = sizeof(uint32_t);
  11173. const size_t s_kv_size = sizeof(uint32_t);
  11174. const size_t s_kv_used = sizeof(uint32_t);
  11175. const size_t s_kv = ctx->kv_self.total_size();
  11176. // TODO: assume the max is more than 1 seq_id per KV cell
  11177. const size_t s_kv_cell = sizeof(llama_pos) + sizeof(size_t) + sizeof(llama_seq_id);
  11178. const size_t s_kv_cells = ctx->kv_self.size * s_kv_cell;
  11179. const size_t s_total = (
  11180. + s_rng_size
  11181. + s_rng
  11182. + s_logits_size
  11183. + s_logits
  11184. + s_embedding_size
  11185. + s_embedding
  11186. + s_kv_buf_size
  11187. + s_kv_head
  11188. + s_kv_size
  11189. + s_kv_used
  11190. + s_kv
  11191. + s_kv_cells
  11192. );
  11193. return s_total;
  11194. }
  11195. // llama_context_data
  11196. struct llama_data_context {
  11197. virtual void write(const void * src, size_t size) = 0;
  11198. virtual size_t get_size_written() = 0;
  11199. virtual ~llama_data_context() = default;
  11200. };
  11201. struct llama_data_buffer_context : llama_data_context {
  11202. uint8_t * ptr;
  11203. size_t size_written = 0;
  11204. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  11205. void write(const void * src, size_t size) override {
  11206. memcpy(ptr, src, size);
  11207. ptr += size;
  11208. size_written += size;
  11209. }
  11210. size_t get_size_written() override {
  11211. return size_written;
  11212. }
  11213. };
  11214. struct llama_data_file_context : llama_data_context {
  11215. llama_file * file;
  11216. size_t size_written = 0;
  11217. llama_data_file_context(llama_file * f) : file(f) {}
  11218. void write(const void * src, size_t size) override {
  11219. file->write_raw(src, size);
  11220. size_written += size;
  11221. }
  11222. size_t get_size_written() override {
  11223. return size_written;
  11224. }
  11225. };
  11226. /** copy state data into either a buffer or file depending on the passed in context
  11227. *
  11228. * file context:
  11229. * llama_file file("/path", "wb");
  11230. * llama_data_file_context data_ctx(&file);
  11231. * llama_copy_state_data(ctx, &data_ctx);
  11232. *
  11233. * buffer context:
  11234. * std::vector<uint8_t> buf(max_size, 0);
  11235. * llama_data_buffer_context data_ctx(&buf.data());
  11236. * llama_copy_state_data(ctx, &data_ctx);
  11237. *
  11238. */
  11239. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  11240. // copy rng
  11241. {
  11242. std::ostringstream rng_ss;
  11243. rng_ss << ctx->rng;
  11244. const std::string & rng_str = rng_ss.str();
  11245. const size_t rng_size = rng_str.size();
  11246. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  11247. data_ctx->write(&rng_size, sizeof(rng_size));
  11248. data_ctx->write(rng_str.data(), rng_size);
  11249. }
  11250. // copy logits
  11251. {
  11252. const size_t logits_size = ctx->logits_size;
  11253. data_ctx->write(&logits_size, sizeof(logits_size));
  11254. if (logits_size) {
  11255. data_ctx->write(ctx->logits, logits_size * sizeof(float));
  11256. }
  11257. }
  11258. // copy embeddings
  11259. {
  11260. const size_t embeddings_size = ctx->embd_size;
  11261. data_ctx->write(&embeddings_size, sizeof(embeddings_size));
  11262. if (embeddings_size) {
  11263. data_ctx->write(ctx->embd, embeddings_size * sizeof(float));
  11264. }
  11265. }
  11266. // copy kv cache
  11267. {
  11268. const auto & kv_self = ctx->kv_self;
  11269. const auto & hparams = ctx->model.hparams;
  11270. const uint32_t n_layer = hparams.n_layer;
  11271. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  11272. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  11273. const size_t kv_buf_size = kv_self.total_size();
  11274. const uint32_t kv_head = llama_kv_cache_cell_max(kv_self);
  11275. const uint32_t kv_size = kv_self.size;
  11276. const uint32_t kv_used = kv_self.used;
  11277. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  11278. data_ctx->write(&kv_head, sizeof(kv_head));
  11279. data_ctx->write(&kv_size, sizeof(kv_size));
  11280. data_ctx->write(&kv_used, sizeof(kv_used));
  11281. if (kv_buf_size) {
  11282. std::vector<uint8_t> tmp_buf;
  11283. for (int il = 0; il < (int) n_layer; ++il) {
  11284. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  11285. tmp_buf.resize(k_size);
  11286. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  11287. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  11288. if (kv_self.recurrent) {
  11289. // v is contiguous for recurrent models
  11290. // TODO: use other tensors for state models than k and v
  11291. const size_t v_size = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*kv_head);
  11292. tmp_buf.resize(v_size);
  11293. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), 0, tmp_buf.size());
  11294. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  11295. continue;
  11296. }
  11297. // v is not contiguous, copy row by row
  11298. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  11299. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_size);
  11300. tmp_buf.resize(v_row_size);
  11301. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  11302. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*v_row_stride, tmp_buf.size());
  11303. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  11304. }
  11305. }
  11306. }
  11307. for (uint32_t i = 0; i < kv_head; ++i) {
  11308. const auto & cell = kv_self.cells[i];
  11309. const llama_pos pos = cell.pos;
  11310. const size_t seq_id_size = cell.seq_id.size();
  11311. data_ctx->write(&pos, sizeof(pos));
  11312. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  11313. for (auto seq_id : cell.seq_id) {
  11314. data_ctx->write(&seq_id, sizeof(seq_id));
  11315. }
  11316. }
  11317. }
  11318. }
  11319. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  11320. llama_data_buffer_context data_ctx(dst);
  11321. llama_copy_state_data_internal(ctx, &data_ctx);
  11322. return data_ctx.get_size_written();
  11323. }
  11324. // Sets the state reading from the specified source address
  11325. size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
  11326. const uint8_t * inp = src;
  11327. // set rng
  11328. {
  11329. size_t rng_size;
  11330. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  11331. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  11332. std::string rng_str((const char *)inp, rng_size); inp += rng_size;
  11333. std::istringstream rng_ss(rng_str);
  11334. rng_ss >> ctx->rng;
  11335. GGML_ASSERT(!rng_ss.fail());
  11336. }
  11337. // set logits
  11338. {
  11339. size_t logits_size;
  11340. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  11341. GGML_ASSERT(ctx->logits_size >= logits_size);
  11342. if (logits_size) {
  11343. memcpy(ctx->logits, inp, logits_size * sizeof(float));
  11344. inp += logits_size * sizeof(float);
  11345. }
  11346. }
  11347. // set embeddings
  11348. {
  11349. size_t embeddings_size;
  11350. memcpy(&embeddings_size, inp, sizeof(embeddings_size)); inp += sizeof(embeddings_size);
  11351. GGML_ASSERT(ctx->embd_size == embeddings_size);
  11352. if (embeddings_size) {
  11353. memcpy(ctx->embd, inp, embeddings_size * sizeof(float));
  11354. inp += embeddings_size * sizeof(float);
  11355. }
  11356. }
  11357. // set kv cache
  11358. {
  11359. const auto & kv_self = ctx->kv_self;
  11360. const auto & hparams = ctx->model.hparams;
  11361. const uint32_t n_layer = hparams.n_layer;
  11362. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  11363. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  11364. size_t kv_buf_size;
  11365. uint32_t kv_head;
  11366. uint32_t kv_size;
  11367. uint32_t kv_used;
  11368. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  11369. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  11370. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  11371. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  11372. if (kv_buf_size) {
  11373. GGML_ASSERT(kv_self.total_size() == kv_buf_size);
  11374. for (int il = 0; il < (int) n_layer; ++il) {
  11375. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  11376. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  11377. inp += k_size;
  11378. if (kv_self.recurrent) {
  11379. // v is contiguous for recurrent models
  11380. // TODO: use other tensors for state models than k and v
  11381. const size_t v_size = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*kv_head);
  11382. ggml_backend_tensor_set(kv_self.v_l[il], inp, 0, v_size);
  11383. inp += v_size;
  11384. continue;
  11385. }
  11386. // v is not contiguous, copy row by row
  11387. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  11388. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_size);
  11389. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  11390. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*v_row_stride, v_row_size);
  11391. inp += v_row_size;
  11392. }
  11393. }
  11394. }
  11395. GGML_ASSERT(kv_self.size == kv_size);
  11396. ctx->kv_self.head = kv_head;
  11397. ctx->kv_self.size = kv_size;
  11398. ctx->kv_self.used = kv_used;
  11399. ctx->kv_self.cells.resize(kv_size);
  11400. for (uint32_t i = 0; i < kv_head; ++i) {
  11401. llama_pos pos;
  11402. size_t seq_id_size;
  11403. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  11404. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  11405. ctx->kv_self.cells[i].pos = pos;
  11406. llama_seq_id seq_id;
  11407. for (size_t j = 0; j < seq_id_size; ++j) {
  11408. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  11409. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  11410. }
  11411. }
  11412. for (uint32_t i = kv_head; i < kv_size; ++i) {
  11413. ctx->kv_self.cells[i].pos = -1;
  11414. ctx->kv_self.cells[i].seq_id.clear();
  11415. }
  11416. }
  11417. const size_t nread = inp - src;
  11418. const size_t max_size = llama_get_state_size(ctx);
  11419. GGML_ASSERT(nread <= max_size);
  11420. return nread;
  11421. }
  11422. 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) {
  11423. llama_file file(path_session, "rb");
  11424. // sanity checks
  11425. {
  11426. const uint32_t magic = file.read_u32();
  11427. const uint32_t version = file.read_u32();
  11428. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  11429. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  11430. return false;
  11431. }
  11432. llama_hparams session_hparams;
  11433. file.read_raw(&session_hparams, sizeof(llama_hparams));
  11434. if (session_hparams != ctx->model.hparams) {
  11435. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  11436. return false;
  11437. }
  11438. }
  11439. // load the prompt
  11440. {
  11441. const uint32_t n_token_count = file.read_u32();
  11442. if (n_token_count > n_token_capacity) {
  11443. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  11444. return false;
  11445. }
  11446. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  11447. *n_token_count_out = n_token_count;
  11448. }
  11449. // restore the context state
  11450. {
  11451. const size_t n_state_size_cur = file.size - file.tell();
  11452. const size_t n_state_size_max = llama_get_state_size(ctx);
  11453. if (n_state_size_cur > n_state_size_max) {
  11454. 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);
  11455. return false;
  11456. }
  11457. std::vector<uint8_t> state_data(n_state_size_max);
  11458. file.read_raw(state_data.data(), n_state_size_cur);
  11459. llama_set_state_data(ctx, state_data.data());
  11460. }
  11461. return true;
  11462. }
  11463. 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) {
  11464. try {
  11465. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  11466. } catch (const std::exception & err) {
  11467. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  11468. return false;
  11469. }
  11470. }
  11471. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  11472. llama_file file(path_session, "wb");
  11473. file.write_u32(LLAMA_SESSION_MAGIC);
  11474. file.write_u32(LLAMA_SESSION_VERSION);
  11475. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  11476. // save the prompt
  11477. file.write_u32((uint32_t) n_token_count);
  11478. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  11479. // save the context state using stream saving
  11480. llama_data_file_context data_ctx(&file);
  11481. llama_copy_state_data_internal(ctx, &data_ctx);
  11482. return true;
  11483. }
  11484. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  11485. ctx->cparams.n_threads = n_threads;
  11486. ctx->cparams.n_threads_batch = n_threads_batch;
  11487. }
  11488. void llama_set_abort_callback(struct llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
  11489. ctx->abort_callback = abort_callback;
  11490. ctx->abort_callback_data = abort_callback_data;
  11491. }
  11492. void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn) {
  11493. ctx->cparams.causal_attn = causal_attn;
  11494. }
  11495. struct llama_batch llama_batch_get_one(
  11496. llama_token * tokens,
  11497. int32_t n_tokens,
  11498. llama_pos pos_0,
  11499. llama_seq_id seq_id) {
  11500. return {
  11501. /*n_tokens =*/ n_tokens,
  11502. /*tokens =*/ tokens,
  11503. /*embd =*/ nullptr,
  11504. /*pos =*/ nullptr,
  11505. /*n_seq_id =*/ nullptr,
  11506. /*seq_id =*/ nullptr,
  11507. /*logits =*/ nullptr,
  11508. /*all_pos_0 =*/ pos_0,
  11509. /*all_pos_1 =*/ 1,
  11510. /*all_seq_id =*/ seq_id,
  11511. };
  11512. }
  11513. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  11514. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  11515. if (embd) {
  11516. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  11517. } else {
  11518. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  11519. }
  11520. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  11521. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  11522. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  11523. for (int i = 0; i < n_tokens_alloc; ++i) {
  11524. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  11525. }
  11526. batch.seq_id[n_tokens_alloc] = nullptr;
  11527. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  11528. return batch;
  11529. }
  11530. void llama_batch_free(struct llama_batch batch) {
  11531. if (batch.token) free(batch.token);
  11532. if (batch.embd) free(batch.embd);
  11533. if (batch.pos) free(batch.pos);
  11534. if (batch.n_seq_id) free(batch.n_seq_id);
  11535. if (batch.seq_id) {
  11536. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  11537. free(batch.seq_id[i]);
  11538. }
  11539. free(batch.seq_id);
  11540. }
  11541. if (batch.logits) free(batch.logits);
  11542. }
  11543. int32_t llama_decode(
  11544. struct llama_context * ctx,
  11545. struct llama_batch batch) {
  11546. const int ret = llama_decode_internal(*ctx, batch);
  11547. if (ret < 0) {
  11548. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  11549. }
  11550. return ret;
  11551. }
  11552. void llama_synchronize(struct llama_context * ctx) {
  11553. ggml_backend_sched_synchronize(ctx->sched);
  11554. // FIXME: if multiple single tokens are evaluated without a synchronization,
  11555. // the stats will be added to the prompt evaluation stats
  11556. // this should only happen when using batch size 1 to evaluate a batch
  11557. // add the evaluation to the stats
  11558. if (ctx->n_queued_tokens == 1) {
  11559. ctx->t_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  11560. ctx->n_eval++;
  11561. } else if (ctx->n_queued_tokens > 1) {
  11562. ctx->t_p_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  11563. ctx->n_p_eval += ctx->n_queued_tokens;
  11564. }
  11565. // get a more accurate load time, upon first eval
  11566. if (ctx->n_queued_tokens > 0 && !ctx->has_evaluated_once) {
  11567. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  11568. ctx->has_evaluated_once = true;
  11569. }
  11570. ctx->n_queued_tokens = 0;
  11571. ctx->t_compute_start_us = 0;
  11572. }
  11573. float * llama_get_logits(struct llama_context * ctx) {
  11574. llama_synchronize(ctx);
  11575. return ctx->logits;
  11576. }
  11577. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  11578. assert(ctx->logits_valid.at(i));
  11579. llama_synchronize(ctx);
  11580. return ctx->logits + i*ctx->model.hparams.n_vocab;
  11581. }
  11582. float * llama_get_embeddings(struct llama_context * ctx) {
  11583. llama_synchronize(ctx);
  11584. return ctx->embd;
  11585. }
  11586. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  11587. llama_synchronize(ctx);
  11588. return ctx->embd + i*ctx->model.hparams.n_embd;
  11589. }
  11590. float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id) {
  11591. llama_synchronize(ctx);
  11592. auto it = ctx->embd_seq.find(seq_id);
  11593. if (it == ctx->embd_seq.end()) {
  11594. return nullptr;
  11595. }
  11596. return it->second.data();
  11597. }
  11598. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  11599. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  11600. return model->vocab.id_to_token[token].text.c_str();
  11601. }
  11602. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  11603. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  11604. return model->vocab.id_to_token[token].score;
  11605. }
  11606. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  11607. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  11608. return model->vocab.id_to_token[token].type;
  11609. }
  11610. llama_token llama_token_bos(const struct llama_model * model) {
  11611. return model->vocab.special_bos_id;
  11612. }
  11613. llama_token llama_token_eos(const struct llama_model * model) {
  11614. return model->vocab.special_eos_id;
  11615. }
  11616. llama_token llama_token_nl(const struct llama_model * model) {
  11617. return model->vocab.linefeed_id;
  11618. }
  11619. int32_t llama_add_bos_token(const struct llama_model * model) {
  11620. return model->vocab.special_add_bos;
  11621. }
  11622. int32_t llama_add_eos_token(const struct llama_model * model) {
  11623. return model->vocab.special_add_eos;
  11624. }
  11625. llama_token llama_token_prefix(const struct llama_model * model) {
  11626. return model->vocab.special_prefix_id;
  11627. }
  11628. llama_token llama_token_middle(const struct llama_model * model) {
  11629. return model->vocab.special_middle_id;
  11630. }
  11631. llama_token llama_token_suffix(const struct llama_model * model) {
  11632. return model->vocab.special_suffix_id;
  11633. }
  11634. llama_token llama_token_eot(const struct llama_model * model) {
  11635. return model->vocab.special_eot_id;
  11636. }
  11637. int32_t llama_tokenize(
  11638. const struct llama_model * model,
  11639. const char * text,
  11640. int32_t text_len,
  11641. llama_token * tokens,
  11642. int32_t n_tokens_max,
  11643. bool add_bos,
  11644. bool special) {
  11645. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  11646. if (n_tokens_max < (int) res.size()) {
  11647. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  11648. return -((int) res.size());
  11649. }
  11650. for (size_t i = 0; i < res.size(); i++) {
  11651. tokens[i] = res[i];
  11652. }
  11653. return res.size();
  11654. }
  11655. static std::string llama_decode_text(const std::string & text) {
  11656. std::string decoded_text;
  11657. auto unicode_sequences = unicode_cpts_from_utf8(text);
  11658. for (auto & unicode_sequence : unicode_sequences) {
  11659. decoded_text += unicode_utf8_to_byte(unicode_cpt_to_utf8(unicode_sequence));
  11660. }
  11661. return decoded_text;
  11662. }
  11663. // does not write null-terminator to buf
  11664. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  11665. if (0 <= token && token < llama_n_vocab(model)) {
  11666. switch (llama_vocab_get_type(model->vocab)) {
  11667. case LLAMA_VOCAB_TYPE_WPM:
  11668. case LLAMA_VOCAB_TYPE_SPM: {
  11669. // NOTE: we accept all unsupported token types,
  11670. // suppressing them like CONTROL tokens.
  11671. if (llama_is_normal_token(model->vocab, token)) {
  11672. std::string result = model->vocab.id_to_token[token].text;
  11673. llama_unescape_whitespace(result);
  11674. if (length < (int) result.length()) {
  11675. return -(int) result.length();
  11676. }
  11677. memcpy(buf, result.c_str(), result.length());
  11678. return result.length();
  11679. } else if (llama_is_user_defined_token(model->vocab, token)) {
  11680. std::string result = model->vocab.id_to_token[token].text;
  11681. if (length < (int) result.length()) {
  11682. return -(int) result.length();
  11683. }
  11684. memcpy(buf, result.c_str(), result.length());
  11685. return result.length();
  11686. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  11687. if (length < 3) {
  11688. return -3;
  11689. }
  11690. memcpy(buf, "\xe2\x96\x85", 3);
  11691. return 3;
  11692. } else if (llama_is_control_token(model->vocab, token)) {
  11693. ;
  11694. } else if (llama_is_byte_token(model->vocab, token)) {
  11695. if (length < 1) {
  11696. return -1;
  11697. }
  11698. buf[0] = llama_token_to_byte(model->vocab, token);
  11699. return 1;
  11700. }
  11701. break;
  11702. }
  11703. case LLAMA_VOCAB_TYPE_BPE: {
  11704. // NOTE: we accept all unsupported token types,
  11705. // suppressing them like CONTROL tokens.
  11706. if (llama_is_normal_token(model->vocab, token)) {
  11707. std::string result = model->vocab.id_to_token[token].text;
  11708. result = llama_decode_text(result);
  11709. if (length < (int) result.length()) {
  11710. return -(int) result.length();
  11711. }
  11712. memcpy(buf, result.c_str(), result.length());
  11713. return result.length();
  11714. } else if (llama_is_user_defined_token(model->vocab, token)) {
  11715. std::string result = model->vocab.id_to_token[token].text;
  11716. if (length < (int) result.length()) {
  11717. return -(int) result.length();
  11718. }
  11719. memcpy(buf, result.c_str(), result.length());
  11720. return result.length();
  11721. } else if (llama_is_control_token(model->vocab, token)) {
  11722. ;
  11723. }
  11724. break;
  11725. }
  11726. default:
  11727. GGML_ASSERT(false);
  11728. }
  11729. }
  11730. return 0;
  11731. }
  11732. // trim whitespace from the beginning and end of a string
  11733. static std::string trim(const std::string & str) {
  11734. size_t start = 0;
  11735. size_t end = str.size();
  11736. while (start < end && isspace(str[start])) {
  11737. start += 1;
  11738. }
  11739. while (end > start && isspace(str[end - 1])) {
  11740. end -= 1;
  11741. }
  11742. return str.substr(start, end - start);
  11743. }
  11744. // Simple version of "llama_apply_chat_template" that only works with strings
  11745. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  11746. static int32_t llama_chat_apply_template_internal(
  11747. const std::string & tmpl,
  11748. const std::vector<const llama_chat_message *> & chat,
  11749. std::string & dest, bool add_ass) {
  11750. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  11751. std::stringstream ss;
  11752. if (tmpl == "chatml" || tmpl.find("<|im_start|>") != std::string::npos) {
  11753. // chatml template
  11754. for (auto message : chat) {
  11755. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  11756. }
  11757. if (add_ass) {
  11758. ss << "<|im_start|>assistant\n";
  11759. }
  11760. } else if (tmpl == "llama2" || tmpl.find("[INST]") != std::string::npos) {
  11761. // llama2 template and its variants
  11762. // [variant] support system message
  11763. bool support_system_message = tmpl.find("<<SYS>>") != std::string::npos;
  11764. // [variant] space before + after response
  11765. bool space_around_response = tmpl.find("' ' + eos_token") != std::string::npos;
  11766. // [variant] add BOS inside history
  11767. bool add_bos_inside_history = tmpl.find("bos_token + '[INST]") != std::string::npos;
  11768. // [variant] trim spaces from the input message
  11769. bool strip_message = tmpl.find("content.strip()") != std::string::npos;
  11770. // construct the prompt
  11771. bool is_inside_turn = true; // skip BOS at the beginning
  11772. ss << "[INST] ";
  11773. for (auto message : chat) {
  11774. std::string content = strip_message ? trim(message->content) : message->content;
  11775. std::string role(message->role);
  11776. if (!is_inside_turn) {
  11777. is_inside_turn = true;
  11778. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  11779. }
  11780. if (role == "system") {
  11781. if (support_system_message) {
  11782. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  11783. } else {
  11784. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  11785. ss << content << "\n";
  11786. }
  11787. } else if (role == "user") {
  11788. ss << content << " [/INST]";
  11789. } else {
  11790. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  11791. is_inside_turn = false;
  11792. }
  11793. }
  11794. // llama2 templates seem to not care about "add_generation_prompt"
  11795. } else if (tmpl == "zephyr" || tmpl.find("<|user|>") != std::string::npos) {
  11796. // zephyr template
  11797. for (auto message : chat) {
  11798. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  11799. }
  11800. if (add_ass) {
  11801. ss << "<|assistant|>\n";
  11802. }
  11803. } else if (tmpl == "monarch" || tmpl.find("bos_token + message['role']") != std::string::npos) {
  11804. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  11805. for (auto message : chat) {
  11806. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  11807. ss << bos << message->role << "\n" << message->content << "</s>\n";
  11808. }
  11809. if (add_ass) {
  11810. ss << "<s>assistant\n";
  11811. }
  11812. } else if (tmpl == "gemma" || tmpl.find("<start_of_turn>") != std::string::npos) {
  11813. // google/gemma-7b-it
  11814. std::string system_prompt = "";
  11815. for (auto message : chat) {
  11816. std::string role(message->role);
  11817. if (role == "system") {
  11818. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  11819. system_prompt = trim(message->content);
  11820. continue;
  11821. }
  11822. // in gemma, "assistant" is "model"
  11823. role = role == "assistant" ? "model" : message->role;
  11824. ss << "<start_of_turn>" << role << "\n";
  11825. if (!system_prompt.empty() && role != "model") {
  11826. ss << system_prompt << "\n\n";
  11827. system_prompt = "";
  11828. }
  11829. ss << trim(message->content) << "<end_of_turn>\n";
  11830. }
  11831. if (add_ass) {
  11832. ss << "<start_of_turn>model\n";
  11833. }
  11834. } else {
  11835. // template not supported
  11836. return -1;
  11837. }
  11838. dest = ss.str();
  11839. return dest.size();
  11840. }
  11841. LLAMA_API int32_t llama_chat_apply_template(
  11842. const struct llama_model * model,
  11843. const char * tmpl,
  11844. const struct llama_chat_message * chat,
  11845. size_t n_msg,
  11846. bool add_ass,
  11847. char * buf,
  11848. int32_t length) {
  11849. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  11850. if (tmpl == nullptr) {
  11851. GGML_ASSERT(model != nullptr);
  11852. // load template from model
  11853. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  11854. std::string template_key = "tokenizer.chat_template";
  11855. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  11856. if (res < 0) {
  11857. // worst case: there is no information about template, we will use chatml by default
  11858. curr_tmpl = "chatml"; // see llama_chat_apply_template_internal
  11859. } else {
  11860. curr_tmpl = std::string(model_template.data(), model_template.size());
  11861. }
  11862. }
  11863. // format the chat to string
  11864. std::vector<const llama_chat_message *> chat_vec;
  11865. chat_vec.resize(n_msg);
  11866. for (size_t i = 0; i < n_msg; i++) {
  11867. chat_vec[i] = &chat[i];
  11868. }
  11869. std::string formatted_chat;
  11870. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  11871. if (res < 0) {
  11872. return res;
  11873. }
  11874. if (buf && length > 0) {
  11875. strncpy(buf, formatted_chat.c_str(), length);
  11876. }
  11877. return res;
  11878. }
  11879. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  11880. struct llama_timings result = {
  11881. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  11882. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  11883. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  11884. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  11885. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  11886. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  11887. /*.n_sample =*/ std::max(1, ctx->n_sample),
  11888. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  11889. /*.n_eval =*/ std::max(1, ctx->n_eval),
  11890. };
  11891. return result;
  11892. }
  11893. void llama_print_timings(struct llama_context * ctx) {
  11894. const llama_timings timings = llama_get_timings(ctx);
  11895. LLAMA_LOG_INFO("\n");
  11896. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  11897. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  11898. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  11899. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  11900. __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);
  11901. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  11902. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  11903. LLAMA_LOG_INFO("%s: total time = %10.2f ms / %5d tokens\n", __func__, (timings.t_end_ms - timings.t_start_ms), (timings.n_p_eval + timings.n_eval));
  11904. }
  11905. void llama_reset_timings(struct llama_context * ctx) {
  11906. ctx->t_start_us = ggml_time_us();
  11907. ctx->t_sample_us = ctx->n_sample = 0;
  11908. ctx->t_eval_us = ctx->n_eval = 0;
  11909. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  11910. }
  11911. const char * llama_print_system_info(void) {
  11912. static std::string s;
  11913. s = "";
  11914. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  11915. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  11916. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  11917. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  11918. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  11919. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  11920. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  11921. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  11922. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  11923. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  11924. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  11925. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  11926. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  11927. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  11928. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  11929. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  11930. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  11931. return s.c_str();
  11932. }
  11933. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  11934. fprintf(stream, "\n");
  11935. fprintf(stream, "###########\n");
  11936. fprintf(stream, "# Timings #\n");
  11937. fprintf(stream, "###########\n");
  11938. fprintf(stream, "\n");
  11939. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  11940. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  11941. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  11942. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  11943. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  11944. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  11945. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  11946. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  11947. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  11948. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  11949. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  11950. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  11951. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  11952. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  11953. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  11954. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  11955. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  11956. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  11957. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  11958. }
  11959. // For internal test use
  11960. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  11961. struct llama_context * ctx
  11962. ) {
  11963. return ctx->model.tensors_by_name;
  11964. }
  11965. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  11966. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  11967. g_state.log_callback_user_data = user_data;
  11968. #ifdef GGML_USE_METAL
  11969. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  11970. #endif
  11971. }
  11972. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  11973. va_list args_copy;
  11974. va_copy(args_copy, args);
  11975. char buffer[128];
  11976. int len = vsnprintf(buffer, 128, format, args);
  11977. if (len < 128) {
  11978. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  11979. } else {
  11980. char* buffer2 = new char[len+1];
  11981. vsnprintf(buffer2, len+1, format, args_copy);
  11982. buffer2[len] = 0;
  11983. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  11984. delete[] buffer2;
  11985. }
  11986. va_end(args_copy);
  11987. }
  11988. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  11989. va_list args;
  11990. va_start(args, format);
  11991. llama_log_internal_v(level, format, args);
  11992. va_end(args);
  11993. }
  11994. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  11995. (void) level;
  11996. (void) user_data;
  11997. fputs(text, stderr);
  11998. fflush(stderr);
  11999. }