llama.cpp 971 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228
  1. /**
  2. * llama.cpp - commit 40c6d79fb52f995f47507fedfeaae2ac05d9b35c - do not edit this file
  3. *
  4. * MIT License
  5. *
  6. * Copyright (c) 2023-2024 The ggml authors
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all
  16. * copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  24. * SOFTWARE.
  25. */
  26. #include "llama-impl.h"
  27. #include "llama-vocab.h"
  28. #include "llama-sampling.h"
  29. #include "unicode.h"
  30. #include "ggml.h"
  31. #include "ggml-alloc.h"
  32. #include "ggml-backend.h"
  33. #include "ggml-cpp.h"
  34. // TODO: replace with ggml API call
  35. #define QK_K 256
  36. #ifdef __has_include
  37. #if __has_include(<unistd.h>)
  38. #include <unistd.h>
  39. #if defined(_POSIX_MAPPED_FILES)
  40. #include <sys/mman.h>
  41. #include <fcntl.h>
  42. #endif
  43. #if defined(_POSIX_MEMLOCK_RANGE)
  44. #include <sys/resource.h>
  45. #endif
  46. #endif
  47. #endif
  48. #if defined(_WIN32)
  49. #define WIN32_LEAN_AND_MEAN
  50. #ifndef NOMINMAX
  51. #define NOMINMAX
  52. #endif
  53. #include <windows.h>
  54. #ifndef PATH_MAX
  55. #define PATH_MAX MAX_PATH
  56. #endif
  57. #include <io.h>
  58. #endif
  59. #if __cplusplus >= 202000L
  60. #define LU8(x) (const char*)(u8##x)
  61. #else
  62. #define LU8(x) u8##x
  63. #endif
  64. #include <algorithm>
  65. #include <array>
  66. #include <cassert>
  67. #include <cctype>
  68. #include <cfloat>
  69. #include <cinttypes>
  70. #include <climits>
  71. #include <cmath>
  72. #include <cstdarg>
  73. #include <cstddef>
  74. #include <cstdint>
  75. #include <cstdio>
  76. #include <cstring>
  77. #include <ctime>
  78. #include <fstream>
  79. #include <functional>
  80. #include <future>
  81. #include <initializer_list>
  82. #include <locale>
  83. #include <map>
  84. #include <memory>
  85. #include <mutex>
  86. #include <numeric>
  87. #include <set>
  88. #include <sstream>
  89. #include <thread>
  90. #include <type_traits>
  91. #include <unordered_map>
  92. #if defined(_MSC_VER)
  93. #pragma warning(disable: 4244 4267) // possible loss of data
  94. #endif
  95. // bump if necessary
  96. #define LLAMA_MAX_LAYERS 512
  97. #define LLAMA_MAX_EXPERTS 160 // DeepSeekV2
  98. //
  99. // helpers
  100. //
  101. // trim whitespace from the beginning and end of a string
  102. static std::string trim(const std::string & str) {
  103. size_t start = 0;
  104. size_t end = str.size();
  105. while (start < end && isspace(str[start])) {
  106. start += 1;
  107. }
  108. while (end > start && isspace(str[end - 1])) {
  109. end -= 1;
  110. }
  111. return str.substr(start, end - start);
  112. }
  113. static bool is_float_close(float a, float b, float abs_tol) {
  114. // Check for non-negative tolerance
  115. if (abs_tol < 0.0) {
  116. throw std::invalid_argument("Tolerance must be non-negative");
  117. }
  118. // Exact equality check
  119. if (a == b) {
  120. return true;
  121. }
  122. // Check for infinities
  123. if (std::isinf(a) || std::isinf(b)) {
  124. return false;
  125. }
  126. // Regular comparison using the provided absolute tolerance
  127. return std::fabs(b - a) <= abs_tol;
  128. }
  129. static void zeros(std::ofstream & file, size_t n) {
  130. char zero = 0;
  131. for (size_t i = 0; i < n; ++i) {
  132. file.write(&zero, 1);
  133. }
  134. }
  135. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  136. static std::string format(const char * fmt, ...) {
  137. va_list ap;
  138. va_list ap2;
  139. va_start(ap, fmt);
  140. va_copy(ap2, ap);
  141. int size = vsnprintf(NULL, 0, fmt, ap);
  142. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  143. std::vector<char> buf(size + 1);
  144. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  145. GGML_ASSERT(size2 == size);
  146. va_end(ap2);
  147. va_end(ap);
  148. return std::string(buf.data(), size);
  149. }
  150. //
  151. // gguf constants (sync with gguf.py)
  152. //
  153. enum llm_arch {
  154. LLM_ARCH_LLAMA,
  155. LLM_ARCH_MLLAMA,
  156. LLM_ARCH_FALCON,
  157. LLM_ARCH_BAICHUAN,
  158. LLM_ARCH_GROK,
  159. LLM_ARCH_GPT2,
  160. LLM_ARCH_GPTJ,
  161. LLM_ARCH_GPTNEOX,
  162. LLM_ARCH_MPT,
  163. LLM_ARCH_STARCODER,
  164. LLM_ARCH_REFACT,
  165. LLM_ARCH_BERT,
  166. LLM_ARCH_NOMIC_BERT,
  167. LLM_ARCH_JINA_BERT_V2,
  168. LLM_ARCH_BLOOM,
  169. LLM_ARCH_STABLELM,
  170. LLM_ARCH_QWEN,
  171. LLM_ARCH_QWEN2,
  172. LLM_ARCH_QWEN2MOE,
  173. LLM_ARCH_PHI2,
  174. LLM_ARCH_PHI3,
  175. LLM_ARCH_PLAMO,
  176. LLM_ARCH_CODESHELL,
  177. LLM_ARCH_ORION,
  178. LLM_ARCH_INTERNLM2,
  179. LLM_ARCH_MINICPM,
  180. LLM_ARCH_MINICPM3,
  181. LLM_ARCH_GEMMA,
  182. LLM_ARCH_GEMMA2,
  183. LLM_ARCH_STARCODER2,
  184. LLM_ARCH_MAMBA,
  185. LLM_ARCH_XVERSE,
  186. LLM_ARCH_COMMAND_R,
  187. LLM_ARCH_DBRX,
  188. LLM_ARCH_OLMO,
  189. LLM_ARCH_OLMO2,
  190. LLM_ARCH_OLMOE,
  191. LLM_ARCH_OPENELM,
  192. LLM_ARCH_ARCTIC,
  193. LLM_ARCH_DEEPSEEK2,
  194. LLM_ARCH_CHATGLM,
  195. LLM_ARCH_BITNET,
  196. LLM_ARCH_T5,
  197. LLM_ARCH_T5ENCODER,
  198. LLM_ARCH_JAIS,
  199. LLM_ARCH_NEMOTRON,
  200. LLM_ARCH_EXAONE,
  201. LLM_ARCH_RWKV6,
  202. LLM_ARCH_GRANITE,
  203. LLM_ARCH_GRANITE_MOE,
  204. LLM_ARCH_CHAMELEON,
  205. LLM_ARCH_SOLAR,
  206. LLM_ARCH_UNKNOWN,
  207. };
  208. static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  209. { LLM_ARCH_LLAMA, "llama" },
  210. { LLM_ARCH_MLLAMA, "mllama" },
  211. { LLM_ARCH_FALCON, "falcon" },
  212. { LLM_ARCH_GROK, "grok" },
  213. { LLM_ARCH_GPT2, "gpt2" },
  214. { LLM_ARCH_GPTJ, "gptj" },
  215. { LLM_ARCH_GPTNEOX, "gptneox" },
  216. { LLM_ARCH_MPT, "mpt" },
  217. { LLM_ARCH_BAICHUAN, "baichuan" },
  218. { LLM_ARCH_STARCODER, "starcoder" },
  219. { LLM_ARCH_REFACT, "refact" },
  220. { LLM_ARCH_BERT, "bert" },
  221. { LLM_ARCH_NOMIC_BERT, "nomic-bert" },
  222. { LLM_ARCH_JINA_BERT_V2, "jina-bert-v2" },
  223. { LLM_ARCH_BLOOM, "bloom" },
  224. { LLM_ARCH_STABLELM, "stablelm" },
  225. { LLM_ARCH_QWEN, "qwen" },
  226. { LLM_ARCH_QWEN2, "qwen2" },
  227. { LLM_ARCH_QWEN2MOE, "qwen2moe" },
  228. { LLM_ARCH_PHI2, "phi2" },
  229. { LLM_ARCH_PHI3, "phi3" },
  230. { LLM_ARCH_PLAMO, "plamo" },
  231. { LLM_ARCH_CODESHELL, "codeshell" },
  232. { LLM_ARCH_ORION, "orion" },
  233. { LLM_ARCH_INTERNLM2, "internlm2" },
  234. { LLM_ARCH_MINICPM, "minicpm" },
  235. { LLM_ARCH_MINICPM3, "minicpm3" },
  236. { LLM_ARCH_GEMMA, "gemma" },
  237. { LLM_ARCH_GEMMA2, "gemma2" },
  238. { LLM_ARCH_STARCODER2, "starcoder2" },
  239. { LLM_ARCH_MAMBA, "mamba" },
  240. { LLM_ARCH_XVERSE, "xverse" },
  241. { LLM_ARCH_COMMAND_R, "command-r" },
  242. { LLM_ARCH_DBRX, "dbrx" },
  243. { LLM_ARCH_OLMO, "olmo" },
  244. { LLM_ARCH_OLMO2, "olmo2" },
  245. { LLM_ARCH_OLMOE, "olmoe" },
  246. { LLM_ARCH_OPENELM, "openelm" },
  247. { LLM_ARCH_ARCTIC, "arctic" },
  248. { LLM_ARCH_DEEPSEEK2, "deepseek2" },
  249. { LLM_ARCH_CHATGLM, "chatglm" },
  250. { LLM_ARCH_BITNET, "bitnet" },
  251. { LLM_ARCH_T5, "t5" },
  252. { LLM_ARCH_T5ENCODER, "t5encoder" },
  253. { LLM_ARCH_JAIS, "jais" },
  254. { LLM_ARCH_NEMOTRON, "nemotron" },
  255. { LLM_ARCH_EXAONE, "exaone" },
  256. { LLM_ARCH_RWKV6, "rwkv6" },
  257. { LLM_ARCH_GRANITE, "granite" },
  258. { LLM_ARCH_GRANITE_MOE, "granitemoe" },
  259. { LLM_ARCH_CHAMELEON, "chameleon" },
  260. { LLM_ARCH_SOLAR, "solar" },
  261. { LLM_ARCH_UNKNOWN, "(unknown)" },
  262. };
  263. enum llm_kv {
  264. LLM_KV_GENERAL_TYPE,
  265. LLM_KV_GENERAL_ARCHITECTURE,
  266. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  267. LLM_KV_GENERAL_ALIGNMENT,
  268. LLM_KV_GENERAL_NAME,
  269. LLM_KV_GENERAL_AUTHOR,
  270. LLM_KV_GENERAL_VERSION,
  271. LLM_KV_GENERAL_URL,
  272. LLM_KV_GENERAL_DESCRIPTION,
  273. LLM_KV_GENERAL_LICENSE,
  274. LLM_KV_GENERAL_SOURCE_URL,
  275. LLM_KV_GENERAL_SOURCE_HF_REPO,
  276. LLM_KV_VOCAB_SIZE,
  277. LLM_KV_CONTEXT_LENGTH,
  278. LLM_KV_EMBEDDING_LENGTH,
  279. LLM_KV_BLOCK_COUNT,
  280. LLM_KV_LEADING_DENSE_BLOCK_COUNT,
  281. LLM_KV_FEED_FORWARD_LENGTH,
  282. LLM_KV_EXPERT_FEED_FORWARD_LENGTH,
  283. LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH,
  284. LLM_KV_USE_PARALLEL_RESIDUAL,
  285. LLM_KV_TENSOR_DATA_LAYOUT,
  286. LLM_KV_EXPERT_COUNT,
  287. LLM_KV_EXPERT_USED_COUNT,
  288. LLM_KV_EXPERT_SHARED_COUNT,
  289. LLM_KV_EXPERT_WEIGHTS_SCALE,
  290. LLM_KV_POOLING_TYPE,
  291. LLM_KV_LOGIT_SCALE,
  292. LLM_KV_DECODER_START_TOKEN_ID,
  293. LLM_KV_ATTN_LOGIT_SOFTCAPPING,
  294. LLM_KV_FINAL_LOGIT_SOFTCAPPING,
  295. LLM_KV_SWIN_NORM,
  296. LLM_KV_RESCALE_EVERY_N_LAYERS,
  297. LLM_KV_TIME_MIX_EXTRA_DIM,
  298. LLM_KV_TIME_DECAY_EXTRA_DIM,
  299. LLM_KV_RESIDUAL_SCALE,
  300. LLM_KV_EMBEDDING_SCALE,
  301. LLM_KV_ATTENTION_HEAD_COUNT,
  302. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  303. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  304. LLM_KV_ATTENTION_CLAMP_KQV,
  305. LLM_KV_ATTENTION_KEY_LENGTH,
  306. LLM_KV_ATTENTION_VALUE_LENGTH,
  307. LLM_KV_ATTENTION_LAYERNORM_EPS,
  308. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  309. LLM_KV_ATTENTION_CAUSAL,
  310. LLM_KV_ATTENTION_Q_LORA_RANK,
  311. LLM_KV_ATTENTION_KV_LORA_RANK,
  312. LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT,
  313. LLM_KV_ATTENTION_SLIDING_WINDOW,
  314. LLM_KV_ATTENTION_SCALE,
  315. LLM_KV_ATTENTION_BLOCK_SKIP_CONNECTION,
  316. LLM_KV_ATTENTION_CROSS_ATTENTION_LAYERS,
  317. LLM_KV_ROPE_DIMENSION_COUNT,
  318. LLM_KV_ROPE_FREQ_BASE,
  319. LLM_KV_ROPE_SCALE_LINEAR,
  320. LLM_KV_ROPE_SCALING_TYPE,
  321. LLM_KV_ROPE_SCALING_FACTOR,
  322. LLM_KV_ROPE_SCALING_ATTN_FACTOR,
  323. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  324. LLM_KV_ROPE_SCALING_FINETUNED,
  325. LLM_KV_ROPE_SCALING_YARN_LOG_MUL,
  326. LLM_KV_SPLIT_NO,
  327. LLM_KV_SPLIT_COUNT,
  328. LLM_KV_SPLIT_TENSORS_COUNT,
  329. LLM_KV_SSM_INNER_SIZE,
  330. LLM_KV_SSM_CONV_KERNEL,
  331. LLM_KV_SSM_STATE_SIZE,
  332. LLM_KV_SSM_TIME_STEP_RANK,
  333. LLM_KV_SSM_DT_B_C_RMS,
  334. LLM_KV_WKV_HEAD_SIZE,
  335. LLM_KV_TOKENIZER_MODEL,
  336. LLM_KV_TOKENIZER_PRE,
  337. LLM_KV_TOKENIZER_LIST,
  338. LLM_KV_TOKENIZER_TOKEN_TYPE,
  339. LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT,
  340. LLM_KV_TOKENIZER_SCORES,
  341. LLM_KV_TOKENIZER_MERGES,
  342. LLM_KV_TOKENIZER_BOS_ID,
  343. LLM_KV_TOKENIZER_EOS_ID,
  344. LLM_KV_TOKENIZER_EOT_ID,
  345. LLM_KV_TOKENIZER_EOM_ID,
  346. LLM_KV_TOKENIZER_UNK_ID,
  347. LLM_KV_TOKENIZER_SEP_ID,
  348. LLM_KV_TOKENIZER_PAD_ID,
  349. LLM_KV_TOKENIZER_CLS_ID,
  350. LLM_KV_TOKENIZER_MASK_ID,
  351. LLM_KV_TOKENIZER_ADD_BOS,
  352. LLM_KV_TOKENIZER_ADD_EOS,
  353. LLM_KV_TOKENIZER_ADD_PREFIX,
  354. LLM_KV_TOKENIZER_REMOVE_EXTRA_WS,
  355. LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP,
  356. LLM_KV_TOKENIZER_HF_JSON,
  357. LLM_KV_TOKENIZER_RWKV,
  358. LLM_KV_TOKENIZER_FIM_PRE_ID,
  359. LLM_KV_TOKENIZER_FIM_SUF_ID,
  360. LLM_KV_TOKENIZER_FIM_MID_ID,
  361. LLM_KV_TOKENIZER_FIM_PAD_ID,
  362. LLM_KV_TOKENIZER_FIM_REP_ID,
  363. LLM_KV_TOKENIZER_FIM_SEP_ID,
  364. LLM_KV_ADAPTER_TYPE,
  365. LLM_KV_ADAPTER_LORA_ALPHA,
  366. // deprecated:
  367. LLM_KV_TOKENIZER_PREFIX_ID,
  368. LLM_KV_TOKENIZER_SUFFIX_ID,
  369. LLM_KV_TOKENIZER_MIDDLE_ID,
  370. };
  371. static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
  372. { LLM_KV_GENERAL_TYPE, "general.type" },
  373. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  374. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  375. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  376. { LLM_KV_GENERAL_NAME, "general.name" },
  377. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  378. { LLM_KV_GENERAL_VERSION, "general.version" },
  379. { LLM_KV_GENERAL_URL, "general.url" },
  380. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  381. { LLM_KV_GENERAL_LICENSE, "general.license" },
  382. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  383. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  384. { LLM_KV_VOCAB_SIZE, "%s.vocab_size" },
  385. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  386. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  387. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  388. { LLM_KV_LEADING_DENSE_BLOCK_COUNT, "%s.leading_dense_block_count" },
  389. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  390. { LLM_KV_EXPERT_FEED_FORWARD_LENGTH, "%s.expert_feed_forward_length" },
  391. { LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, "%s.expert_shared_feed_forward_length" },
  392. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  393. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  394. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  395. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  396. { LLM_KV_EXPERT_SHARED_COUNT, "%s.expert_shared_count" },
  397. { LLM_KV_EXPERT_WEIGHTS_SCALE, "%s.expert_weights_scale" },
  398. { LLM_KV_POOLING_TYPE, "%s.pooling_type" },
  399. { LLM_KV_LOGIT_SCALE, "%s.logit_scale" },
  400. { LLM_KV_DECODER_START_TOKEN_ID, "%s.decoder_start_token_id" },
  401. { LLM_KV_ATTN_LOGIT_SOFTCAPPING, "%s.attn_logit_softcapping" },
  402. { LLM_KV_FINAL_LOGIT_SOFTCAPPING, "%s.final_logit_softcapping" },
  403. { LLM_KV_SWIN_NORM, "%s.swin_norm" },
  404. { LLM_KV_RESCALE_EVERY_N_LAYERS, "%s.rescale_every_n_layers" },
  405. { LLM_KV_TIME_MIX_EXTRA_DIM, "%s.time_mix_extra_dim" },
  406. { LLM_KV_TIME_DECAY_EXTRA_DIM, "%s.time_decay_extra_dim" },
  407. { LLM_KV_RESIDUAL_SCALE, "%s.residual_scale" },
  408. { LLM_KV_EMBEDDING_SCALE, "%s.embedding_scale" },
  409. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  410. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  411. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  412. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  413. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  414. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  415. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  416. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  417. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  418. { LLM_KV_ATTENTION_Q_LORA_RANK, "%s.attention.q_lora_rank" },
  419. { LLM_KV_ATTENTION_KV_LORA_RANK, "%s.attention.kv_lora_rank" },
  420. { LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, "%s.attention.relative_buckets_count" },
  421. { LLM_KV_ATTENTION_SLIDING_WINDOW, "%s.attention.sliding_window" },
  422. { LLM_KV_ATTENTION_SCALE, "%s.attention.scale" },
  423. { LLM_KV_ATTENTION_BLOCK_SKIP_CONNECTION, "%s.attention.block_skip_connection.%d" },
  424. { LLM_KV_ATTENTION_CROSS_ATTENTION_LAYERS, "%s.attention.cross_attention_layers" },
  425. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  426. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  427. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  428. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  429. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  430. { LLM_KV_ROPE_SCALING_ATTN_FACTOR, "%s.rope.scaling.attn_factor" },
  431. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  432. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  433. { LLM_KV_ROPE_SCALING_YARN_LOG_MUL, "%s.rope.scaling.yarn_log_multiplier" },
  434. { LLM_KV_SPLIT_NO, "split.no" },
  435. { LLM_KV_SPLIT_COUNT, "split.count" },
  436. { LLM_KV_SPLIT_TENSORS_COUNT, "split.tensors.count" },
  437. { LLM_KV_SSM_CONV_KERNEL, "%s.ssm.conv_kernel" },
  438. { LLM_KV_SSM_INNER_SIZE, "%s.ssm.inner_size" },
  439. { LLM_KV_SSM_STATE_SIZE, "%s.ssm.state_size" },
  440. { LLM_KV_SSM_TIME_STEP_RANK, "%s.ssm.time_step_rank" },
  441. { LLM_KV_SSM_DT_B_C_RMS, "%s.ssm.dt_b_c_rms" },
  442. { LLM_KV_WKV_HEAD_SIZE, "%s.wkv.head_size" },
  443. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  444. { LLM_KV_TOKENIZER_PRE, "tokenizer.ggml.pre" },
  445. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  446. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  447. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  448. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  449. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  450. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  451. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  452. { LLM_KV_TOKENIZER_EOT_ID, "tokenizer.ggml.eot_token_id" },
  453. { LLM_KV_TOKENIZER_EOM_ID, "tokenizer.ggml.eom_token_id" },
  454. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  455. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  456. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  457. { LLM_KV_TOKENIZER_CLS_ID, "tokenizer.ggml.cls_token_id" },
  458. { LLM_KV_TOKENIZER_MASK_ID, "tokenizer.ggml.mask_token_id" },
  459. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  460. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  461. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  462. { LLM_KV_TOKENIZER_REMOVE_EXTRA_WS, "tokenizer.ggml.remove_extra_whitespaces" },
  463. { LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP, "tokenizer.ggml.precompiled_charsmap" },
  464. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  465. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  466. { LLM_KV_TOKENIZER_FIM_PRE_ID, "tokenizer.ggml.fim_pre_token_id" },
  467. { LLM_KV_TOKENIZER_FIM_SUF_ID, "tokenizer.ggml.fim_suf_token_id" },
  468. { LLM_KV_TOKENIZER_FIM_MID_ID, "tokenizer.ggml.fim_mid_token_id" },
  469. { LLM_KV_TOKENIZER_FIM_PAD_ID, "tokenizer.ggml.fim_pad_token_id" },
  470. { LLM_KV_TOKENIZER_FIM_REP_ID, "tokenizer.ggml.fim_rep_token_id" },
  471. { LLM_KV_TOKENIZER_FIM_SEP_ID, "tokenizer.ggml.fim_sep_token_id" },
  472. { LLM_KV_ADAPTER_TYPE, "adapter.type" },
  473. { LLM_KV_ADAPTER_LORA_ALPHA, "adapter.lora.alpha" },
  474. // deprecated
  475. { LLM_KV_TOKENIZER_PREFIX_ID, "tokenizer.ggml.prefix_token_id" },
  476. { LLM_KV_TOKENIZER_SUFFIX_ID, "tokenizer.ggml.suffix_token_id" },
  477. { LLM_KV_TOKENIZER_MIDDLE_ID, "tokenizer.ggml.middle_token_id" },
  478. };
  479. struct LLM_KV {
  480. LLM_KV(llm_arch arch) : arch(arch) {}
  481. llm_arch arch;
  482. std::string operator()(llm_kv kv) const {
  483. return ::format(LLM_KV_NAMES.at(kv), LLM_ARCH_NAMES.at(arch));
  484. }
  485. };
  486. enum llm_tensor {
  487. LLM_TENSOR_TOKEN_EMBD,
  488. LLM_TENSOR_TOKEN_EMBD_NORM,
  489. LLM_TENSOR_TOKEN_TYPES,
  490. LLM_TENSOR_POS_EMBD,
  491. LLM_TENSOR_OUTPUT,
  492. LLM_TENSOR_OUTPUT_NORM,
  493. LLM_TENSOR_ROPE_FREQS,
  494. LLM_TENSOR_ROPE_FACTORS_LONG,
  495. LLM_TENSOR_ROPE_FACTORS_SHORT,
  496. LLM_TENSOR_ATTN_Q,
  497. LLM_TENSOR_ATTN_K,
  498. LLM_TENSOR_ATTN_V,
  499. LLM_TENSOR_ATTN_QKV,
  500. LLM_TENSOR_ATTN_OUT,
  501. LLM_TENSOR_ATTN_NORM,
  502. LLM_TENSOR_ATTN_NORM_2,
  503. LLM_TENSOR_ATTN_OUT_NORM,
  504. LLM_TENSOR_ATTN_POST_NORM,
  505. LLM_TENSOR_ATTN_ROT_EMBD,
  506. LLM_TENSOR_FFN_GATE_INP,
  507. LLM_TENSOR_FFN_GATE_INP_SHEXP,
  508. LLM_TENSOR_FFN_NORM,
  509. LLM_TENSOR_FFN_POST_NORM,
  510. LLM_TENSOR_FFN_GATE,
  511. LLM_TENSOR_FFN_DOWN,
  512. LLM_TENSOR_FFN_UP,
  513. LLM_TENSOR_FFN_ACT,
  514. LLM_TENSOR_FFN_DOWN_EXP, // split experts for backward compatibility
  515. LLM_TENSOR_FFN_GATE_EXP,
  516. LLM_TENSOR_FFN_UP_EXP,
  517. LLM_TENSOR_FFN_NORM_EXPS,
  518. LLM_TENSOR_FFN_DOWN_EXPS, // merged experts
  519. LLM_TENSOR_FFN_GATE_EXPS,
  520. LLM_TENSOR_FFN_UP_EXPS,
  521. LLM_TENSOR_FFN_DOWN_SHEXP,
  522. LLM_TENSOR_FFN_GATE_SHEXP,
  523. LLM_TENSOR_FFN_UP_SHEXP,
  524. LLM_TENSOR_ATTN_Q_NORM,
  525. LLM_TENSOR_ATTN_K_NORM,
  526. LLM_TENSOR_LAYER_OUT_NORM,
  527. LLM_TENSOR_SSM_IN,
  528. LLM_TENSOR_SSM_CONV1D,
  529. LLM_TENSOR_SSM_X,
  530. LLM_TENSOR_SSM_DT,
  531. LLM_TENSOR_SSM_A,
  532. LLM_TENSOR_SSM_D,
  533. LLM_TENSOR_SSM_OUT,
  534. LLM_TENSOR_TIME_MIX_W1,
  535. LLM_TENSOR_TIME_MIX_W2,
  536. LLM_TENSOR_TIME_MIX_LERP_X,
  537. LLM_TENSOR_TIME_MIX_LERP_W,
  538. LLM_TENSOR_TIME_MIX_LERP_K,
  539. LLM_TENSOR_TIME_MIX_LERP_V,
  540. LLM_TENSOR_TIME_MIX_LERP_R,
  541. LLM_TENSOR_TIME_MIX_LERP_G,
  542. LLM_TENSOR_TIME_MIX_FIRST,
  543. LLM_TENSOR_TIME_MIX_DECAY,
  544. LLM_TENSOR_TIME_MIX_DECAY_W1,
  545. LLM_TENSOR_TIME_MIX_DECAY_W2,
  546. LLM_TENSOR_TIME_MIX_KEY,
  547. LLM_TENSOR_TIME_MIX_VALUE,
  548. LLM_TENSOR_TIME_MIX_RECEPTANCE,
  549. LLM_TENSOR_TIME_MIX_GATE,
  550. LLM_TENSOR_TIME_MIX_LN,
  551. LLM_TENSOR_TIME_MIX_OUTPUT,
  552. LLM_TENSOR_CHANNEL_MIX_LERP_K,
  553. LLM_TENSOR_CHANNEL_MIX_LERP_R,
  554. LLM_TENSOR_CHANNEL_MIX_KEY,
  555. LLM_TENSOR_CHANNEL_MIX_RECEPTANCE,
  556. LLM_TENSOR_CHANNEL_MIX_VALUE,
  557. LLM_TENSOR_ATTN_Q_A,
  558. LLM_TENSOR_ATTN_Q_B,
  559. LLM_TENSOR_ATTN_KV_A_MQA,
  560. LLM_TENSOR_ATTN_KV_B,
  561. LLM_TENSOR_ATTN_Q_A_NORM,
  562. LLM_TENSOR_ATTN_KV_A_NORM,
  563. LLM_TENSOR_ATTN_SUB_NORM,
  564. LLM_TENSOR_FFN_SUB_NORM,
  565. LLM_TENSOR_DEC_ATTN_NORM,
  566. LLM_TENSOR_DEC_ATTN_Q,
  567. LLM_TENSOR_DEC_ATTN_K,
  568. LLM_TENSOR_DEC_ATTN_V,
  569. LLM_TENSOR_DEC_ATTN_OUT,
  570. LLM_TENSOR_DEC_ATTN_REL_B,
  571. LLM_TENSOR_DEC_CROSS_ATTN_NORM,
  572. LLM_TENSOR_DEC_CROSS_ATTN_Q,
  573. LLM_TENSOR_DEC_CROSS_ATTN_K,
  574. LLM_TENSOR_DEC_CROSS_ATTN_V,
  575. LLM_TENSOR_DEC_CROSS_ATTN_OUT,
  576. LLM_TENSOR_DEC_CROSS_ATTN_REL_B,
  577. LLM_TENSOR_DEC_FFN_NORM,
  578. LLM_TENSOR_DEC_FFN_GATE,
  579. LLM_TENSOR_DEC_FFN_DOWN,
  580. LLM_TENSOR_DEC_FFN_UP,
  581. LLM_TENSOR_DEC_OUTPUT_NORM,
  582. LLM_TENSOR_ENC_ATTN_NORM,
  583. LLM_TENSOR_ENC_ATTN_Q,
  584. LLM_TENSOR_ENC_ATTN_K,
  585. LLM_TENSOR_ENC_ATTN_V,
  586. LLM_TENSOR_ENC_ATTN_OUT,
  587. LLM_TENSOR_ENC_ATTN_REL_B,
  588. LLM_TENSOR_ENC_FFN_NORM,
  589. LLM_TENSOR_ENC_FFN_GATE,
  590. LLM_TENSOR_ENC_FFN_DOWN,
  591. LLM_TENSOR_ENC_FFN_UP,
  592. LLM_TENSOR_ENC_OUTPUT_NORM,
  593. LLM_TENSOR_CLS,
  594. LLM_TENSOR_CLS_OUT,
  595. LLM_TENSOR_BSKCN_TV,
  596. LLM_TENSOR_CROSS_ATTN_K_NORM,
  597. LLM_TENSOR_CROSS_ATTN_K_PROJ,
  598. LLM_TENSOR_CROSS_ATTN_O_PROJ,
  599. LLM_TENSOR_CROSS_ATTN_Q_NORM,
  600. LLM_TENSOR_CROSS_ATTN_Q_PROJ,
  601. LLM_TENSOR_CROSS_ATTN_V_PROJ,
  602. LLM_TENSOR_CROSS_ATTN_ATTN_GATE,
  603. LLM_TENSOR_CROSS_ATTN_MLP_GATE,
  604. };
  605. static const std::map<llm_arch, std::map<llm_tensor, const char *>> LLM_TENSOR_NAMES = {
  606. {
  607. LLM_ARCH_LLAMA,
  608. {
  609. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  610. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  611. { LLM_TENSOR_OUTPUT, "output" },
  612. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  613. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  614. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  615. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  616. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  617. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  618. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  619. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  620. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  621. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  622. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  623. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  624. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  625. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  626. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  627. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  628. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  629. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  630. },
  631. },
  632. {
  633. LLM_ARCH_MLLAMA,
  634. {
  635. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  636. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  637. { LLM_TENSOR_OUTPUT, "output" },
  638. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  639. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  640. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  641. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  642. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  643. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  644. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  645. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  646. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  647. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  648. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  649. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  650. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  651. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  652. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  653. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  654. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  655. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  656. { LLM_TENSOR_CROSS_ATTN_K_NORM, "blk.%d.cross_attn_k_norm" },
  657. { LLM_TENSOR_CROSS_ATTN_K_PROJ, "blk.%d.cross_attn_k_proj" },
  658. { LLM_TENSOR_CROSS_ATTN_O_PROJ, "blk.%d.cross_attn_o_proj" },
  659. { LLM_TENSOR_CROSS_ATTN_Q_NORM, "blk.%d.cross_attn_q_norm" },
  660. { LLM_TENSOR_CROSS_ATTN_Q_PROJ, "blk.%d.cross_attn_q_proj" },
  661. { LLM_TENSOR_CROSS_ATTN_V_PROJ, "blk.%d.cross_attn_v_proj" },
  662. { LLM_TENSOR_CROSS_ATTN_ATTN_GATE, "blk.%d.cross_attn_attn_gate" },
  663. { LLM_TENSOR_CROSS_ATTN_MLP_GATE, "blk.%d.cross_attn_mlp_gate" },
  664. },
  665. },
  666. {
  667. LLM_ARCH_BAICHUAN,
  668. {
  669. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  670. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  671. { LLM_TENSOR_OUTPUT, "output" },
  672. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  673. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  674. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  675. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  676. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  677. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  678. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  679. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  680. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  681. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  682. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  683. },
  684. },
  685. {
  686. LLM_ARCH_FALCON,
  687. {
  688. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  689. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  690. { LLM_TENSOR_OUTPUT, "output" },
  691. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  692. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  693. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  694. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  695. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  696. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  697. },
  698. },
  699. {
  700. LLM_ARCH_GROK,
  701. {
  702. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  703. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  704. { LLM_TENSOR_OUTPUT, "output" },
  705. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  706. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  707. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  708. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  709. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  710. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  711. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  712. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  713. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  714. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  715. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  716. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  717. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  718. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  719. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  720. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  721. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  722. },
  723. },
  724. {
  725. LLM_ARCH_GPT2,
  726. {
  727. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  728. { LLM_TENSOR_POS_EMBD, "position_embd" },
  729. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  730. { LLM_TENSOR_OUTPUT, "output" },
  731. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  732. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  733. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  734. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  735. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  736. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  737. },
  738. },
  739. {
  740. LLM_ARCH_GPTJ,
  741. {
  742. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  743. },
  744. },
  745. {
  746. LLM_ARCH_GPTNEOX,
  747. {
  748. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  749. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  750. { LLM_TENSOR_OUTPUT, "output" },
  751. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  752. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  753. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  754. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  755. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  756. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  757. },
  758. },
  759. {
  760. LLM_ARCH_MPT,
  761. {
  762. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  763. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  764. { LLM_TENSOR_OUTPUT, "output"},
  765. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  766. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  767. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  768. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  769. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  770. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  771. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  772. { LLM_TENSOR_POS_EMBD, "position_embd" },
  773. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  774. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  775. },
  776. },
  777. {
  778. LLM_ARCH_STARCODER,
  779. {
  780. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  781. { LLM_TENSOR_POS_EMBD, "position_embd" },
  782. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  783. { LLM_TENSOR_OUTPUT, "output" },
  784. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  785. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  786. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  787. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  788. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  789. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  790. },
  791. },
  792. {
  793. LLM_ARCH_REFACT,
  794. {
  795. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  796. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  797. { LLM_TENSOR_OUTPUT, "output" },
  798. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  799. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  800. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  801. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  802. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  803. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  804. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  805. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  806. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  807. },
  808. },
  809. {
  810. LLM_ARCH_BERT,
  811. {
  812. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  813. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  814. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  815. { LLM_TENSOR_POS_EMBD, "position_embd" },
  816. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  817. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  818. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  819. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  820. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  821. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  822. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  823. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  824. { LLM_TENSOR_CLS, "cls" },
  825. { LLM_TENSOR_CLS_OUT, "cls.output" },
  826. },
  827. },
  828. {
  829. LLM_ARCH_NOMIC_BERT,
  830. {
  831. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  832. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  833. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  834. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  835. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  836. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  837. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  838. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  839. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  840. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  841. },
  842. },
  843. {
  844. LLM_ARCH_JINA_BERT_V2,
  845. {
  846. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  847. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  848. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  849. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  850. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  851. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  852. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  853. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  854. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  855. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  856. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  857. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  858. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  859. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  860. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  861. { LLM_TENSOR_CLS, "cls" },
  862. },
  863. },
  864. {
  865. LLM_ARCH_BLOOM,
  866. {
  867. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  868. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  869. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  870. { LLM_TENSOR_OUTPUT, "output" },
  871. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  872. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  873. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  874. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  875. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  876. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  877. },
  878. },
  879. {
  880. LLM_ARCH_STABLELM,
  881. {
  882. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  883. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  884. { LLM_TENSOR_OUTPUT, "output" },
  885. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  886. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  887. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  888. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  889. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  890. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  891. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  892. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  893. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  894. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  895. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  896. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  897. },
  898. },
  899. {
  900. LLM_ARCH_QWEN,
  901. {
  902. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  903. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  904. { LLM_TENSOR_OUTPUT, "output" },
  905. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  906. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  907. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  908. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  909. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  910. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  911. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  912. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  913. },
  914. },
  915. {
  916. LLM_ARCH_QWEN2,
  917. {
  918. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  919. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  920. { LLM_TENSOR_OUTPUT, "output" },
  921. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  922. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  923. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  924. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  925. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  926. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  927. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  928. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  929. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  930. },
  931. },
  932. {
  933. LLM_ARCH_QWEN2MOE,
  934. {
  935. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  936. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  937. { LLM_TENSOR_OUTPUT, "output" },
  938. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  939. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  940. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  941. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  942. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  943. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  944. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  945. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  946. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  947. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  948. { LLM_TENSOR_FFN_GATE_INP_SHEXP, "blk.%d.ffn_gate_inp_shexp" },
  949. { LLM_TENSOR_FFN_GATE_SHEXP, "blk.%d.ffn_gate_shexp" },
  950. { LLM_TENSOR_FFN_DOWN_SHEXP, "blk.%d.ffn_down_shexp" },
  951. { LLM_TENSOR_FFN_UP_SHEXP, "blk.%d.ffn_up_shexp" },
  952. },
  953. },
  954. {
  955. LLM_ARCH_PHI2,
  956. {
  957. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  958. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  959. { LLM_TENSOR_OUTPUT, "output" },
  960. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  961. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  962. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  963. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  964. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  965. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  966. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  967. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  968. },
  969. },
  970. {
  971. LLM_ARCH_PHI3,
  972. {
  973. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  974. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  975. { LLM_TENSOR_OUTPUT, "output" },
  976. { LLM_TENSOR_ROPE_FACTORS_LONG, "rope_factors_long" },
  977. { LLM_TENSOR_ROPE_FACTORS_SHORT, "rope_factors_short" },
  978. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  979. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  980. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  981. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  982. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  983. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  984. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  985. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  986. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  987. },
  988. },
  989. {
  990. LLM_ARCH_PLAMO,
  991. {
  992. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  993. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  994. { LLM_TENSOR_OUTPUT, "output" },
  995. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  996. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  997. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  998. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  999. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1000. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1001. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1002. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1003. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1004. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1005. },
  1006. },
  1007. {
  1008. LLM_ARCH_CODESHELL,
  1009. {
  1010. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1011. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1012. { LLM_TENSOR_OUTPUT, "output" },
  1013. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1014. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1015. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1016. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1017. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1018. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1019. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1020. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1021. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1022. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1023. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1024. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1025. },
  1026. },
  1027. {
  1028. LLM_ARCH_ORION,
  1029. {
  1030. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1031. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1032. { LLM_TENSOR_OUTPUT, "output" },
  1033. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1034. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1035. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1036. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1037. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1038. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1039. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1040. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1041. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1042. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1043. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1044. },
  1045. },
  1046. {
  1047. LLM_ARCH_INTERNLM2,
  1048. {
  1049. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1050. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1051. { LLM_TENSOR_OUTPUT, "output" },
  1052. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1053. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1054. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1055. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1056. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1057. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1058. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1059. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1060. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1061. },
  1062. },
  1063. {
  1064. LLM_ARCH_MINICPM,
  1065. {
  1066. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1067. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1068. { LLM_TENSOR_OUTPUT, "output" },
  1069. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1070. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1071. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1072. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1073. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1074. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1075. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1076. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1077. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1078. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1079. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1080. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1081. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  1082. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  1083. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  1084. },
  1085. },
  1086. {
  1087. LLM_ARCH_MINICPM3,
  1088. {
  1089. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1090. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1091. { LLM_TENSOR_OUTPUT, "output" },
  1092. { LLM_TENSOR_ROPE_FACTORS_LONG, "rope_factors_long" },
  1093. { LLM_TENSOR_ROPE_FACTORS_SHORT, "rope_factors_short" },
  1094. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1095. { LLM_TENSOR_ATTN_Q_A_NORM, "blk.%d.attn_q_a_norm" },
  1096. { LLM_TENSOR_ATTN_KV_A_NORM, "blk.%d.attn_kv_a_norm" },
  1097. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1098. { LLM_TENSOR_ATTN_Q_A, "blk.%d.attn_q_a" },
  1099. { LLM_TENSOR_ATTN_Q_B, "blk.%d.attn_q_b" },
  1100. { LLM_TENSOR_ATTN_KV_A_MQA, "blk.%d.attn_kv_a_mqa" },
  1101. { LLM_TENSOR_ATTN_KV_B, "blk.%d.attn_kv_b" },
  1102. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1103. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1104. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1105. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1106. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1107. },
  1108. },
  1109. {
  1110. LLM_ARCH_GEMMA,
  1111. {
  1112. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1113. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1114. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1115. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1116. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1117. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1118. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1119. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1120. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1121. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1122. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1123. },
  1124. },
  1125. {
  1126. LLM_ARCH_GEMMA2,
  1127. {
  1128. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1129. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1130. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1131. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1132. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1133. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1134. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1135. { LLM_TENSOR_ATTN_POST_NORM, "blk.%d.post_attention_norm" },
  1136. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1137. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1138. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1139. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1140. { LLM_TENSOR_FFN_POST_NORM, "blk.%d.post_ffw_norm" },
  1141. },
  1142. },
  1143. {
  1144. LLM_ARCH_STARCODER2,
  1145. {
  1146. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1147. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1148. { LLM_TENSOR_OUTPUT, "output" },
  1149. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1150. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1151. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1152. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1153. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1154. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1155. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1156. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1157. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1158. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1159. },
  1160. },
  1161. {
  1162. LLM_ARCH_MAMBA,
  1163. {
  1164. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1165. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1166. { LLM_TENSOR_OUTPUT, "output" },
  1167. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1168. { LLM_TENSOR_SSM_IN, "blk.%d.ssm_in" },
  1169. { LLM_TENSOR_SSM_CONV1D, "blk.%d.ssm_conv1d" },
  1170. { LLM_TENSOR_SSM_X, "blk.%d.ssm_x" },
  1171. { LLM_TENSOR_SSM_DT, "blk.%d.ssm_dt" },
  1172. { LLM_TENSOR_SSM_A, "blk.%d.ssm_a" },
  1173. { LLM_TENSOR_SSM_D, "blk.%d.ssm_d" },
  1174. { LLM_TENSOR_SSM_OUT, "blk.%d.ssm_out" },
  1175. },
  1176. },
  1177. {
  1178. LLM_ARCH_XVERSE,
  1179. {
  1180. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1181. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1182. { LLM_TENSOR_OUTPUT, "output" },
  1183. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1184. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1185. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1186. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1187. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1188. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1189. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1190. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1191. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1192. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1193. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1194. },
  1195. },
  1196. {
  1197. LLM_ARCH_COMMAND_R,
  1198. {
  1199. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1200. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1201. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1202. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1203. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1204. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1205. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1206. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1207. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1208. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1209. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  1210. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  1211. },
  1212. },
  1213. {
  1214. LLM_ARCH_DBRX,
  1215. {
  1216. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1217. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1218. { LLM_TENSOR_OUTPUT, "output" },
  1219. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1220. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1221. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1222. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  1223. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1224. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1225. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1226. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1227. },
  1228. },
  1229. {
  1230. LLM_ARCH_OLMO,
  1231. {
  1232. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1233. { LLM_TENSOR_OUTPUT, "output" },
  1234. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1235. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1236. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1237. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1238. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1239. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1240. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1241. },
  1242. },
  1243. {
  1244. LLM_ARCH_OLMO2,
  1245. {
  1246. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1247. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1248. { LLM_TENSOR_OUTPUT, "output" },
  1249. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1250. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1251. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1252. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1253. { LLM_TENSOR_ATTN_POST_NORM, "blk.%d.post_attention_norm" },
  1254. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  1255. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  1256. { LLM_TENSOR_FFN_POST_NORM, "blk.%d.post_ffw_norm" },
  1257. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1258. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1259. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1260. },
  1261. },
  1262. {
  1263. LLM_ARCH_OLMOE,
  1264. {
  1265. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1266. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1267. { LLM_TENSOR_OUTPUT, "output" },
  1268. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1269. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1270. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1271. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1272. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1273. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  1274. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  1275. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1276. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1277. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1278. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1279. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1280. },
  1281. },
  1282. {
  1283. LLM_ARCH_OPENELM,
  1284. {
  1285. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1286. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1287. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1288. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1289. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  1290. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  1291. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1292. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1293. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1294. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1295. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1296. },
  1297. },
  1298. {
  1299. LLM_ARCH_ARCTIC,
  1300. {
  1301. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1302. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1303. { LLM_TENSOR_OUTPUT, "output" },
  1304. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1305. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1306. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1307. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1308. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1309. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1310. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1311. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1312. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1313. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1314. { LLM_TENSOR_FFN_NORM_EXPS, "blk.%d.ffn_norm_exps" },
  1315. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1316. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1317. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1318. },
  1319. },
  1320. {
  1321. LLM_ARCH_DEEPSEEK2,
  1322. {
  1323. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1324. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1325. { LLM_TENSOR_OUTPUT, "output" },
  1326. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1327. { LLM_TENSOR_ATTN_Q_A_NORM, "blk.%d.attn_q_a_norm" },
  1328. { LLM_TENSOR_ATTN_KV_A_NORM, "blk.%d.attn_kv_a_norm" },
  1329. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1330. { LLM_TENSOR_ATTN_Q_A, "blk.%d.attn_q_a" },
  1331. { LLM_TENSOR_ATTN_Q_B, "blk.%d.attn_q_b" },
  1332. { LLM_TENSOR_ATTN_KV_A_MQA, "blk.%d.attn_kv_a_mqa" },
  1333. { LLM_TENSOR_ATTN_KV_B, "blk.%d.attn_kv_b" },
  1334. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1335. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1336. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1337. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1338. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1339. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1340. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1341. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1342. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1343. { LLM_TENSOR_FFN_GATE_INP_SHEXP, "blk.%d.ffn_gate_inp_shexp" },
  1344. { LLM_TENSOR_FFN_GATE_SHEXP, "blk.%d.ffn_gate_shexp" },
  1345. { LLM_TENSOR_FFN_DOWN_SHEXP, "blk.%d.ffn_down_shexp" },
  1346. { LLM_TENSOR_FFN_UP_SHEXP, "blk.%d.ffn_up_shexp" },
  1347. },
  1348. },
  1349. {
  1350. LLM_ARCH_CHATGLM,
  1351. {
  1352. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1353. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1354. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1355. { LLM_TENSOR_OUTPUT, "output" },
  1356. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1357. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1358. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1359. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1360. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1361. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1362. },
  1363. },
  1364. {
  1365. LLM_ARCH_BITNET,
  1366. {
  1367. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1368. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1369. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1370. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1371. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1372. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1373. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1374. { LLM_TENSOR_ATTN_SUB_NORM, "blk.%d.attn_sub_norm" },
  1375. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1376. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1377. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1378. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1379. { LLM_TENSOR_FFN_SUB_NORM, "blk.%d.ffn_sub_norm" },
  1380. },
  1381. },
  1382. {
  1383. LLM_ARCH_T5,
  1384. {
  1385. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1386. { LLM_TENSOR_OUTPUT, "output" },
  1387. { LLM_TENSOR_DEC_OUTPUT_NORM, "dec.output_norm" },
  1388. { LLM_TENSOR_DEC_ATTN_NORM, "dec.blk.%d.attn_norm" },
  1389. { LLM_TENSOR_DEC_ATTN_Q, "dec.blk.%d.attn_q" },
  1390. { LLM_TENSOR_DEC_ATTN_K, "dec.blk.%d.attn_k" },
  1391. { LLM_TENSOR_DEC_ATTN_V, "dec.blk.%d.attn_v" },
  1392. { LLM_TENSOR_DEC_ATTN_OUT, "dec.blk.%d.attn_o" },
  1393. { LLM_TENSOR_DEC_ATTN_REL_B, "dec.blk.%d.attn_rel_b" },
  1394. { LLM_TENSOR_DEC_CROSS_ATTN_NORM, "dec.blk.%d.cross_attn_norm" },
  1395. { LLM_TENSOR_DEC_CROSS_ATTN_Q, "dec.blk.%d.cross_attn_q" },
  1396. { LLM_TENSOR_DEC_CROSS_ATTN_K, "dec.blk.%d.cross_attn_k" },
  1397. { LLM_TENSOR_DEC_CROSS_ATTN_V, "dec.blk.%d.cross_attn_v" },
  1398. { LLM_TENSOR_DEC_CROSS_ATTN_OUT, "dec.blk.%d.cross_attn_o" },
  1399. { LLM_TENSOR_DEC_CROSS_ATTN_REL_B, "dec.blk.%d.cross_attn_rel_b" },
  1400. { LLM_TENSOR_DEC_FFN_NORM, "dec.blk.%d.ffn_norm" },
  1401. { LLM_TENSOR_DEC_FFN_GATE, "dec.blk.%d.ffn_gate" },
  1402. { LLM_TENSOR_DEC_FFN_DOWN, "dec.blk.%d.ffn_down" },
  1403. { LLM_TENSOR_DEC_FFN_UP, "dec.blk.%d.ffn_up" },
  1404. { LLM_TENSOR_ENC_OUTPUT_NORM, "enc.output_norm" },
  1405. { LLM_TENSOR_ENC_ATTN_NORM, "enc.blk.%d.attn_norm" },
  1406. { LLM_TENSOR_ENC_ATTN_Q, "enc.blk.%d.attn_q" },
  1407. { LLM_TENSOR_ENC_ATTN_K, "enc.blk.%d.attn_k" },
  1408. { LLM_TENSOR_ENC_ATTN_V, "enc.blk.%d.attn_v" },
  1409. { LLM_TENSOR_ENC_ATTN_OUT, "enc.blk.%d.attn_o" },
  1410. { LLM_TENSOR_ENC_ATTN_REL_B, "enc.blk.%d.attn_rel_b" },
  1411. { LLM_TENSOR_ENC_FFN_NORM, "enc.blk.%d.ffn_norm" },
  1412. { LLM_TENSOR_ENC_FFN_GATE, "enc.blk.%d.ffn_gate" },
  1413. { LLM_TENSOR_ENC_FFN_DOWN, "enc.blk.%d.ffn_down" },
  1414. { LLM_TENSOR_ENC_FFN_UP, "enc.blk.%d.ffn_up" },
  1415. },
  1416. },
  1417. {
  1418. LLM_ARCH_T5ENCODER,
  1419. {
  1420. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1421. { LLM_TENSOR_OUTPUT, "output" },
  1422. { LLM_TENSOR_ENC_OUTPUT_NORM, "enc.output_norm" },
  1423. { LLM_TENSOR_ENC_ATTN_NORM, "enc.blk.%d.attn_norm" },
  1424. { LLM_TENSOR_ENC_ATTN_Q, "enc.blk.%d.attn_q" },
  1425. { LLM_TENSOR_ENC_ATTN_K, "enc.blk.%d.attn_k" },
  1426. { LLM_TENSOR_ENC_ATTN_V, "enc.blk.%d.attn_v" },
  1427. { LLM_TENSOR_ENC_ATTN_OUT, "enc.blk.%d.attn_o" },
  1428. { LLM_TENSOR_ENC_ATTN_REL_B, "enc.blk.%d.attn_rel_b" },
  1429. { LLM_TENSOR_ENC_FFN_NORM, "enc.blk.%d.ffn_norm" },
  1430. { LLM_TENSOR_ENC_FFN_GATE, "enc.blk.%d.ffn_gate" },
  1431. { LLM_TENSOR_ENC_FFN_DOWN, "enc.blk.%d.ffn_down" },
  1432. { LLM_TENSOR_ENC_FFN_UP, "enc.blk.%d.ffn_up" },
  1433. },
  1434. },
  1435. {
  1436. LLM_ARCH_JAIS,
  1437. {
  1438. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1439. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1440. { LLM_TENSOR_OUTPUT, "output" },
  1441. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1442. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1443. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1444. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1445. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1446. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1447. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1448. },
  1449. },
  1450. {
  1451. LLM_ARCH_NEMOTRON,
  1452. {
  1453. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1454. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1455. { LLM_TENSOR_OUTPUT, "output" },
  1456. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1457. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1458. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1459. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1460. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1461. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1462. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1463. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1464. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1465. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1466. },
  1467. },
  1468. {
  1469. LLM_ARCH_EXAONE,
  1470. {
  1471. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1472. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1473. { LLM_TENSOR_OUTPUT, "output" },
  1474. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1475. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1476. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1477. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1478. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1479. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1480. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1481. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1482. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1483. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1484. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1485. },
  1486. },
  1487. {
  1488. LLM_ARCH_RWKV6,
  1489. {
  1490. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1491. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  1492. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1493. { LLM_TENSOR_OUTPUT, "output" },
  1494. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1495. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  1496. { LLM_TENSOR_TIME_MIX_W1, "blk.%d.time_mix_w1" },
  1497. { LLM_TENSOR_TIME_MIX_W2, "blk.%d.time_mix_w2" },
  1498. { LLM_TENSOR_TIME_MIX_LERP_X, "blk.%d.time_mix_lerp_x" },
  1499. { LLM_TENSOR_TIME_MIX_LERP_W, "blk.%d.time_mix_lerp_w" },
  1500. { LLM_TENSOR_TIME_MIX_LERP_K, "blk.%d.time_mix_lerp_k" },
  1501. { LLM_TENSOR_TIME_MIX_LERP_V, "blk.%d.time_mix_lerp_v" },
  1502. { LLM_TENSOR_TIME_MIX_LERP_R, "blk.%d.time_mix_lerp_r" },
  1503. { LLM_TENSOR_TIME_MIX_LERP_G, "blk.%d.time_mix_lerp_g" },
  1504. { LLM_TENSOR_TIME_MIX_FIRST, "blk.%d.time_mix_first" },
  1505. { LLM_TENSOR_TIME_MIX_DECAY, "blk.%d.time_mix_decay" },
  1506. { LLM_TENSOR_TIME_MIX_DECAY_W1, "blk.%d.time_mix_decay_w1" },
  1507. { LLM_TENSOR_TIME_MIX_DECAY_W2, "blk.%d.time_mix_decay_w2" },
  1508. { LLM_TENSOR_TIME_MIX_KEY, "blk.%d.time_mix_key" },
  1509. { LLM_TENSOR_TIME_MIX_VALUE, "blk.%d.time_mix_value" },
  1510. { LLM_TENSOR_TIME_MIX_RECEPTANCE, "blk.%d.time_mix_receptance" },
  1511. { LLM_TENSOR_TIME_MIX_GATE, "blk.%d.time_mix_gate" },
  1512. { LLM_TENSOR_TIME_MIX_LN, "blk.%d.time_mix_ln" },
  1513. { LLM_TENSOR_TIME_MIX_OUTPUT, "blk.%d.time_mix_output" },
  1514. { LLM_TENSOR_CHANNEL_MIX_LERP_K, "blk.%d.channel_mix_lerp_k" },
  1515. { LLM_TENSOR_CHANNEL_MIX_LERP_R, "blk.%d.channel_mix_lerp_r" },
  1516. { LLM_TENSOR_CHANNEL_MIX_KEY, "blk.%d.channel_mix_key" },
  1517. { LLM_TENSOR_CHANNEL_MIX_VALUE, "blk.%d.channel_mix_value" },
  1518. { LLM_TENSOR_CHANNEL_MIX_RECEPTANCE, "blk.%d.channel_mix_receptance" },
  1519. },
  1520. },
  1521. {
  1522. LLM_ARCH_GRANITE,
  1523. {
  1524. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1525. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1526. { LLM_TENSOR_OUTPUT, "output" },
  1527. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1528. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1529. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1530. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1531. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1532. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1533. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1534. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1535. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1536. },
  1537. },
  1538. {
  1539. LLM_ARCH_GRANITE_MOE,
  1540. {
  1541. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1542. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1543. { LLM_TENSOR_OUTPUT, "output" },
  1544. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1545. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1546. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1547. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1548. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1549. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1550. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1551. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1552. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1553. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1554. },
  1555. },
  1556. {
  1557. LLM_ARCH_CHAMELEON,
  1558. {
  1559. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1560. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1561. { LLM_TENSOR_OUTPUT, "output" },
  1562. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1563. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1564. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1565. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1566. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1567. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1568. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1569. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1570. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1571. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  1572. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  1573. },
  1574. },
  1575. {
  1576. LLM_ARCH_SOLAR,
  1577. {
  1578. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1579. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1580. { LLM_TENSOR_OUTPUT, "output" },
  1581. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1582. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1583. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1584. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1585. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1586. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1587. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1588. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1589. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1590. { LLM_TENSOR_BSKCN_TV, "bskcn_tv" },
  1591. },
  1592. },
  1593. {
  1594. LLM_ARCH_UNKNOWN,
  1595. {
  1596. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1597. },
  1598. },
  1599. };
  1600. enum llm_chat_template {
  1601. LLM_CHAT_TEMPLATE_CHATML,
  1602. LLM_CHAT_TEMPLATE_LLAMA_2,
  1603. LLM_CHAT_TEMPLATE_LLAMA_2_SYS,
  1604. LLM_CHAT_TEMPLATE_LLAMA_2_SYS_BOS,
  1605. LLM_CHAT_TEMPLATE_LLAMA_2_SYS_STRIP,
  1606. LLM_CHAT_TEMPLATE_MISTRAL_V1,
  1607. LLM_CHAT_TEMPLATE_MISTRAL_V3,
  1608. LLM_CHAT_TEMPLATE_MISTRAL_V3_TEKKEN,
  1609. LLM_CHAT_TEMPLATE_MISTRAL_V7,
  1610. LLM_CHAT_TEMPLATE_PHI_3,
  1611. LLM_CHAT_TEMPLATE_ZEPHYR,
  1612. LLM_CHAT_TEMPLATE_MONARCH,
  1613. LLM_CHAT_TEMPLATE_GEMMA,
  1614. LLM_CHAT_TEMPLATE_ORION,
  1615. LLM_CHAT_TEMPLATE_OPENCHAT,
  1616. LLM_CHAT_TEMPLATE_VICUNA,
  1617. LLM_CHAT_TEMPLATE_VICUNA_ORCA,
  1618. LLM_CHAT_TEMPLATE_DEEPSEEK,
  1619. LLM_CHAT_TEMPLATE_DEEPSEEK_2,
  1620. LLM_CHAT_TEMPLATE_COMMAND_R,
  1621. LLM_CHAT_TEMPLATE_LLAMA_3,
  1622. LLM_CHAT_TEMPLATE_CHATGML_3,
  1623. LLM_CHAT_TEMPLATE_CHATGML_4,
  1624. LLM_CHAT_TEMPLATE_MINICPM,
  1625. LLM_CHAT_TEMPLATE_EXAONE_3,
  1626. LLM_CHAT_TEMPLATE_RWKV_WORLD,
  1627. LLM_CHAT_TEMPLATE_GRANITE,
  1628. LLM_CHAT_TEMPLATE_UNKNOWN,
  1629. };
  1630. static const std::map<std::string, llm_chat_template> LLM_CHAT_TEMPLATES = {
  1631. { "chatml", LLM_CHAT_TEMPLATE_CHATML },
  1632. { "llama2", LLM_CHAT_TEMPLATE_LLAMA_2 },
  1633. { "llama2-sys", LLM_CHAT_TEMPLATE_LLAMA_2_SYS },
  1634. { "llama2-sys-bos", LLM_CHAT_TEMPLATE_LLAMA_2_SYS_BOS },
  1635. { "llama2-sys-strip", LLM_CHAT_TEMPLATE_LLAMA_2_SYS_STRIP },
  1636. { "mistral-v1", LLM_CHAT_TEMPLATE_MISTRAL_V1 },
  1637. { "mistral-v3", LLM_CHAT_TEMPLATE_MISTRAL_V3 },
  1638. { "mistral-v3-tekken", LLM_CHAT_TEMPLATE_MISTRAL_V3_TEKKEN },
  1639. { "mistral-v7", LLM_CHAT_TEMPLATE_MISTRAL_V7 },
  1640. { "phi3", LLM_CHAT_TEMPLATE_PHI_3 },
  1641. { "zephyr", LLM_CHAT_TEMPLATE_ZEPHYR },
  1642. { "monarch", LLM_CHAT_TEMPLATE_MONARCH },
  1643. { "gemma", LLM_CHAT_TEMPLATE_GEMMA },
  1644. { "orion", LLM_CHAT_TEMPLATE_ORION },
  1645. { "openchat", LLM_CHAT_TEMPLATE_OPENCHAT },
  1646. { "vicuna", LLM_CHAT_TEMPLATE_VICUNA },
  1647. { "vicuna-orca", LLM_CHAT_TEMPLATE_VICUNA_ORCA },
  1648. { "deepseek", LLM_CHAT_TEMPLATE_DEEPSEEK },
  1649. { "deepseek2", LLM_CHAT_TEMPLATE_DEEPSEEK_2 },
  1650. { "command-r", LLM_CHAT_TEMPLATE_COMMAND_R },
  1651. { "llama3", LLM_CHAT_TEMPLATE_LLAMA_3 },
  1652. { "chatglm3", LLM_CHAT_TEMPLATE_CHATGML_3 },
  1653. { "chatglm4", LLM_CHAT_TEMPLATE_CHATGML_4 },
  1654. { "minicpm", LLM_CHAT_TEMPLATE_MINICPM },
  1655. { "exaone3", LLM_CHAT_TEMPLATE_EXAONE_3 },
  1656. { "rwkv-world", LLM_CHAT_TEMPLATE_RWKV_WORLD },
  1657. { "granite", LLM_CHAT_TEMPLATE_GRANITE },
  1658. };
  1659. static llm_arch llm_arch_from_string(const std::string & name) {
  1660. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  1661. if (kv.second == name) {
  1662. return kv.first;
  1663. }
  1664. }
  1665. return LLM_ARCH_UNKNOWN;
  1666. }
  1667. // helper to handle gguf constants
  1668. // usage:
  1669. //
  1670. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  1671. //
  1672. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  1673. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  1674. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  1675. //
  1676. struct LLM_TN_IMPL {
  1677. const llm_arch arch;
  1678. const llm_tensor tensor;
  1679. const char * const suffix;
  1680. const int bid;
  1681. const int xid;
  1682. std::string str() const {
  1683. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1684. return "__missing__";
  1685. }
  1686. std::string name = ::format(LLM_TENSOR_NAMES.at(arch).at(tensor), bid, xid);
  1687. if (suffix != nullptr) {
  1688. name += ".";
  1689. name += suffix;
  1690. }
  1691. return name;
  1692. }
  1693. operator std::string() const {
  1694. return str();
  1695. }
  1696. friend bool operator==(const std::string & str, const LLM_TN_IMPL & tn) {
  1697. return str == tn.str();
  1698. }
  1699. friend bool operator!=(const std::string & str, const LLM_TN_IMPL & tn) {
  1700. return str != tn.str();
  1701. }
  1702. };
  1703. struct LLM_TN {
  1704. LLM_TN(llm_arch arch) : arch(arch) {}
  1705. llm_arch arch;
  1706. LLM_TN_IMPL operator()(llm_tensor tensor, const char * suffix, int bid = -1, int xid = -1) const {
  1707. return { arch, tensor, suffix, bid, xid };
  1708. }
  1709. LLM_TN_IMPL operator()(llm_tensor tensor, int bid = -1, int xid = -1) const {
  1710. return { arch, tensor, nullptr, bid, xid };
  1711. }
  1712. };
  1713. //
  1714. // gguf helpers
  1715. //
  1716. static const std::map<llama_rope_scaling_type, const char *> LLAMA_ROPE_SCALING_TYPES = {
  1717. { LLAMA_ROPE_SCALING_TYPE_NONE, "none" },
  1718. { LLAMA_ROPE_SCALING_TYPE_LINEAR, "linear" },
  1719. { LLAMA_ROPE_SCALING_TYPE_YARN, "yarn" },
  1720. };
  1721. static llama_rope_scaling_type llama_rope_scaling_type_from_string(const std::string & name) {
  1722. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  1723. if (kv.second == name) {
  1724. return (llama_rope_scaling_type) kv.first;
  1725. }
  1726. }
  1727. return LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
  1728. }
  1729. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  1730. switch (type) {
  1731. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  1732. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  1733. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  1734. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  1735. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  1736. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  1737. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  1738. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  1739. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  1740. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  1741. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  1742. default: return format("unknown type %d", type);
  1743. }
  1744. }
  1745. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  1746. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  1747. switch (type) {
  1748. case GGUF_TYPE_STRING:
  1749. return gguf_get_val_str(ctx_gguf, i);
  1750. case GGUF_TYPE_ARRAY:
  1751. {
  1752. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  1753. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  1754. const void * data = gguf_get_arr_data(ctx_gguf, i);
  1755. std::stringstream ss;
  1756. ss << "[";
  1757. for (int j = 0; j < arr_n; j++) {
  1758. if (arr_type == GGUF_TYPE_STRING) {
  1759. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  1760. // escape quotes
  1761. replace_all(val, "\\", "\\\\");
  1762. replace_all(val, "\"", "\\\"");
  1763. ss << '"' << val << '"';
  1764. } else if (arr_type == GGUF_TYPE_ARRAY) {
  1765. ss << "???";
  1766. } else {
  1767. ss << gguf_data_to_str(arr_type, data, j);
  1768. }
  1769. if (j < arr_n - 1) {
  1770. ss << ", ";
  1771. }
  1772. }
  1773. ss << "]";
  1774. return ss.str();
  1775. }
  1776. default:
  1777. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  1778. }
  1779. }
  1780. //
  1781. // llama helpers
  1782. //
  1783. #if defined(_WIN32)
  1784. static std::string llama_format_win_err(DWORD err) {
  1785. LPSTR buf;
  1786. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1787. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  1788. if (!size) {
  1789. return "FormatMessageA failed";
  1790. }
  1791. std::string ret(buf, size);
  1792. LocalFree(buf);
  1793. return ret;
  1794. }
  1795. #endif
  1796. template <typename T>
  1797. struct no_init {
  1798. T value;
  1799. no_init() { /* do nothing */ }
  1800. };
  1801. struct llama_file {
  1802. #if defined(_WIN32)
  1803. // use FILE * so we don't have to re-open the file to mmap
  1804. FILE * fp;
  1805. HANDLE fp_win32;
  1806. size_t size;
  1807. private:
  1808. std::string GetErrorMessageWin32(DWORD error_code) const {
  1809. std::string ret;
  1810. LPSTR lpMsgBuf = NULL;
  1811. DWORD bufLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1812. NULL, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lpMsgBuf, 0, NULL);
  1813. if (!bufLen) {
  1814. ret = format("Win32 error code: %s", error_code);
  1815. } else {
  1816. ret = lpMsgBuf;
  1817. LocalFree(lpMsgBuf);
  1818. }
  1819. return ret;
  1820. }
  1821. public:
  1822. llama_file(const char * fname, const char * mode) {
  1823. fp = ggml_fopen(fname, mode);
  1824. if (fp == NULL) {
  1825. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  1826. }
  1827. fp_win32 = (HANDLE) _get_osfhandle(_fileno(fp));
  1828. seek(0, SEEK_END);
  1829. size = tell();
  1830. seek(0, SEEK_SET);
  1831. }
  1832. size_t tell() const {
  1833. // SetFilePointerEx returns the current position when seeking relative 0 bytes
  1834. LARGE_INTEGER li;
  1835. li.QuadPart = 0;
  1836. BOOL ret = SetFilePointerEx(fp_win32, li, &li, FILE_CURRENT);
  1837. if (!ret) {
  1838. throw std::runtime_error(format("read error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1839. }
  1840. return li.QuadPart;
  1841. }
  1842. void seek(size_t offset, int whence) const {
  1843. // no need to convert SEEK_* to FILE_*. The enums are the same.
  1844. // Still, keep static asserts to avoid failures in the future.
  1845. static_assert(SEEK_SET == FILE_BEGIN, "SEEK_SET != FILE_BEGIN");
  1846. static_assert(SEEK_CUR == FILE_CURRENT, "SEEK_CUR != FILE_CURRENT");
  1847. static_assert(SEEK_END == FILE_END, "SEEK_END != FILE_END");
  1848. LARGE_INTEGER li;
  1849. li.QuadPart = offset;
  1850. BOOL ret = SetFilePointerEx(fp_win32, li, NULL, whence);
  1851. if (!ret) {
  1852. throw std::runtime_error(format("read error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1853. }
  1854. }
  1855. void read_raw(void * ptr, size_t len) const {
  1856. // On Win32 ReadFile is significant faster than fread which is again significant faster than std::fstream. Thus
  1857. // use the Win32 API to do file io instead of the C/C++ library functions.
  1858. // There are conditions under which ReadFile cannot read chunks >64MB.
  1859. // Thus split the operation into smaller chunks if len exceeds this limit.
  1860. size_t bytes_read = 0;
  1861. while (bytes_read < len) {
  1862. size_t chunk_size = std::min<size_t>(len - bytes_read, 64*1024*1024);
  1863. DWORD chunk_read = 0;
  1864. BOOL result = ReadFile(fp_win32, reinterpret_cast<char*>(ptr) + bytes_read, chunk_size, &chunk_read, NULL);
  1865. if (!result) {
  1866. throw std::runtime_error(format("read error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1867. }
  1868. if (chunk_read < chunk_size || chunk_read == 0) {
  1869. throw std::runtime_error("unexpectedly reached end of file");
  1870. }
  1871. bytes_read += chunk_read;
  1872. } ;
  1873. }
  1874. uint32_t read_u32() const {
  1875. uint32_t val;
  1876. read_raw(&val, sizeof(val));
  1877. return val;
  1878. }
  1879. void write_raw(const void * ptr, size_t len) const {
  1880. // There are conditions under which WriteFile cannot write chunks >64MB.
  1881. // Thus split the operation into smaller chunks if len exceeds this limit.
  1882. size_t bytes_written = 0;
  1883. while (bytes_written < len) {
  1884. size_t chunk_size = std::min<size_t>(len - bytes_written, 64*1024*1024);
  1885. DWORD chunk_written = 0;
  1886. BOOL result = WriteFile(fp_win32, reinterpret_cast<char const*>(ptr) + bytes_written, chunk_size, &chunk_written, NULL);
  1887. if (!result) {
  1888. throw std::runtime_error(format("write error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1889. }
  1890. if (chunk_written < chunk_size || chunk_written == 0) {
  1891. throw std::runtime_error("unexpectedly failed to write bytes");
  1892. }
  1893. bytes_written += chunk_written;
  1894. }
  1895. }
  1896. void write_u32(std::uint32_t val) const {
  1897. write_raw(&val, sizeof(val));
  1898. }
  1899. ~llama_file() {
  1900. if (fp) {
  1901. std::fclose(fp);
  1902. }
  1903. }
  1904. #else
  1905. // use FILE * so we don't have to re-open the file to mmap
  1906. FILE * fp;
  1907. size_t size;
  1908. llama_file(const char * fname, const char * mode) {
  1909. fp = ggml_fopen(fname, mode);
  1910. if (fp == NULL) {
  1911. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  1912. }
  1913. seek(0, SEEK_END);
  1914. size = tell();
  1915. seek(0, SEEK_SET);
  1916. }
  1917. size_t tell() const {
  1918. #ifdef _WIN32
  1919. __int64 ret = _ftelli64(fp);
  1920. #else
  1921. long ret = std::ftell(fp);
  1922. #endif
  1923. if (ret == -1) {
  1924. throw std::runtime_error(format("ftell error: %s", strerror(errno)));
  1925. }
  1926. return (size_t) ret;
  1927. }
  1928. void seek(size_t offset, int whence) const {
  1929. #ifdef _WIN32
  1930. int ret = _fseeki64(fp, (__int64) offset, whence);
  1931. #else
  1932. int ret = std::fseek(fp, (long) offset, whence);
  1933. #endif
  1934. if (ret != 0) {
  1935. throw std::runtime_error(format("seek error: %s", strerror(errno)));
  1936. }
  1937. }
  1938. void read_raw(void * ptr, size_t len) const {
  1939. if (len == 0) {
  1940. return;
  1941. }
  1942. errno = 0;
  1943. std::size_t ret = std::fread(ptr, len, 1, fp);
  1944. if (ferror(fp)) {
  1945. throw std::runtime_error(format("read error: %s", strerror(errno)));
  1946. }
  1947. if (ret != 1) {
  1948. throw std::runtime_error("unexpectedly reached end of file");
  1949. }
  1950. }
  1951. uint32_t read_u32() const {
  1952. uint32_t ret;
  1953. read_raw(&ret, sizeof(ret));
  1954. return ret;
  1955. }
  1956. void write_raw(const void * ptr, size_t len) const {
  1957. if (len == 0) {
  1958. return;
  1959. }
  1960. errno = 0;
  1961. size_t ret = std::fwrite(ptr, len, 1, fp);
  1962. if (ret != 1) {
  1963. throw std::runtime_error(format("write error: %s", strerror(errno)));
  1964. }
  1965. }
  1966. void write_u32(std::uint32_t val) const {
  1967. write_raw(&val, sizeof(val));
  1968. }
  1969. ~llama_file() {
  1970. if (fp) {
  1971. std::fclose(fp);
  1972. }
  1973. }
  1974. #endif
  1975. };
  1976. using llama_files = std::vector<std::unique_ptr<llama_file>>;
  1977. struct llama_mmap {
  1978. void * addr;
  1979. size_t size;
  1980. llama_mmap(const llama_mmap &) = delete;
  1981. #ifdef _POSIX_MAPPED_FILES
  1982. static constexpr bool SUPPORTED = true;
  1983. // list of mapped fragments (first_offset, last_offset)
  1984. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  1985. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  1986. size = file->size;
  1987. int fd = fileno(file->fp);
  1988. int flags = MAP_SHARED;
  1989. // prefetch/readahead impairs performance on NUMA systems
  1990. if (numa) { prefetch = 0; }
  1991. #ifdef __linux__
  1992. // advise the kernel to read the file sequentially (increases readahead)
  1993. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  1994. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  1995. strerror(errno));
  1996. }
  1997. if (prefetch) { flags |= MAP_POPULATE; }
  1998. #endif
  1999. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  2000. if (addr == MAP_FAILED) { // NOLINT
  2001. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  2002. }
  2003. if (prefetch > 0) {
  2004. // advise the kernel to preload the mapped memory
  2005. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  2006. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  2007. strerror(errno));
  2008. }
  2009. }
  2010. if (numa) {
  2011. // advise the kernel not to use readahead
  2012. // (because the next page might not belong on the same node)
  2013. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  2014. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  2015. strerror(errno));
  2016. }
  2017. }
  2018. // initialize list of mapped_fragments
  2019. mapped_fragments.emplace_back(0, file->size);
  2020. }
  2021. static void align_range(size_t * first, size_t * last, size_t page_size) {
  2022. // align first to the next page
  2023. size_t offset_in_page = *first & (page_size - 1);
  2024. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  2025. *first += offset_to_page;
  2026. // align last to the previous page
  2027. *last = *last & ~(page_size - 1);
  2028. if (*last <= *first) {
  2029. *last = *first;
  2030. }
  2031. }
  2032. // partially unmap the file in the range [first, last)
  2033. void unmap_fragment(size_t first, size_t last) {
  2034. // note: this function must not be called multiple times with overlapping ranges
  2035. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  2036. int page_size = sysconf(_SC_PAGESIZE);
  2037. align_range(&first, &last, page_size);
  2038. size_t len = last - first;
  2039. if (len == 0) {
  2040. return;
  2041. }
  2042. GGML_ASSERT(first % page_size == 0);
  2043. GGML_ASSERT(last % page_size == 0);
  2044. GGML_ASSERT(last > first);
  2045. void * next_page_start = (uint8_t *) addr + first;
  2046. // unmap the range
  2047. if (munmap(next_page_start, len)) {
  2048. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  2049. }
  2050. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  2051. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  2052. for (const auto & frag : mapped_fragments) {
  2053. if (frag.first < first && frag.second > last) {
  2054. // the range is in the middle of the fragment, split it
  2055. new_mapped_fragments.emplace_back(frag.first, first);
  2056. new_mapped_fragments.emplace_back(last, frag.second);
  2057. } else if (frag.first < first && frag.second > first) {
  2058. // the range starts in the middle of the fragment
  2059. new_mapped_fragments.emplace_back(frag.first, first);
  2060. } else if (frag.first < last && frag.second > last) {
  2061. // the range ends in the middle of the fragment
  2062. new_mapped_fragments.emplace_back(last, frag.second);
  2063. } else if (frag.first >= first && frag.second <= last) {
  2064. // the range covers the entire fragment
  2065. } else {
  2066. // the range is outside the fragment
  2067. new_mapped_fragments.push_back(frag);
  2068. }
  2069. }
  2070. mapped_fragments = std::move(new_mapped_fragments);
  2071. }
  2072. ~llama_mmap() {
  2073. for (const auto & frag : mapped_fragments) {
  2074. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  2075. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  2076. }
  2077. }
  2078. }
  2079. #elif defined(_WIN32)
  2080. static constexpr bool SUPPORTED = true;
  2081. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  2082. GGML_UNUSED(numa);
  2083. size = file->size;
  2084. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  2085. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  2086. if (hMapping == NULL) {
  2087. DWORD error = GetLastError();
  2088. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  2089. }
  2090. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  2091. DWORD error = GetLastError();
  2092. CloseHandle(hMapping);
  2093. if (addr == NULL) {
  2094. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  2095. }
  2096. if (prefetch > 0) {
  2097. #if _WIN32_WINNT >= 0x602
  2098. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  2099. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  2100. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  2101. // may fail on pre-Windows 8 systems
  2102. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  2103. if (pPrefetchVirtualMemory) {
  2104. // advise the kernel to preload the mapped memory
  2105. WIN32_MEMORY_RANGE_ENTRY range;
  2106. range.VirtualAddress = addr;
  2107. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  2108. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  2109. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  2110. llama_format_win_err(GetLastError()).c_str());
  2111. }
  2112. }
  2113. #else
  2114. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  2115. #endif
  2116. }
  2117. }
  2118. void unmap_fragment(size_t first, size_t last) {
  2119. // not supported
  2120. GGML_UNUSED(first);
  2121. GGML_UNUSED(last);
  2122. }
  2123. ~llama_mmap() {
  2124. if (!UnmapViewOfFile(addr)) {
  2125. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  2126. llama_format_win_err(GetLastError()).c_str());
  2127. }
  2128. }
  2129. #else
  2130. static constexpr bool SUPPORTED = false;
  2131. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  2132. GGML_UNUSED(file);
  2133. GGML_UNUSED(prefetch);
  2134. GGML_UNUSED(numa);
  2135. throw std::runtime_error("mmap not supported");
  2136. }
  2137. void unmap_fragment(size_t first, size_t last) {
  2138. GGML_UNUSED(first);
  2139. GGML_UNUSED(last);
  2140. throw std::runtime_error("mmap not supported");
  2141. }
  2142. #endif
  2143. };
  2144. using llama_mmaps = std::vector<std::unique_ptr<llama_mmap>>;
  2145. // Represents some region of memory being locked using mlock or VirtualLock;
  2146. // will automatically unlock on destruction.
  2147. struct llama_mlock {
  2148. void * addr = NULL;
  2149. size_t size = 0;
  2150. bool failed_already = false;
  2151. llama_mlock() {}
  2152. llama_mlock(const llama_mlock &) = delete;
  2153. ~llama_mlock() {
  2154. if (size) {
  2155. raw_unlock(addr, size);
  2156. }
  2157. }
  2158. void init(void * ptr) {
  2159. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  2160. addr = ptr;
  2161. }
  2162. void grow_to(size_t target_size) {
  2163. GGML_ASSERT(addr);
  2164. if (failed_already) {
  2165. return;
  2166. }
  2167. size_t granularity = lock_granularity();
  2168. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  2169. if (target_size > size) {
  2170. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  2171. size = target_size;
  2172. } else {
  2173. failed_already = true;
  2174. }
  2175. }
  2176. }
  2177. #ifdef _POSIX_MEMLOCK_RANGE
  2178. static constexpr bool SUPPORTED = true;
  2179. static size_t lock_granularity() {
  2180. return (size_t) sysconf(_SC_PAGESIZE);
  2181. }
  2182. #ifdef __APPLE__
  2183. #define MLOCK_SUGGESTION \
  2184. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  2185. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  2186. #else
  2187. #define MLOCK_SUGGESTION \
  2188. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  2189. #endif
  2190. bool raw_lock(const void * addr, size_t size) const {
  2191. if (!mlock(addr, size)) {
  2192. return true;
  2193. }
  2194. char* errmsg = std::strerror(errno);
  2195. bool suggest = (errno == ENOMEM);
  2196. // Check if the resource limit is fine after all
  2197. struct rlimit lock_limit;
  2198. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  2199. suggest = false;
  2200. }
  2201. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  2202. suggest = false;
  2203. }
  2204. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  2205. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  2206. return false;
  2207. }
  2208. #undef MLOCK_SUGGESTION
  2209. static void raw_unlock(void * addr, size_t size) {
  2210. if (munlock(addr, size)) {
  2211. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  2212. }
  2213. }
  2214. #elif defined(_WIN32)
  2215. static constexpr bool SUPPORTED = true;
  2216. static size_t lock_granularity() {
  2217. SYSTEM_INFO si;
  2218. GetSystemInfo(&si);
  2219. return (size_t) si.dwPageSize;
  2220. }
  2221. bool raw_lock(void * ptr, size_t len) const {
  2222. for (int tries = 1; ; tries++) {
  2223. if (VirtualLock(ptr, len)) {
  2224. return true;
  2225. }
  2226. if (tries == 2) {
  2227. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  2228. len, size, llama_format_win_err(GetLastError()).c_str());
  2229. return false;
  2230. }
  2231. // It failed but this was only the first try; increase the working
  2232. // set size and try again.
  2233. SIZE_T min_ws_size, max_ws_size;
  2234. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  2235. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  2236. llama_format_win_err(GetLastError()).c_str());
  2237. return false;
  2238. }
  2239. // Per MSDN: "The maximum number of pages that a process can lock
  2240. // is equal to the number of pages in its minimum working set minus
  2241. // a small overhead."
  2242. // Hopefully a megabyte is enough overhead:
  2243. size_t increment = len + 1048576;
  2244. // The minimum must be <= the maximum, so we need to increase both:
  2245. min_ws_size += increment;
  2246. max_ws_size += increment;
  2247. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  2248. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  2249. llama_format_win_err(GetLastError()).c_str());
  2250. return false;
  2251. }
  2252. }
  2253. }
  2254. static void raw_unlock(void * ptr, size_t len) {
  2255. if (!VirtualUnlock(ptr, len)) {
  2256. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  2257. llama_format_win_err(GetLastError()).c_str());
  2258. }
  2259. }
  2260. #else
  2261. static constexpr bool SUPPORTED = false;
  2262. static size_t lock_granularity() {
  2263. return (size_t) 65536;
  2264. }
  2265. bool raw_lock(const void * addr, size_t len) const {
  2266. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  2267. return false;
  2268. }
  2269. static void raw_unlock(const void * addr, size_t len) {}
  2270. #endif
  2271. };
  2272. using llama_mlocks = std::vector<std::unique_ptr<llama_mlock>>;
  2273. // NOTE: avoid ever using this except for building the token_to_piece caches
  2274. static std::string llama_token_to_piece(const struct llama_model * model, llama_token token, bool special) {
  2275. std::string piece;
  2276. piece.resize(piece.capacity()); // using string internal cache
  2277. const int n_chars = llama_token_to_piece(model, token, &piece[0], piece.size(), 0, special);
  2278. if (n_chars < 0) {
  2279. piece.resize(-n_chars);
  2280. int check = llama_token_to_piece(model, token, &piece[0], piece.size(), 0, special);
  2281. GGML_ASSERT(check == -n_chars);
  2282. }
  2283. else {
  2284. piece.resize(n_chars);
  2285. }
  2286. return piece;
  2287. }
  2288. //
  2289. // globals
  2290. //
  2291. struct llama_logger_state {
  2292. ggml_log_callback log_callback = llama_log_callback_default;
  2293. void * log_callback_user_data = nullptr;
  2294. };
  2295. static llama_logger_state g_logger_state;
  2296. // available llama models
  2297. enum e_model {
  2298. MODEL_UNKNOWN,
  2299. MODEL_14M,
  2300. MODEL_17M,
  2301. MODEL_22M,
  2302. MODEL_33M,
  2303. MODEL_60M,
  2304. MODEL_70M,
  2305. MODEL_80M,
  2306. MODEL_109M,
  2307. MODEL_137M,
  2308. MODEL_160M,
  2309. MODEL_220M,
  2310. MODEL_250M,
  2311. MODEL_270M,
  2312. MODEL_335M,
  2313. MODEL_410M,
  2314. MODEL_450M,
  2315. MODEL_770M,
  2316. MODEL_780M,
  2317. MODEL_0_5B,
  2318. MODEL_1B,
  2319. MODEL_1_3B,
  2320. MODEL_1_4B,
  2321. MODEL_1_5B,
  2322. MODEL_1_6B,
  2323. MODEL_2B,
  2324. MODEL_2_8B,
  2325. MODEL_3B,
  2326. MODEL_4B,
  2327. MODEL_6B,
  2328. MODEL_6_9B,
  2329. MODEL_7B,
  2330. MODEL_8B,
  2331. MODEL_9B,
  2332. MODEL_11B,
  2333. MODEL_12B,
  2334. MODEL_13B,
  2335. MODEL_14B,
  2336. MODEL_15B,
  2337. MODEL_16B,
  2338. MODEL_20B,
  2339. MODEL_22B,
  2340. MODEL_30B,
  2341. MODEL_32B,
  2342. MODEL_34B,
  2343. MODEL_35B,
  2344. MODEL_40B,
  2345. MODEL_65B,
  2346. MODEL_70B,
  2347. MODEL_90B,
  2348. MODEL_236B,
  2349. MODEL_314B,
  2350. MODEL_SMALL,
  2351. MODEL_MEDIUM,
  2352. MODEL_LARGE,
  2353. MODEL_XL,
  2354. MODEL_A1_7B,
  2355. MODEL_A2_7B,
  2356. MODEL_8x7B,
  2357. MODEL_8x22B,
  2358. MODEL_16x12B,
  2359. MODEL_10B_128x3_66B,
  2360. MODEL_57B_A14B,
  2361. MODEL_27B,
  2362. };
  2363. static const size_t kiB = 1024;
  2364. static const size_t MiB = 1024*kiB;
  2365. static const size_t GiB = 1024*MiB;
  2366. struct llama_hparams {
  2367. bool vocab_only;
  2368. bool rope_finetuned;
  2369. bool use_par_res;
  2370. bool swin_norm;
  2371. uint32_t n_vocab;
  2372. uint32_t n_ctx_train; // context size the model was trained on
  2373. uint32_t n_embd;
  2374. uint32_t n_layer;
  2375. uint32_t n_rot;
  2376. uint32_t n_swa = 0; // sliding window attention (SWA)
  2377. 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
  2378. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  2379. uint32_t n_expert = 0;
  2380. uint32_t n_expert_used = 0;
  2381. uint32_t n_vocab_type = 0; // for BERT-style token types
  2382. uint32_t n_rel_attn_bkts = 0;
  2383. std::array<uint32_t, LLAMA_MAX_LAYERS> n_head_arr;
  2384. std::array<uint32_t, LLAMA_MAX_LAYERS> n_head_kv_arr;
  2385. std::array<uint32_t, LLAMA_MAX_LAYERS> n_ff_arr;
  2386. std::array<std::array<uint32_t, LLAMA_MAX_LAYERS>, 4> n_bskcn_arr;
  2387. std::array<uint32_t, LLAMA_MAX_LAYERS> cross_attn_layers;
  2388. uint32_t n_layer_dense_lead = 0;
  2389. uint32_t n_lora_q = 0;
  2390. uint32_t n_lora_kv = 0;
  2391. uint32_t n_ff_exp = 0;
  2392. uint32_t n_ff_shexp = 0;
  2393. uint32_t n_expert_shared = 0;
  2394. float expert_weights_scale = 0.0;
  2395. float f_norm_eps;
  2396. float f_norm_rms_eps;
  2397. float f_attn_logit_softcapping = 50.0f;
  2398. float f_final_logit_softcapping = 30.0f;
  2399. // for RWKV
  2400. uint32_t rescale_every_n_layers = 0;
  2401. uint32_t time_mix_extra_dim = 0;
  2402. uint32_t time_decay_extra_dim = 0;
  2403. uint32_t wkv_head_size = 0;
  2404. float rope_attn_factor = 1.0f;
  2405. float rope_freq_base_train;
  2406. float rope_freq_scale_train;
  2407. uint32_t n_ctx_orig_yarn;
  2408. float rope_yarn_log_mul;
  2409. // for State Space Models
  2410. uint32_t ssm_d_conv = 0;
  2411. uint32_t ssm_d_inner = 0;
  2412. uint32_t ssm_d_state = 0;
  2413. uint32_t ssm_dt_rank = 0;
  2414. bool ssm_dt_b_c_rms = false;
  2415. float f_clamp_kqv = 0.0f;
  2416. float f_max_alibi_bias = 0.0f;
  2417. float f_logit_scale = 0.0f;
  2418. // Additional scale factors (Granite/Granite MoE)
  2419. float f_residual_scale = 0.0f;
  2420. float f_embedding_scale = 0.0f;
  2421. float f_attention_scale = 0.0f;
  2422. bool causal_attn = true;
  2423. bool use_alibi = false;
  2424. bool attn_soft_cap = false;
  2425. // needed by encoder-decoder models (e.g. T5, FLAN-T5)
  2426. // ref: https://github.com/ggerganov/llama.cpp/pull/8141
  2427. llama_token dec_start_token_id = LLAMA_TOKEN_NULL;
  2428. enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_NONE;
  2429. enum llama_rope_type rope_type = LLAMA_ROPE_TYPE_NONE;
  2430. enum llama_rope_scaling_type rope_scaling_type_train = LLAMA_ROPE_SCALING_TYPE_NONE;
  2431. bool operator!=(const llama_hparams & other) const {
  2432. if (this->vocab_only != other.vocab_only) return true;
  2433. if (this->n_vocab != other.n_vocab) return true;
  2434. if (this->n_ctx_train != other.n_ctx_train) return true;
  2435. if (this->n_embd != other.n_embd) return true;
  2436. if (this->n_layer != other.n_layer) return true;
  2437. if (this->n_rot != other.n_rot) return true;
  2438. if (this->n_swa != other.n_swa) return true;
  2439. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  2440. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  2441. if (this->n_expert != other.n_expert) return true;
  2442. if (this->n_expert_used != other.n_expert_used) return true;
  2443. if (this->n_head_arr != other.n_head_arr) return true;
  2444. if (this->n_head_kv_arr != other.n_head_kv_arr) return true;
  2445. if (this->n_ff_arr != other.n_ff_arr) return true;
  2446. if (this->n_bskcn_arr != other.n_bskcn_arr) return true;
  2447. if (this->cross_attn_layers != other.cross_attn_layers) return true;
  2448. if (this->n_rel_attn_bkts != other.n_rel_attn_bkts) return true;
  2449. if (this->n_layer_dense_lead != other.n_layer_dense_lead) return true;
  2450. if (this->n_lora_q != other.n_lora_q) return true;
  2451. if (this->n_lora_kv != other.n_lora_kv) return true;
  2452. if (this->n_ff_exp != other.n_ff_exp) return true;
  2453. if (this->n_ff_shexp != other.n_ff_shexp) return true;
  2454. if (this->n_expert_shared != other.n_expert_shared) return true;
  2455. if (this->rope_finetuned != other.rope_finetuned) return true;
  2456. if (this->n_ctx_orig_yarn != other.n_ctx_orig_yarn) return true;
  2457. if (this->ssm_d_conv != other.ssm_d_conv) return true;
  2458. if (this->ssm_d_inner != other.ssm_d_inner) return true;
  2459. if (this->ssm_d_state != other.ssm_d_state) return true;
  2460. if (this->ssm_dt_rank != other.ssm_dt_rank) return true;
  2461. if (this->ssm_dt_b_c_rms != other.ssm_dt_b_c_rms) return true;
  2462. if (this->rescale_every_n_layers != other.rescale_every_n_layers) return true;
  2463. if (this->time_mix_extra_dim != other.time_mix_extra_dim) return true;
  2464. if (this->time_decay_extra_dim != other.time_decay_extra_dim) return true;
  2465. if (this->wkv_head_size != other.wkv_head_size) return true;
  2466. if (this->dec_start_token_id != other.dec_start_token_id) return true;
  2467. const float EPSILON = 1e-9f;
  2468. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  2469. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  2470. if (!is_float_close(this->rope_attn_factor, other.rope_attn_factor, EPSILON)) return true;
  2471. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  2472. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  2473. if (!is_float_close(this->expert_weights_scale, other.expert_weights_scale, EPSILON)) return true;
  2474. if (!is_float_close(this->rope_yarn_log_mul, other.rope_yarn_log_mul, EPSILON)) return true;
  2475. if (!is_float_close(this->f_residual_scale, other.f_residual_scale, EPSILON)) return true;
  2476. if (!is_float_close(this->f_embedding_scale, other.f_embedding_scale, EPSILON)) return true;
  2477. if (!is_float_close(this->f_attention_scale, other.f_attention_scale, EPSILON)) return true;
  2478. return false;
  2479. }
  2480. uint32_t n_head(uint32_t il = 0) const {
  2481. if (il < n_layer) {
  2482. return n_head_arr[il];
  2483. }
  2484. GGML_ABORT("fatal error");
  2485. }
  2486. uint32_t n_head_kv(uint32_t il = 0) const {
  2487. if (il < n_layer) {
  2488. return n_head_kv_arr[il];
  2489. }
  2490. GGML_ABORT("fatal error");
  2491. }
  2492. uint32_t n_ff(uint32_t il = 0) const {
  2493. if (il < n_layer) {
  2494. return n_ff_arr[il];
  2495. }
  2496. GGML_ABORT("fatal error");
  2497. }
  2498. uint32_t n_gqa(uint32_t il = 0) const {
  2499. const uint32_t n_head = this->n_head(il);
  2500. const uint32_t n_head_kv = this->n_head_kv(il);
  2501. if (n_head_kv == 0) {
  2502. return 0;
  2503. }
  2504. return n_head/n_head_kv;
  2505. }
  2506. uint32_t n_embd_k_gqa(uint32_t il = 0) const { // dimension of key embeddings across all k-v heads
  2507. const uint32_t n_head_kv = this->n_head_kv(il);
  2508. return n_embd_head_k * n_head_kv;
  2509. }
  2510. uint32_t n_embd_v_gqa(uint32_t il = 0) const { // dimension of value embeddings across all k-v heads
  2511. const uint32_t n_head_kv = this->n_head_kv(il);
  2512. return n_embd_head_v * n_head_kv;
  2513. }
  2514. uint32_t n_embd_k_s() const { // dimension of the rolling state embeddings
  2515. // corresponds to Mamba's conv_states size or RWKV's token_shift states size
  2516. if (wkv_head_size != 0) {
  2517. // for RWKV models
  2518. return 2 * n_embd;
  2519. } else {
  2520. // TODO: maybe support other convolution strides than 1
  2521. // NOTE: since the first column of the conv_state is shifted out each time, it's not actually needed
  2522. return (ssm_d_conv > 0 ? ssm_d_conv - 1 : 0) * ssm_d_inner;
  2523. }
  2524. }
  2525. uint32_t n_embd_v_s() const { // dimension of the recurrent state embeddings
  2526. if (wkv_head_size != 0) {
  2527. // corresponds to RWKV's wkv_states size
  2528. return n_embd * wkv_head_size;
  2529. } else {
  2530. // corresponds to Mamba's ssm_states size
  2531. return ssm_d_state * ssm_d_inner;
  2532. }
  2533. }
  2534. bool n_bskcn(uint32_t n, uint32_t il = 0) const {
  2535. if (il < n_layer) {
  2536. return n_bskcn_arr[n][il] > 0;
  2537. }
  2538. GGML_ABORT("fatal error");
  2539. }
  2540. bool cross_attention_layers(uint32_t il) const {
  2541. return std::find(cross_attn_layers.begin(), cross_attn_layers.end(), il) != cross_attn_layers.end();
  2542. }
  2543. };
  2544. static_assert(std::is_trivially_copyable<llama_hparams>::value, "llama_hparams must be trivially copyable");
  2545. struct llama_cparams {
  2546. uint32_t n_ctx; // context size used during inference
  2547. uint32_t n_batch;
  2548. uint32_t n_ubatch;
  2549. uint32_t n_seq_max;
  2550. int n_threads; // number of threads to use for generation
  2551. int n_threads_batch; // number of threads to use for batch processing
  2552. float rope_freq_base;
  2553. float rope_freq_scale;
  2554. uint32_t n_ctx_orig_yarn;
  2555. // These hyperparameters are not exposed in GGUF, because all
  2556. // existing YaRN models use the same values for them.
  2557. float yarn_ext_factor;
  2558. float yarn_attn_factor;
  2559. float yarn_beta_fast;
  2560. float yarn_beta_slow;
  2561. float defrag_thold;
  2562. bool embeddings;
  2563. bool causal_attn;
  2564. bool offload_kqv;
  2565. bool flash_attn;
  2566. bool no_perf;
  2567. // TODO (jmorganca): this should most likely be passed in as part of a batch
  2568. // and not set on the context for all batches.
  2569. bool cross_attn = false;
  2570. enum llama_pooling_type pooling_type;
  2571. ggml_backend_sched_eval_callback cb_eval;
  2572. void * cb_eval_user_data;
  2573. };
  2574. // TODO: separate into "llama_layer_enc" and "llama_layer_dec"
  2575. struct llama_layer {
  2576. llama_layer() {
  2577. // initialize all pointers to NULL
  2578. std::memset(this, 0, sizeof(*this));
  2579. }
  2580. // normalization
  2581. struct ggml_tensor * attn_norm;
  2582. struct ggml_tensor * attn_norm_b;
  2583. struct ggml_tensor * attn_norm_2;
  2584. struct ggml_tensor * attn_norm_2_b;
  2585. struct ggml_tensor * attn_q_norm;
  2586. struct ggml_tensor * attn_q_norm_b;
  2587. struct ggml_tensor * attn_k_norm;
  2588. struct ggml_tensor * attn_k_norm_b;
  2589. struct ggml_tensor * attn_out_norm;
  2590. struct ggml_tensor * attn_out_norm_b;
  2591. struct ggml_tensor * attn_q_a_norm;
  2592. struct ggml_tensor * attn_kv_a_norm;
  2593. struct ggml_tensor * attn_sub_norm;
  2594. struct ggml_tensor * attn_post_norm;
  2595. struct ggml_tensor * ffn_sub_norm;
  2596. struct ggml_tensor * attn_norm_cross;
  2597. struct ggml_tensor * attn_norm_enc;
  2598. // attention
  2599. struct ggml_tensor * wq;
  2600. struct ggml_tensor * wk;
  2601. struct ggml_tensor * wv;
  2602. struct ggml_tensor * wo;
  2603. struct ggml_tensor * wqkv;
  2604. struct ggml_tensor * wq_a;
  2605. struct ggml_tensor * wq_b;
  2606. struct ggml_tensor * wkv_a_mqa;
  2607. struct ggml_tensor * wkv_b;
  2608. struct ggml_tensor * wq_cross;
  2609. struct ggml_tensor * wk_cross;
  2610. struct ggml_tensor * wv_cross;
  2611. struct ggml_tensor * wo_cross;
  2612. struct ggml_tensor * wq_enc;
  2613. struct ggml_tensor * wk_enc;
  2614. struct ggml_tensor * wv_enc;
  2615. struct ggml_tensor * wo_enc;
  2616. // attention bias
  2617. struct ggml_tensor * bq;
  2618. struct ggml_tensor * bk;
  2619. struct ggml_tensor * bv;
  2620. struct ggml_tensor * bo;
  2621. struct ggml_tensor * bqkv;
  2622. // relative position bias
  2623. struct ggml_tensor * attn_rel_b;
  2624. struct ggml_tensor * attn_rel_b_enc;
  2625. struct ggml_tensor * attn_rel_b_cross;
  2626. // normalization
  2627. struct ggml_tensor * ffn_norm;
  2628. struct ggml_tensor * ffn_norm_b;
  2629. struct ggml_tensor * ffn_post_norm;
  2630. struct ggml_tensor * layer_out_norm;
  2631. struct ggml_tensor * layer_out_norm_b;
  2632. struct ggml_tensor * ffn_norm_exps;
  2633. struct ggml_tensor * ffn_norm_enc;
  2634. // ff
  2635. struct ggml_tensor * ffn_gate; // w1
  2636. struct ggml_tensor * ffn_down; // w2
  2637. struct ggml_tensor * ffn_up; // w3
  2638. struct ggml_tensor * ffn_gate_enc;
  2639. struct ggml_tensor * ffn_down_enc;
  2640. struct ggml_tensor * ffn_up_enc;
  2641. // ff MoE
  2642. struct ggml_tensor * ffn_gate_inp;
  2643. struct ggml_tensor * ffn_gate_exps;
  2644. struct ggml_tensor * ffn_down_exps;
  2645. struct ggml_tensor * ffn_up_exps ;
  2646. // ff shared expert (shexp)
  2647. struct ggml_tensor * ffn_gate_inp_shexp;
  2648. struct ggml_tensor * ffn_gate_shexp;
  2649. struct ggml_tensor * ffn_down_shexp;
  2650. struct ggml_tensor * ffn_up_shexp;
  2651. // ff bias
  2652. struct ggml_tensor * ffn_gate_b;
  2653. struct ggml_tensor * ffn_down_b; // b2
  2654. struct ggml_tensor * ffn_up_b; // b3
  2655. struct ggml_tensor * ffn_act;
  2656. // mamba proj
  2657. struct ggml_tensor * ssm_in;
  2658. struct ggml_tensor * ssm_x;
  2659. struct ggml_tensor * ssm_dt;
  2660. struct ggml_tensor * ssm_out;
  2661. // mamba
  2662. struct ggml_tensor * ssm_conv1d;
  2663. struct ggml_tensor * ssm_a;
  2664. struct ggml_tensor * ssm_d;
  2665. // mamba bias
  2666. struct ggml_tensor * ssm_conv1d_b;
  2667. struct ggml_tensor * ssm_dt_b;
  2668. // rwkv
  2669. struct ggml_tensor * time_mix_w1;
  2670. struct ggml_tensor * time_mix_w2;
  2671. struct ggml_tensor * time_mix_lerp_x;
  2672. struct ggml_tensor * time_mix_lerp_w;
  2673. struct ggml_tensor * time_mix_lerp_k;
  2674. struct ggml_tensor * time_mix_lerp_v;
  2675. struct ggml_tensor * time_mix_lerp_r;
  2676. struct ggml_tensor * time_mix_lerp_g;
  2677. struct ggml_tensor * time_mix_first;
  2678. struct ggml_tensor * time_mix_decay;
  2679. struct ggml_tensor * time_mix_decay_w1;
  2680. struct ggml_tensor * time_mix_decay_w2;
  2681. struct ggml_tensor * time_mix_key;
  2682. struct ggml_tensor * time_mix_value;
  2683. struct ggml_tensor * time_mix_receptance;
  2684. struct ggml_tensor * time_mix_gate;
  2685. struct ggml_tensor * time_mix_ln;
  2686. struct ggml_tensor * time_mix_ln_b;
  2687. struct ggml_tensor * time_mix_output;
  2688. struct ggml_tensor * channel_mix_lerp_k;
  2689. struct ggml_tensor * channel_mix_lerp_r;
  2690. struct ggml_tensor * channel_mix_key;
  2691. struct ggml_tensor * channel_mix_receptance;
  2692. struct ggml_tensor * channel_mix_value;
  2693. // long rope factors
  2694. struct ggml_tensor * rope_long = nullptr;
  2695. struct ggml_tensor * rope_short = nullptr;
  2696. struct ggml_tensor * rope_freqs = nullptr;
  2697. // bitnet scale
  2698. struct ggml_tensor * wq_scale;
  2699. struct ggml_tensor * wk_scale;
  2700. struct ggml_tensor * wv_scale;
  2701. struct ggml_tensor * wo_scale;
  2702. struct ggml_tensor * ffn_gate_scale;
  2703. struct ggml_tensor * ffn_up_scale;
  2704. struct ggml_tensor * ffn_down_scale;
  2705. struct ggml_tensor * bskcn_tv;
  2706. // cross attention
  2707. struct ggml_tensor * cross_attn_k_norm;
  2708. struct ggml_tensor * cross_attn_k_proj;
  2709. struct ggml_tensor * cross_attn_o_proj;
  2710. struct ggml_tensor * cross_attn_q_norm;
  2711. struct ggml_tensor * cross_attn_q_proj;
  2712. struct ggml_tensor * cross_attn_v_proj;
  2713. struct ggml_tensor * cross_attn_attn_gate;
  2714. struct ggml_tensor * cross_attn_mlp_gate;
  2715. };
  2716. // very similar to llama_batch,
  2717. // but has more metadata about sequences
  2718. struct llama_ubatch {
  2719. bool equal_seqs;
  2720. // TODO: whole_seqs for embeddings?
  2721. uint32_t n_tokens; // total tokens (n_seq_tokens * n_seqs)
  2722. uint32_t n_seq_tokens; // tokens per sequence
  2723. uint32_t n_seqs;
  2724. llama_token * token; // [n_tokens]
  2725. float * embd; // [n_embd, n_tokens]
  2726. llama_pos * pos; // [n_tokens]
  2727. int32_t * n_seq_id; // [n_seqs]
  2728. llama_seq_id ** seq_id; // [n_seqs]
  2729. int8_t * output; // [n_tokens]
  2730. };
  2731. struct llama_kv_cell {
  2732. llama_pos pos = -1;
  2733. llama_pos delta = 0;
  2734. int32_t src = -1; // used by recurrent state models to copy states
  2735. int32_t tail = -1;
  2736. std::set<llama_seq_id> seq_id;
  2737. bool has_seq_id(const llama_seq_id & id) const {
  2738. return seq_id.find(id) != seq_id.end();
  2739. }
  2740. bool is_empty() const {
  2741. return seq_id.empty();
  2742. }
  2743. bool is_same_seq(const llama_kv_cell & other) const {
  2744. return seq_id == other.seq_id;
  2745. }
  2746. };
  2747. // ring-buffer of cached KV data
  2748. struct llama_kv_cache {
  2749. bool has_shift = false;
  2750. bool do_defrag = false;
  2751. bool recurrent = false; // with recurrent state models, a cell can hold the state for more than one past token
  2752. bool v_trans = true; // the value tensor is transposed
  2753. // Note: The value of head isn't only used to optimize searching
  2754. // for a free KV slot. llama_decode_internal also uses it, so it
  2755. // cannot be freely changed after a slot has been allocated.
  2756. uint32_t head = 0;
  2757. uint32_t size = 0;
  2758. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  2759. // computed before each graph build
  2760. uint32_t n = 0;
  2761. ggml_type type_k = GGML_TYPE_F16;
  2762. ggml_type type_v = GGML_TYPE_F16;
  2763. std::vector<llama_kv_cell> cells;
  2764. std::vector<struct ggml_tensor *> k_l; // per layer
  2765. std::vector<struct ggml_tensor *> v_l;
  2766. std::vector<ggml_context_ptr> ctxs;
  2767. std::vector<ggml_backend_buffer_ptr> bufs;
  2768. size_t total_size() {
  2769. size_t size = 0;
  2770. for (auto & buf : bufs) {
  2771. size += ggml_backend_buffer_get_size(buf.get());
  2772. }
  2773. return size;
  2774. }
  2775. };
  2776. struct llama_control_vector {
  2777. std::vector<struct ggml_tensor *> tensors; // per layer
  2778. std::vector<ggml_context_ptr> ctxs;
  2779. std::vector<ggml_backend_buffer_ptr> bufs;
  2780. int32_t layer_start = -1;
  2781. int32_t layer_end = -1;
  2782. struct ggml_tensor * tensor_for(int il) const {
  2783. if (il < 0 || il < layer_start || il > layer_end || (size_t) il >= tensors.size()) {
  2784. return nullptr;
  2785. }
  2786. return tensors[il];
  2787. }
  2788. struct ggml_tensor * apply_to(struct ggml_context * ctx, struct ggml_tensor * cur, int il) const {
  2789. ggml_tensor * layer_dir = tensor_for(il);
  2790. if (layer_dir != nullptr) {
  2791. cur = ggml_add(ctx, cur, layer_dir);
  2792. }
  2793. return cur;
  2794. }
  2795. };
  2796. struct llama_model {
  2797. e_model type = MODEL_UNKNOWN;
  2798. llm_arch arch = LLM_ARCH_UNKNOWN;
  2799. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  2800. std::string name = "n/a";
  2801. llama_hparams hparams = {};
  2802. llama_vocab vocab;
  2803. struct ggml_tensor * tok_embd = nullptr;
  2804. struct ggml_tensor * type_embd = nullptr;
  2805. struct ggml_tensor * pos_embd = nullptr;
  2806. struct ggml_tensor * tok_norm = nullptr;
  2807. struct ggml_tensor * tok_norm_b = nullptr;
  2808. struct ggml_tensor * output_norm = nullptr;
  2809. struct ggml_tensor * output_norm_b = nullptr;
  2810. struct ggml_tensor * output = nullptr;
  2811. struct ggml_tensor * output_b = nullptr;
  2812. struct ggml_tensor * output_norm_enc = nullptr;
  2813. // classifier
  2814. struct ggml_tensor * cls = nullptr;
  2815. struct ggml_tensor * cls_b = nullptr;
  2816. struct ggml_tensor * cls_out = nullptr;
  2817. struct ggml_tensor * cls_out_b = nullptr;
  2818. std::vector<llama_layer> layers;
  2819. // gguf metadata
  2820. std::unordered_map<std::string, std::string> gguf_kv;
  2821. llama_split_mode split_mode;
  2822. int main_gpu;
  2823. int n_gpu_layers;
  2824. std::vector<std::string> rpc_servers;
  2825. // list of devices used in this model
  2826. std::vector<ggml_backend_dev_t> devices;
  2827. // lists of buffer types used for each layer
  2828. using buft_list_t = std::vector<std::pair<ggml_backend_dev_t, ggml_backend_buffer_type_t>>;
  2829. buft_list_t cpu_buft_list;
  2830. std::map<ggml_backend_dev_t, buft_list_t> gpu_buft_list;
  2831. struct layer_dev {
  2832. ggml_backend_dev_t dev;
  2833. buft_list_t * buft_list;
  2834. };
  2835. layer_dev dev_input = {};
  2836. layer_dev dev_output = {};
  2837. std::vector<layer_dev> dev_layer;
  2838. // contexts where the model tensors metadata is stored
  2839. std::vector<ggml_context_ptr> ctxs;
  2840. // the model memory buffers for the tensor data
  2841. std::vector<ggml_backend_buffer_ptr> bufs;
  2842. // model memory mapped files
  2843. llama_mmaps mappings;
  2844. // objects representing data potentially being locked in memory
  2845. llama_mlocks mlock_bufs;
  2846. llama_mlocks mlock_mmaps;
  2847. // for quantize-stats only
  2848. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  2849. int64_t t_load_us = 0;
  2850. int64_t t_start_us = 0;
  2851. // total number of parameters in the model
  2852. uint64_t n_elements = 0;
  2853. // total size of all the tensors in the model in bytes
  2854. size_t n_bytes = 0;
  2855. // keep track of loaded lora adapters
  2856. std::set<struct llama_lora_adapter *> lora_adapters;
  2857. ~llama_model() {
  2858. while (!lora_adapters.empty()) {
  2859. llama_lora_adapter_free(*lora_adapters.begin());
  2860. }
  2861. }
  2862. };
  2863. struct llama_sbatch_seq {
  2864. int32_t n_seq_id;
  2865. llama_seq_id * seq_id;
  2866. size_t offset;
  2867. size_t length;
  2868. };
  2869. // sequence-length-aware batch splitting
  2870. struct llama_sbatch {
  2871. // tokens left in this batch
  2872. size_t n_tokens;
  2873. size_t n_embd;
  2874. bool logits_all; // TODO: remove once lctx.logits_all is removed too
  2875. // sorted indices into the batch
  2876. std::vector<size_t> ids;
  2877. // batch indices of the output
  2878. std::vector<size_t> out_ids;
  2879. std::vector<llama_sbatch_seq> seq;
  2880. const llama_batch * batch = nullptr;
  2881. // buffers for the ubatch
  2882. std::vector<llama_token> ubatch_token;
  2883. std::vector<float> ubatch_embd;
  2884. std::vector<llama_pos> ubatch_pos;
  2885. std::vector<int32_t> ubatch_n_seq_id;
  2886. std::vector<llama_seq_id *> ubatch_seq_id;
  2887. std::vector<int8_t> ubatch_output;
  2888. llama_ubatch reserve_ubatch(size_t n_ubatch, bool has_embd = false) {
  2889. // clear empty sequences
  2890. // the previous ubatch is assumed to be gone,
  2891. // so nothing should refer to values in these sequences anymore.
  2892. for (size_t i = seq.size(); i-- > 0;) {
  2893. if (seq[i].length == 0) {
  2894. seq.pop_back();
  2895. } else {
  2896. break;
  2897. }
  2898. }
  2899. ubatch_token.resize(!has_embd ? n_ubatch : 0);
  2900. ubatch_embd.resize(has_embd ? n_embd * n_ubatch : 0);
  2901. ubatch_pos.resize(n_ubatch);
  2902. ubatch_n_seq_id.resize(n_ubatch);
  2903. ubatch_seq_id.resize(n_ubatch);
  2904. ubatch_output.resize(n_ubatch);
  2905. llama_ubatch ubatch = {
  2906. /*equal_seqs =*/ true,
  2907. /*n_tokens =*/ 0,
  2908. /*n_seq_tokens =*/ 0,
  2909. /*n_seqs =*/ 0,
  2910. /*token =*/ !has_embd ? ubatch_token.data() : nullptr,
  2911. /*embd =*/ has_embd ? ubatch_embd.data() : nullptr,
  2912. /*pos =*/ ubatch_pos.data(),
  2913. /*n_seq_id =*/ ubatch_n_seq_id.data(),
  2914. /*seq_id =*/ ubatch_seq_id.data(),
  2915. /*output =*/ ubatch_output.data(),
  2916. };
  2917. return ubatch;
  2918. }
  2919. void add_seq_to_ubatch(llama_ubatch & ubatch, llama_sbatch_seq & seq, size_t length) {
  2920. GGML_ASSERT(batch != nullptr);
  2921. GGML_ASSERT(length <= seq.length);
  2922. // Can only add sequences of equal lengths to a batch,
  2923. // otherwise it isn't clear to which sequence a token belongs
  2924. GGML_ASSERT(seq.n_seq_id == 0 || ubatch.n_seqs == 0 || length == (size_t) ubatch.n_tokens / ubatch.n_seqs);
  2925. GGML_ASSERT((seq.n_seq_id != 0) == ubatch.equal_seqs);
  2926. // NOTE: loops are separated for cache-friendliness
  2927. if (batch->token) {
  2928. if (ubatch.equal_seqs) {
  2929. for (size_t i = 0; i < length; ++i) {
  2930. ubatch.token[ubatch.n_tokens + i] = batch->token[ids[seq.offset + i]];
  2931. }
  2932. } else {
  2933. // simple split
  2934. ubatch.token = batch->token + seq.offset;
  2935. }
  2936. } else {
  2937. ubatch.token = nullptr;
  2938. }
  2939. if (batch->embd) {
  2940. if (ubatch.equal_seqs) {
  2941. for (size_t i = 0; i < length; ++i) {
  2942. memcpy(
  2943. ubatch.embd + n_embd * (ubatch.n_tokens + i),
  2944. batch->embd + n_embd * ids[seq.offset + i],
  2945. n_embd * sizeof(float)
  2946. );
  2947. }
  2948. } else {
  2949. // simple split
  2950. ubatch.embd = batch->embd + (n_embd * seq.offset);
  2951. }
  2952. } else {
  2953. ubatch.embd = nullptr;
  2954. }
  2955. if (ubatch.equal_seqs) {
  2956. for (size_t i = 0; i < length; ++i) {
  2957. ubatch.pos[ubatch.n_tokens + i] = batch->pos[ids[seq.offset + i]];
  2958. }
  2959. } else {
  2960. // simple split
  2961. ubatch.pos = batch->pos + seq.offset;
  2962. }
  2963. if (ubatch.equal_seqs) {
  2964. ubatch.n_seq_id[ubatch.n_seqs] = seq.n_seq_id;
  2965. if (seq.seq_id) {
  2966. ubatch.seq_id[ubatch.n_seqs] = seq.seq_id;
  2967. }
  2968. } else {
  2969. // simple split
  2970. if (batch->n_seq_id) {
  2971. ubatch.n_seq_id = batch->n_seq_id + seq.offset;
  2972. } else {
  2973. for (size_t i = 0; i < length; ++i) {
  2974. ubatch.n_seq_id[ubatch.n_seqs + i] = 1;
  2975. }
  2976. }
  2977. if (batch->seq_id) {
  2978. ubatch.seq_id = batch->seq_id + seq.offset;
  2979. }
  2980. }
  2981. if (logits_all) {
  2982. for (size_t i = 0; i < length; ++i) {
  2983. ubatch.output[ubatch.n_tokens + i] = 1;
  2984. out_ids.push_back(ids[seq.offset + i]);
  2985. }
  2986. } else if (batch->logits) {
  2987. if (ubatch.equal_seqs) {
  2988. for (size_t i = 0; i < length; ++i) {
  2989. size_t id = ids[seq.offset + i];
  2990. int8_t is_output = batch->logits[id];
  2991. ubatch.output[ubatch.n_tokens + i] = is_output;
  2992. if (is_output) { out_ids.push_back(id); }
  2993. }
  2994. } else {
  2995. // simple split
  2996. ubatch.output = batch->logits + seq.offset;
  2997. for (size_t i = 0; i < length; ++i) {
  2998. if (ubatch.output[i] != 0) { out_ids.push_back(seq.offset + i); }
  2999. }
  3000. }
  3001. } else {
  3002. // only get last output
  3003. for (size_t i = 0; i < length; ++i) {
  3004. size_t id = ids[seq.offset + i];
  3005. int8_t is_last = id == ids.size() - 1;
  3006. ubatch.output[ubatch.n_tokens + i] = is_last;
  3007. if (is_last) { out_ids.push_back(id); }
  3008. }
  3009. }
  3010. if (ubatch.n_tokens == 0 && ubatch.n_seqs == 0) {
  3011. ubatch.n_seq_tokens = ubatch.equal_seqs ? length : 1;
  3012. }
  3013. ubatch.n_tokens += length;
  3014. ubatch.n_seqs += ubatch.equal_seqs ? 1 : length; // virtual sequences for simple splits
  3015. seq.offset += length;
  3016. seq.length -= length;
  3017. n_tokens -= length;
  3018. GGML_ASSERT(ubatch.n_tokens == ubatch.n_seq_tokens * ubatch.n_seqs);
  3019. }
  3020. // simple split, unknown number of sequences of unequal lengths
  3021. llama_ubatch split_simple(size_t n_ubatch) {
  3022. n_ubatch = n_tokens < n_ubatch ? n_tokens : n_ubatch;
  3023. llama_ubatch ubatch = reserve_ubatch(n_ubatch, /* has_embd */ batch->embd != nullptr);
  3024. ubatch.equal_seqs = false;
  3025. if (!seq.empty()) {
  3026. llama_sbatch_seq & s = seq[0];
  3027. size_t length = s.length < n_ubatch ? s.length : n_ubatch;
  3028. GGML_ASSERT(seq.size() == 1 && s.n_seq_id == 0); // don't mix with other splits
  3029. add_seq_to_ubatch(ubatch, s, length);
  3030. }
  3031. return ubatch;
  3032. }
  3033. // make batches of equal-length sequences
  3034. llama_ubatch split_equal(size_t n_ubatch) {
  3035. n_ubatch = n_tokens < n_ubatch ? n_tokens : n_ubatch;
  3036. llama_ubatch ubatch = reserve_ubatch(n_ubatch, /* has_embd */ batch->embd != nullptr);
  3037. if (!seq.empty()) {
  3038. size_t length = 0;
  3039. size_t n_tokens_in_ubatch = 0;
  3040. GGML_ASSERT(seq[0].n_seq_id > 0); // should not be mixed with simple splits
  3041. // smallest first, because it's easier to split this way;
  3042. // starting from the end to pop in constant time.
  3043. for (size_t i = seq.size(); i-- > 0;) {
  3044. llama_sbatch_seq & s = seq[i];
  3045. GGML_ASSERT(s.length > 0);
  3046. if (length == 0) {
  3047. length = s.length < n_ubatch ? s.length : n_ubatch;
  3048. }
  3049. add_seq_to_ubatch(ubatch, s, length);
  3050. n_tokens_in_ubatch += length;
  3051. // shared prompts can't be mixed with any of their sequences,
  3052. // so it's safer to compute them in their own ubatch
  3053. if (s.n_seq_id > 1) { break; }
  3054. // stop when there isn't enough space for another sequence
  3055. if (length + n_tokens_in_ubatch > n_ubatch) { break; }
  3056. }
  3057. }
  3058. return ubatch;
  3059. }
  3060. // sequence-wise split
  3061. llama_ubatch split_seq(size_t n_ubatch) {
  3062. n_ubatch = n_tokens < n_ubatch ? n_tokens : n_ubatch;
  3063. llama_ubatch ubatch = reserve_ubatch(n_ubatch, /* has_embd */ batch->embd != nullptr);
  3064. if (!seq.empty()) {
  3065. llama_sbatch_seq & s = seq[seq.size() - 1];
  3066. size_t length = s.length < n_ubatch ? s.length : n_ubatch;
  3067. GGML_ASSERT(s.n_seq_id > 0); // should not be mixed with simple splits
  3068. add_seq_to_ubatch(ubatch, s, length);
  3069. }
  3070. return ubatch;
  3071. }
  3072. void from_batch(const llama_batch & batch, const size_t n_embd, const bool simple_split = false, const bool logits_all = false) {
  3073. GGML_ASSERT(batch.n_tokens >= 0);
  3074. this->batch = &batch;
  3075. this->n_embd = n_embd;
  3076. this->logits_all = logits_all;
  3077. n_tokens = batch.n_tokens;
  3078. ids.resize(n_tokens);
  3079. out_ids.clear();
  3080. // TODO: reserve out_ids and seq
  3081. for (size_t i = 0; i < n_tokens; ++i) {
  3082. ids[i] = i;
  3083. }
  3084. if (simple_split) {
  3085. seq.resize(1);
  3086. llama_sbatch_seq & s = seq[0];
  3087. s.n_seq_id = 0;
  3088. s.seq_id = nullptr;
  3089. s.offset = 0;
  3090. s.length = n_tokens;
  3091. return;
  3092. }
  3093. std::sort(ids.begin(), ids.end(),
  3094. [&batch](size_t a, size_t b) {
  3095. int32_t n_seq_a = batch.n_seq_id ? batch.n_seq_id[a] : 1;
  3096. int32_t n_seq_b = batch.n_seq_id ? batch.n_seq_id[b] : 1;
  3097. // sort by seq_id, then by pos
  3098. if (n_seq_a == n_seq_b) {
  3099. if (batch.seq_id) {
  3100. for (int32_t i = 0; i < n_seq_a; ++i) {
  3101. llama_seq_id seq_id_a = batch.seq_id[a][i];
  3102. llama_seq_id seq_id_b = batch.seq_id[b][i];
  3103. // smaller seq_ids go first
  3104. if (seq_id_a != seq_id_b) {
  3105. return seq_id_a < seq_id_b;
  3106. }
  3107. }
  3108. }
  3109. // when all else is equal, sort by pos
  3110. if (batch.pos) {
  3111. return batch.pos[a] < batch.pos[b];
  3112. }
  3113. // no pos, sort by id
  3114. return a < b;
  3115. }
  3116. // shared prompts go first
  3117. return n_seq_a > n_seq_b;
  3118. }
  3119. );
  3120. // init seq
  3121. llama_sbatch_seq * last_seq = nullptr;
  3122. for (size_t i = 0; i < n_tokens; ++i) {
  3123. const size_t bi = ids[i];
  3124. const int32_t n_seqs = batch.n_seq_id[bi];
  3125. llama_seq_id * seq_ids = batch.seq_id[bi];
  3126. if (last_seq != nullptr) {
  3127. bool same = n_seqs == last_seq->n_seq_id;
  3128. for (int32_t j = 0; same && j < n_seqs; ++j) {
  3129. if (seq_ids[j] != last_seq->seq_id[j]) {
  3130. same = false;
  3131. }
  3132. }
  3133. if (same) {
  3134. last_seq->length += 1;
  3135. continue;
  3136. }
  3137. }
  3138. llama_sbatch_seq new_seq = {n_seqs, seq_ids, i, 1};
  3139. seq.push_back(new_seq);
  3140. last_seq = &seq.back();
  3141. }
  3142. // keep shared prompts first at the end, then sort by length descending.
  3143. std::sort(seq.begin(), seq.end(),
  3144. [](llama_sbatch_seq & a, llama_sbatch_seq & b) {
  3145. if (a.n_seq_id == b.n_seq_id) {
  3146. return a.length > b.length;
  3147. }
  3148. return a.n_seq_id < b.n_seq_id;
  3149. }
  3150. );
  3151. }
  3152. };
  3153. struct llama_context {
  3154. llama_context(const llama_model & model)
  3155. : model(model)
  3156. , t_start_us(model.t_start_us)
  3157. , t_load_us(model.t_load_us) {}
  3158. const struct llama_model & model;
  3159. struct llama_cparams cparams;
  3160. struct llama_sbatch sbatch;
  3161. struct llama_kv_cache kv_self;
  3162. struct llama_control_vector cvec;
  3163. std::unordered_map<struct llama_lora_adapter *, float> lora_adapters;
  3164. std::vector<ggml_backend_ptr> backends;
  3165. std::vector<std::pair<ggml_backend_t, ggml_backend_set_n_threads_t>> set_n_threads_fns;
  3166. ggml_backend_t backend_cpu = nullptr;
  3167. ggml_threadpool_t threadpool = nullptr;
  3168. ggml_threadpool_t threadpool_batch = nullptr;
  3169. bool has_evaluated_once = false;
  3170. mutable int64_t t_start_us;
  3171. mutable int64_t t_load_us;
  3172. mutable int64_t t_p_eval_us = 0;
  3173. mutable int64_t t_eval_us = 0;
  3174. mutable int64_t t_compute_start_us = 0;
  3175. mutable int64_t n_queued_tokens = 0;
  3176. mutable int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  3177. mutable int32_t n_eval = 0; // number of eval calls
  3178. // host buffer for the model output (logits and embeddings)
  3179. ggml_backend_buffer_ptr buf_output;
  3180. // decode output (2-dimensional array: [n_outputs][n_vocab])
  3181. size_t logits_size = 0; // capacity (of floats) for logits
  3182. float * logits = nullptr;
  3183. std::vector<int32_t> output_ids; // map batch token positions to ids of the logits and embd buffers
  3184. size_t output_size = 0; // capacity (of tokens positions) for the output buffers
  3185. int32_t n_outputs = 0; // number of actually-used outputs in the current ubatch or last logical batch
  3186. bool logits_all = false;
  3187. // embeddings output (2-dimensional array: [n_outputs][n_embd])
  3188. // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE
  3189. size_t embd_size = 0; // capacity (of floats) for embeddings
  3190. float * embd = nullptr;
  3191. // sequence embeddings output (map of [n_embd] vectors)
  3192. // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE
  3193. std::map<llama_seq_id, std::vector<float>> embd_seq;
  3194. // whether we are computing encoder output or decoder output
  3195. bool is_encoding = false;
  3196. // output of the encoder part of the encoder-decoder models
  3197. std::vector<float> embd_enc;
  3198. std::vector<std::set<llama_seq_id>> seq_ids_enc;
  3199. // memory buffers used to evaluate the model
  3200. std::vector<uint8_t> buf_compute_meta;
  3201. ggml_backend_sched_ptr sched;
  3202. ggml_abort_callback abort_callback = nullptr;
  3203. void * abort_callback_data = nullptr;
  3204. // input tensors
  3205. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  3206. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  3207. struct ggml_tensor * inp_pos; // I32 [n_batch]
  3208. struct ggml_tensor * inp_out_ids; // I32 [n_outputs]
  3209. struct ggml_tensor * inp_KQ_mask; // F32 [kv_size, n_batch]
  3210. struct ggml_tensor * inp_KQ_mask_swa; // F32 [kv_size, n_batch]
  3211. struct ggml_tensor * inp_K_shift; // I32 [kv_size]
  3212. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  3213. struct ggml_tensor * inp_cls; // I32 [n_batch]
  3214. struct ggml_tensor * inp_s_copy; // I32 [kv_size]
  3215. struct ggml_tensor * inp_s_mask; // F32 [1, n_kv]
  3216. struct ggml_tensor * inp_s_seq; // I32 [n_kv, n_batch]
  3217. struct ggml_tensor * inp_pos_bucket; // I32 [n_batch|n_kv, n_batch]
  3218. struct ggml_tensor * inp_embd_enc; // F32 [n_embd, n_outputs_enc]
  3219. struct ggml_tensor * inp_KQ_mask_cross; // F32 [n_outputs_enc, n_batch]
  3220. struct ggml_tensor * inp_cross_attn_state; // F32 [4, n_embd, 1061]
  3221. };
  3222. struct llama_lora_weight {
  3223. struct ggml_tensor * a = nullptr;
  3224. struct ggml_tensor * b = nullptr;
  3225. llama_lora_weight() = default;
  3226. llama_lora_weight(struct ggml_tensor * a, struct ggml_tensor * b): a(a), b(b) {}
  3227. };
  3228. struct llama_lora_adapter {
  3229. struct llama_model * base_model;
  3230. // map tensor name to lora_a_b
  3231. std::unordered_map<std::string, struct llama_lora_weight> ab_map;
  3232. std::vector<ggml_context_ptr> ctxs;
  3233. std::vector<ggml_backend_buffer_ptr> bufs;
  3234. float alpha;
  3235. llama_lora_adapter(struct llama_model * base_model): base_model(base_model) {
  3236. base_model->lora_adapters.insert(this);
  3237. }
  3238. llama_lora_weight * get_weight(struct ggml_tensor * w) {
  3239. std::string name(w->name);
  3240. auto pos = ab_map.find(name);
  3241. if (ab_map.find(name) != ab_map.end()) {
  3242. return &pos->second;
  3243. }
  3244. return nullptr;
  3245. }
  3246. ~llama_lora_adapter() {
  3247. auto pos = base_model->lora_adapters.find(this);
  3248. if (pos != base_model->lora_adapters.end()) {
  3249. base_model->lora_adapters.erase(pos);
  3250. }
  3251. }
  3252. };
  3253. static int llama_get_device_count(const llama_model & model) {
  3254. return (int) model.devices.size();
  3255. }
  3256. template<typename F>
  3257. static bool buft_supported(ggml_backend_buffer_type_t buft, ggml_backend_dev_t dev, F & fn) {
  3258. ggml_init_params params = {
  3259. /*.mem_size =*/ ggml_tensor_overhead()*8,
  3260. /*.mem_buffer =*/ NULL,
  3261. /*.no_alloc =*/ true,
  3262. };
  3263. ggml_context_ptr ctx { ggml_init(params) };
  3264. if (!ctx) {
  3265. throw std::runtime_error(format("failed to create ggml context"));
  3266. }
  3267. ggml_backend_buffer_ptr buf { ggml_backend_buft_alloc_buffer(buft, 0) };
  3268. ggml_tensor * op_tensor = fn(ctx.get());
  3269. for (int i = 0; i < GGML_MAX_SRC; i++) {
  3270. if (op_tensor->src[i] != nullptr) {
  3271. assert(op_tensor->src[i]->buffer == nullptr);
  3272. op_tensor->src[i]->buffer = buf.get();
  3273. }
  3274. }
  3275. bool op_supported = ggml_backend_dev_supports_op(dev, op_tensor);
  3276. return op_supported;
  3277. }
  3278. template<typename F>
  3279. static ggml_backend_buffer_type_t select_buft(const llama_model::buft_list_t & buft_list, const F & fn) {
  3280. for (const auto & cur : buft_list) {
  3281. ggml_backend_dev_t cur_dev = cur.first;
  3282. ggml_backend_buffer_type_t cur_buft = cur.second;
  3283. if (buft_supported(cur_buft, cur_dev, fn)) {
  3284. return cur_buft;
  3285. }
  3286. }
  3287. throw std::runtime_error(format("no suitable buffer type found"));
  3288. }
  3289. //
  3290. // kv cache helpers
  3291. //
  3292. static bool llama_kv_cache_init(
  3293. struct llama_kv_cache & cache,
  3294. const llama_context * ctx,
  3295. ggml_type type_k,
  3296. ggml_type type_v,
  3297. uint32_t kv_size,
  3298. bool offload) {
  3299. const llama_model & model = ctx->model;
  3300. const llama_cparams & cparams = ctx->cparams;
  3301. const struct llama_hparams & hparams = model.hparams;
  3302. const int64_t n_layer = hparams.n_layer;
  3303. cache.has_shift = false;
  3304. cache.recurrent = llama_model_is_recurrent(&model);
  3305. cache.v_trans = !cache.recurrent && !cparams.flash_attn;
  3306. cache.head = 0;
  3307. cache.size = kv_size;
  3308. cache.used = 0;
  3309. cache.type_k = type_k;
  3310. cache.type_v = type_v;
  3311. cache.cells.clear();
  3312. cache.cells.resize(kv_size);
  3313. // create a context for each buffer type
  3314. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3315. auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
  3316. auto it = ctx_map.find(buft);
  3317. if (it == ctx_map.end()) {
  3318. struct ggml_init_params params = {
  3319. /*.mem_size =*/ size_t(2u*n_layer*ggml_tensor_overhead()),
  3320. /*.mem_buffer =*/ NULL,
  3321. /*.no_alloc =*/ true,
  3322. };
  3323. ggml_context * ctx = ggml_init(params);
  3324. if (!ctx) {
  3325. return nullptr;
  3326. }
  3327. ctx_map[buft] = ctx;
  3328. cache.ctxs.emplace_back(ctx);
  3329. return ctx;
  3330. }
  3331. return it->second;
  3332. };
  3333. cache.k_l.reserve(n_layer);
  3334. cache.v_l.reserve(n_layer);
  3335. for (int i = 0; i < (int) n_layer; i++) {
  3336. // for cross attention layers
  3337. if (model.arch == LLM_ARCH_MLLAMA && hparams.cross_attention_layers(i)) {
  3338. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(i) + hparams.n_embd_k_s();
  3339. const llama_model::buft_list_t * buft_list;
  3340. if (offload) {
  3341. buft_list = model.dev_layer.at(i).buft_list;
  3342. } else {
  3343. buft_list = &model.cpu_buft_list;
  3344. }
  3345. ggml_backend_buffer_type_t buft = select_buft(*buft_list,
  3346. [&](ggml_context * ctx) {
  3347. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  3348. if (hparams.rope_type == LLAMA_ROPE_TYPE_NONE) {
  3349. return k;
  3350. }
  3351. ggml_tensor * p = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 1);
  3352. return ggml_rope(ctx, k, p, hparams.n_rot, hparams.rope_type);
  3353. });
  3354. ggml_context * ctx = ctx_for_buft(buft);
  3355. if (!ctx) {
  3356. LLAMA_LOG_ERROR("%s: failed to create ggml context for kv cache\n", __func__);
  3357. return false;
  3358. }
  3359. ggml_tensor * k = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, hparams.n_embd_head_k, 6404, hparams.n_head_kv(i));
  3360. ggml_tensor * v = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, hparams.n_embd_head_v, 6404, hparams.n_head_kv(i));
  3361. ggml_format_name(k, "cache_k_l%d", i);
  3362. ggml_format_name(v, "cache_v_l%d", i);
  3363. cache.k_l.push_back(k);
  3364. cache.v_l.push_back(v);
  3365. continue;
  3366. }
  3367. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(i) + hparams.n_embd_k_s();
  3368. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(i) + hparams.n_embd_v_s();
  3369. ggml_backend_buffer_type_t buft;
  3370. if (offload) {
  3371. auto * dev = model.dev_layer.at(i).dev;
  3372. buft = ggml_backend_dev_buffer_type(dev);
  3373. } else {
  3374. buft = ggml_backend_cpu_buffer_type();
  3375. }
  3376. ggml_context * ctx = ctx_for_buft(buft);
  3377. if (!ctx) {
  3378. LLAMA_LOG_ERROR("%s: failed to create ggml context for kv cache\n", __func__);
  3379. return false;
  3380. }
  3381. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  3382. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*kv_size);
  3383. ggml_format_name(k, "cache_k_l%d", i);
  3384. ggml_format_name(v, "cache_v_l%d", i);
  3385. cache.k_l.push_back(k);
  3386. cache.v_l.push_back(v);
  3387. }
  3388. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  3389. for (auto it : ctx_map) {
  3390. auto * buft = it.first;
  3391. auto * ctx = it.second;
  3392. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  3393. if (!buf) {
  3394. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  3395. return false;
  3396. }
  3397. ggml_backend_buffer_clear(buf, 0);
  3398. 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);
  3399. cache.bufs.emplace_back(buf);
  3400. }
  3401. return true;
  3402. }
  3403. // a structure holds information about the slot found in llama_kv_cache_find_slot
  3404. struct llama_kv_cache_slot_info {
  3405. std::pair<uint32_t, uint32_t> boundaries; // slot boundaries [begin, end)
  3406. bool found = false; // the slot was found
  3407. explicit llama_kv_cache_slot_info(bool found_) : found{found_} {}
  3408. llama_kv_cache_slot_info(uint32_t begin, uint32_t end) : boundaries{begin, end}, found{true} {}
  3409. operator bool() const { return found; }
  3410. };
  3411. static const llama_kv_cache_slot_info llama_kv_cache_slot_info_failed{false};
  3412. // find an empty slot of size "n_tokens" in the cache
  3413. // updates the cache head
  3414. // returns a structure holding information about the slot found
  3415. // Note: On success, it's important that cache.head points
  3416. // to the first cell of the slot.
  3417. static struct llama_kv_cache_slot_info llama_kv_cache_find_slot(
  3418. struct llama_kv_cache & cache,
  3419. const struct llama_ubatch & batch) {
  3420. const uint32_t n_tokens = batch.n_tokens;
  3421. const uint32_t n_seqs = batch.n_seqs;
  3422. const uint32_t n_seq_tokens = batch.n_seq_tokens;
  3423. if (cache.recurrent) {
  3424. // For recurrent state architectures (like Mamba or RWKV),
  3425. // each cache cell can store the state for a whole sequence.
  3426. // A slot should be always be contiguous.
  3427. // can only process batches with an equal number of new tokens in each sequence
  3428. GGML_ASSERT(batch.equal_seqs);
  3429. int32_t min = cache.size - 1;
  3430. int32_t max = 0;
  3431. // everything should fit if all seq_ids are smaller than the max
  3432. for (uint32_t s = 0; s < n_seqs; ++s) {
  3433. const uint32_t n_seq_id = batch.n_seq_id[s];
  3434. for (uint32_t j = 0; j < n_seq_id; ++j) {
  3435. const llama_seq_id seq_id = batch.seq_id[s][j];
  3436. if (seq_id < 0 || (uint32_t) seq_id >= cache.size) {
  3437. // too big seq_id
  3438. // TODO: would it be possible to resize the cache instead?
  3439. LLAMA_LOG_ERROR("%s: seq_id=%d >= n_seq_max=%d Try using a bigger --parallel value\n", __func__, seq_id, cache.size);
  3440. return llama_kv_cache_slot_info_failed;
  3441. }
  3442. if (j > 0) {
  3443. llama_kv_cell & seq = cache.cells[seq_id];
  3444. if (seq.tail >= 0) {
  3445. llama_kv_cell & cell = cache.cells[seq.tail];
  3446. // clear cells from seq_ids that become shared
  3447. // (should not normally happen, but let's handle it anyway)
  3448. cell.seq_id.erase(seq_id);
  3449. seq.tail = -1;
  3450. if (cell.seq_id.empty()) {
  3451. cell.pos = -1;
  3452. cell.src = -1;
  3453. cache.used -= 1;
  3454. }
  3455. }
  3456. }
  3457. }
  3458. }
  3459. #ifndef NDEBUG
  3460. {
  3461. std::vector<int32_t> tails_verif;
  3462. tails_verif.assign(cache.size, -1);
  3463. for (uint32_t i = 0; i < cache.size; ++i) {
  3464. llama_kv_cell & cell = cache.cells[i];
  3465. for (llama_seq_id seq_id : cell.seq_id) {
  3466. if (tails_verif[seq_id] != -1) {
  3467. LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tails_verif[seq_id]);
  3468. }
  3469. tails_verif[seq_id] = i;
  3470. }
  3471. }
  3472. for (uint32_t i = 0; i < cache.size; ++i) {
  3473. if (tails_verif[i] != cache.cells[i].tail) {
  3474. LLAMA_LOG_ERROR("%s: wrong tail for seq_id %d, (%d instead of %d)\n", __func__, i, cache.cells[i].tail, tails_verif[i]);
  3475. }
  3476. }
  3477. }
  3478. #endif
  3479. // find next empty cell
  3480. uint32_t next_empty_cell = cache.head;
  3481. for (uint32_t i = 0; i < cache.size; ++i) {
  3482. if (next_empty_cell >= cache.size) { next_empty_cell -= cache.size; }
  3483. llama_kv_cell & cell = cache.cells[next_empty_cell];
  3484. if (cell.is_empty()) { break; }
  3485. next_empty_cell += 1;
  3486. }
  3487. // find usable cell range
  3488. for (uint32_t s = 0; s < n_seqs; ++s) {
  3489. const llama_seq_id seq_id = batch.seq_id[s][0];
  3490. llama_kv_cell & seq_meta = cache.cells[seq_id];
  3491. bool has_cell = false;
  3492. if (seq_meta.tail >= 0) {
  3493. llama_kv_cell & cell = cache.cells[seq_meta.tail];
  3494. GGML_ASSERT(cell.has_seq_id(seq_id));
  3495. // does this seq_id "own" the cell?
  3496. if (cell.seq_id.size() == 1) { has_cell = true; }
  3497. }
  3498. if (!has_cell) {
  3499. llama_kv_cell & empty_cell = cache.cells[next_empty_cell];
  3500. GGML_ASSERT(empty_cell.is_empty());
  3501. // copy old tail into the empty cell
  3502. if (seq_meta.tail >= 0) {
  3503. llama_kv_cell & orig_cell = cache.cells[seq_meta.tail];
  3504. empty_cell.pos = orig_cell.pos;
  3505. empty_cell.src = orig_cell.src;
  3506. orig_cell.seq_id.erase(seq_id);
  3507. empty_cell.seq_id.insert(seq_id); // will be overwritten
  3508. }
  3509. seq_meta.tail = next_empty_cell;
  3510. // find next empty cell
  3511. if (s + 1 < n_seqs) {
  3512. next_empty_cell += 1;
  3513. for (uint32_t i = 0; i < cache.size; ++i) {
  3514. if (next_empty_cell >= cache.size) { next_empty_cell -= cache.size; }
  3515. llama_kv_cell & cell = cache.cells[next_empty_cell];
  3516. if (cell.is_empty()) { break; }
  3517. next_empty_cell += 1;
  3518. }
  3519. }
  3520. }
  3521. if (min > seq_meta.tail) { min = seq_meta.tail; }
  3522. if (max < seq_meta.tail) { max = seq_meta.tail; }
  3523. }
  3524. // gather and re-order
  3525. for (uint32_t s = 0; s < n_seqs; ++s) {
  3526. int32_t dst_id = s + min;
  3527. int32_t src_id = cache.cells[batch.seq_id[s][0]].tail;
  3528. if (dst_id != src_id) {
  3529. llama_kv_cell & dst_cell = cache.cells[dst_id];
  3530. llama_kv_cell & src_cell = cache.cells[src_id];
  3531. std::swap(dst_cell.pos, src_cell.pos);
  3532. std::swap(dst_cell.src, src_cell.src);
  3533. std::swap(dst_cell.seq_id, src_cell.seq_id);
  3534. // swap tails (assuming they NEVER overlap)
  3535. for (const llama_seq_id seq_id : src_cell.seq_id) {
  3536. cache.cells[seq_id].tail = src_id;
  3537. }
  3538. for (const llama_seq_id seq_id : dst_cell.seq_id) {
  3539. cache.cells[seq_id].tail = dst_id;
  3540. }
  3541. }
  3542. }
  3543. // update the pos of the used seqs
  3544. for (uint32_t s = 0; s < n_seqs; ++s) {
  3545. const llama_pos last_pos = batch.pos[n_seq_tokens * s + n_seq_tokens - 1];
  3546. int32_t cell_id = s + min;
  3547. llama_kv_cell & cell = cache.cells[cell_id];
  3548. if (cell.pos >= 0 && last_pos != cell.pos + (llama_pos) n_seq_tokens) {
  3549. // What should happen when the pos backtracks or skips a value?
  3550. // Clearing the state mid-batch would require special-casing which isn't done.
  3551. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d with %u new tokens\n",
  3552. __func__, last_pos, cell.pos, batch.seq_id[s][0], n_seq_tokens);
  3553. }
  3554. cell.pos = last_pos;
  3555. cell.seq_id.clear();
  3556. for (int32_t j = 0; j < batch.n_seq_id[s]; ++j) {
  3557. const llama_seq_id seq_id = batch.seq_id[s][j];
  3558. cell.seq_id.insert(seq_id);
  3559. cache.cells[seq_id].tail = cell_id;
  3560. }
  3561. }
  3562. // allow getting the range of used cells, from head to head + n
  3563. cache.head = min;
  3564. cache.n = max - min + 1;
  3565. cache.used = std::count_if(cache.cells.begin(), cache.cells.end(),
  3566. [](const llama_kv_cell& cell){ return !cell.is_empty(); });
  3567. // sanity check
  3568. return llama_kv_cache_slot_info(cache.n >= n_seqs);
  3569. }
  3570. // otherwise, one cell per token.
  3571. if (n_tokens > cache.size) {
  3572. LLAMA_LOG_ERROR("%s: n_tokens=%d > cache.size=%d\n", __func__, n_tokens, cache.size);
  3573. return llama_kv_cache_slot_info_failed;
  3574. }
  3575. uint32_t n_tested = 0;
  3576. while (true) {
  3577. if (cache.head + n_tokens > cache.size) {
  3578. n_tested += cache.size - cache.head;
  3579. cache.head = 0;
  3580. continue;
  3581. }
  3582. bool found = true;
  3583. for (uint32_t i = 0; i < n_tokens; i++) {
  3584. if (cache.cells[cache.head + i].pos >= 0) {
  3585. found = false;
  3586. cache.head += i + 1;
  3587. n_tested += i + 1;
  3588. break;
  3589. }
  3590. }
  3591. if (found) {
  3592. break;
  3593. }
  3594. if (n_tested >= cache.size) {
  3595. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  3596. return llama_kv_cache_slot_info_failed;
  3597. }
  3598. }
  3599. for (uint32_t s = 0; s < n_seqs; s++) {
  3600. for (uint32_t i = 0; i < n_seq_tokens; ++i) {
  3601. uint32_t k = s*n_seq_tokens + i;
  3602. cache.cells[cache.head + k].pos = batch.pos[k];
  3603. for (int32_t j = 0; j < batch.n_seq_id[s]; j++) {
  3604. cache.cells[cache.head + k].seq_id.insert(batch.seq_id[s][j]);
  3605. }
  3606. }
  3607. }
  3608. cache.used += n_tokens;
  3609. return llama_kv_cache_slot_info(cache.head, cache.head + n_tokens);
  3610. }
  3611. // find how many cells are currently in use
  3612. static uint32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  3613. for (uint32_t i = cache.size; i > 0; --i) {
  3614. const llama_kv_cell & cell = cache.cells[i - 1];
  3615. if (cell.pos >= 0 && !cell.is_empty()) {
  3616. return i;
  3617. }
  3618. }
  3619. return 0;
  3620. }
  3621. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  3622. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  3623. cache.cells[i].pos = -1;
  3624. cache.cells[i].seq_id.clear();
  3625. cache.cells[i].src = -1;
  3626. cache.cells[i].tail = -1;
  3627. }
  3628. cache.head = 0;
  3629. cache.used = 0;
  3630. for (auto & buf : cache.bufs) {
  3631. ggml_backend_buffer_clear(buf.get(), 0);
  3632. }
  3633. }
  3634. static bool llama_kv_cache_seq_rm(
  3635. struct llama_kv_cache & cache,
  3636. llama_seq_id seq_id,
  3637. llama_pos p0,
  3638. llama_pos p1) {
  3639. uint32_t new_head = cache.size;
  3640. if (p0 < 0) p0 = 0;
  3641. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3642. // models like Mamba or RWKV can't have a state partially erased
  3643. if (cache.recurrent) {
  3644. if (seq_id >= (int64_t) cache.size) {
  3645. // could be fatal
  3646. return false;
  3647. }
  3648. if (0 <= seq_id) {
  3649. int32_t & tail_id = cache.cells[seq_id].tail;
  3650. if (tail_id >= 0) {
  3651. const llama_kv_cell & cell = cache.cells[tail_id];
  3652. // partial intersection is invalid
  3653. if ((0 < p0 && p0 <= cell.pos) || (0 < p1 && p1 <= cell.pos)) {
  3654. return false;
  3655. }
  3656. // invalidate tails which will be cleared
  3657. if (p0 <= cell.pos && cell.pos < p1) {
  3658. tail_id = -1;
  3659. }
  3660. }
  3661. } else {
  3662. // seq_id is negative, then the range should include everything or nothing
  3663. if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
  3664. return false;
  3665. }
  3666. }
  3667. }
  3668. for (uint32_t i = 0; i < cache.size; ++i) {
  3669. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3670. if (seq_id < 0) {
  3671. cache.cells[i].seq_id.clear();
  3672. } else if (cache.cells[i].has_seq_id(seq_id)) {
  3673. cache.cells[i].seq_id.erase(seq_id);
  3674. } else {
  3675. continue;
  3676. }
  3677. if (cache.cells[i].is_empty()) {
  3678. // keep count of the number of used cells
  3679. if (cache.cells[i].pos >= 0) cache.used--;
  3680. cache.cells[i].pos = -1;
  3681. cache.cells[i].src = -1;
  3682. if (new_head == cache.size) new_head = i;
  3683. }
  3684. }
  3685. }
  3686. // If we freed up a slot, set head to it so searching can start there.
  3687. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  3688. return true;
  3689. }
  3690. static void llama_kv_cache_seq_cp(
  3691. struct llama_kv_cache & cache,
  3692. llama_seq_id seq_id_src,
  3693. llama_seq_id seq_id_dst,
  3694. llama_pos p0,
  3695. llama_pos p1) {
  3696. if (p0 < 0) p0 = 0;
  3697. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3698. if (cache.recurrent) {
  3699. if ((uint32_t) seq_id_dst < cache.size && (uint32_t) seq_id_src < cache.size) {
  3700. llama_kv_cell & tail_src = cache.cells[seq_id_src];
  3701. llama_kv_cell & tail_dst = cache.cells[seq_id_dst];
  3702. if (tail_dst.tail >= 0) {
  3703. // clear destination seq_id if it wasn't empty
  3704. llama_kv_cell & cell_dst = cache.cells[tail_dst.tail];
  3705. cell_dst.seq_id.erase(seq_id_dst);
  3706. tail_dst.tail = -1;
  3707. if (cell_dst.seq_id.empty()) {
  3708. cell_dst.pos = -1;
  3709. cell_dst.delta = -1;
  3710. cell_dst.src = -1;
  3711. cache.used -= 1;
  3712. }
  3713. }
  3714. if (tail_src.tail >= 0) {
  3715. llama_kv_cell & cell_src = cache.cells[tail_src.tail];
  3716. cell_src.seq_id.insert(seq_id_dst);
  3717. tail_dst.tail = tail_src.tail;
  3718. }
  3719. }
  3720. return;
  3721. }
  3722. // otherwise, this is the KV cache of a Transformer-like model
  3723. cache.head = 0;
  3724. for (uint32_t i = 0; i < cache.size; ++i) {
  3725. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3726. cache.cells[i].seq_id.insert(seq_id_dst);
  3727. }
  3728. }
  3729. }
  3730. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  3731. uint32_t new_head = cache.size;
  3732. for (uint32_t i = 0; i < cache.size; ++i) {
  3733. if (cache.recurrent && (llama_seq_id) i != seq_id) {
  3734. cache.cells[i].tail = -1;
  3735. }
  3736. if (!cache.cells[i].has_seq_id(seq_id)) {
  3737. if (cache.cells[i].pos >= 0) cache.used--;
  3738. cache.cells[i].pos = -1;
  3739. cache.cells[i].src = -1;
  3740. cache.cells[i].seq_id.clear();
  3741. if (new_head == cache.size) new_head = i;
  3742. } else {
  3743. cache.cells[i].seq_id.clear();
  3744. cache.cells[i].seq_id.insert(seq_id);
  3745. }
  3746. }
  3747. // If we freed up a slot, set head to it so searching can start there.
  3748. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  3749. }
  3750. static void llama_kv_cache_seq_add(
  3751. struct llama_kv_cache & cache,
  3752. llama_seq_id seq_id,
  3753. llama_pos p0,
  3754. llama_pos p1,
  3755. llama_pos delta) {
  3756. uint32_t new_head = cache.size;
  3757. if (p0 < 0) p0 = 0;
  3758. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3759. // If there is no range then return early to avoid looping over the cache.
  3760. if (p0 == p1) return;
  3761. if (cache.recurrent) {
  3762. // for Mamba-like or RWKV models, only the pos needs to be shifted
  3763. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  3764. const int32_t tail_id = cache.cells[seq_id].tail;
  3765. if (tail_id >= 0) {
  3766. llama_kv_cell & cell = cache.cells[tail_id];
  3767. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  3768. cell.pos += delta;
  3769. }
  3770. }
  3771. }
  3772. return;
  3773. }
  3774. for (uint32_t i = 0; i < cache.size; ++i) {
  3775. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3776. cache.has_shift = true;
  3777. cache.cells[i].pos += delta;
  3778. cache.cells[i].delta += delta;
  3779. if (cache.cells[i].pos < 0) {
  3780. if (!cache.cells[i].is_empty()) {
  3781. cache.used--;
  3782. }
  3783. cache.cells[i].pos = -1;
  3784. cache.cells[i].seq_id.clear();
  3785. if (new_head == cache.size) {
  3786. new_head = i;
  3787. }
  3788. }
  3789. }
  3790. }
  3791. // If we freed up a slot, set head to it so searching can start there.
  3792. // Otherwise we just start the next search from the beginning.
  3793. cache.head = new_head != cache.size ? new_head : 0;
  3794. }
  3795. static void llama_kv_cache_seq_div(
  3796. struct llama_kv_cache & cache,
  3797. llama_seq_id seq_id,
  3798. llama_pos p0,
  3799. llama_pos p1,
  3800. int d) {
  3801. if (p0 < 0) p0 = 0;
  3802. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3803. // If there is no range then return early to avoid looping over the cache.
  3804. if (p0 == p1) return;
  3805. if (cache.recurrent) {
  3806. // for Mamba-like or RWKV models, only the pos needs to be changed
  3807. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  3808. const int32_t tail_id = cache.cells[seq_id].tail;
  3809. if (tail_id >= 0) {
  3810. llama_kv_cell & cell = cache.cells[tail_id];
  3811. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  3812. cell.pos /= d;
  3813. }
  3814. }
  3815. }
  3816. return;
  3817. }
  3818. for (uint32_t i = 0; i < cache.size; ++i) {
  3819. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3820. cache.has_shift = true;
  3821. {
  3822. llama_pos p_old = cache.cells[i].pos;
  3823. cache.cells[i].pos /= d;
  3824. cache.cells[i].delta += cache.cells[i].pos - p_old;
  3825. }
  3826. }
  3827. }
  3828. }
  3829. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  3830. llama_pos result = 0;
  3831. for (uint32_t i = 0; i < cache.size; ++i) {
  3832. if (cache.cells[i].has_seq_id(seq_id)) {
  3833. result = std::max(result, cache.cells[i].pos);
  3834. }
  3835. }
  3836. return result;
  3837. }
  3838. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  3839. if (!cache.recurrent) {
  3840. cache.do_defrag = true;
  3841. }
  3842. }
  3843. static uint32_t llama_kv_cache_get_padding(const struct llama_cparams & cparams) {
  3844. // the FA kernels require padding to avoid extra runtime boundary checks
  3845. return cparams.flash_attn ? 256u : 32u;
  3846. }
  3847. // saves the kv_cache state for future recovery.
  3848. // used to rollback llama_kv_cache_find_slot changes.
  3849. struct llama_kv_slot_restorer {
  3850. struct llama_kv_cache_state {
  3851. uint32_t head = 0;
  3852. uint32_t n = 0;
  3853. } old_state;
  3854. // for non-recurrent models only
  3855. // list of slots to restore
  3856. std::vector<std::pair<uint32_t, uint32_t>> slot_boundaries;
  3857. bool do_restore = false;
  3858. explicit llama_kv_slot_restorer(const struct llama_kv_cache & cache) {
  3859. old_state.head = cache.head;
  3860. old_state.n = cache.n;
  3861. }
  3862. // saves a slot information for future restoration
  3863. void save(const struct llama_kv_cache_slot_info & slot) {
  3864. if (slot) {
  3865. do_restore = true;
  3866. if (slot.boundaries.first != slot.boundaries.second) {
  3867. slot_boundaries.push_back(slot.boundaries);
  3868. }
  3869. }
  3870. }
  3871. // must be explicitly called to restore the kv_cache state
  3872. // and rollback changes from all llama_kv_cache_find_slot calls
  3873. void restore(struct llama_kv_cache & cache) {
  3874. if (do_restore) {
  3875. cache.head = old_state.head;
  3876. cache.n = old_state.n;
  3877. if (cache.recurrent) { // recurrent models like Mamba or RWKV can't have a state partially erased
  3878. llama_kv_cache_seq_rm(cache, -1, -1, -1);
  3879. } else {
  3880. for (auto & slot : slot_boundaries) {
  3881. llama_kv_cache_seq_rm(cache, -1, slot.first, slot.second);
  3882. }
  3883. }
  3884. }
  3885. }
  3886. };
  3887. //
  3888. // model loading and saving
  3889. //
  3890. enum llama_fver {
  3891. GGUF_FILE_VERSION_V1 = 1,
  3892. GGUF_FILE_VERSION_V2 = 2,
  3893. GGUF_FILE_VERSION_V3 = 3,
  3894. };
  3895. static const char * llama_file_version_name(llama_fver version) {
  3896. switch (version) {
  3897. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  3898. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  3899. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  3900. }
  3901. return "unknown";
  3902. }
  3903. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  3904. char buf[256];
  3905. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  3906. for (size_t i = 1; i < ne.size(); i++) {
  3907. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  3908. }
  3909. return buf;
  3910. }
  3911. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  3912. char buf[256];
  3913. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  3914. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  3915. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  3916. }
  3917. return buf;
  3918. }
  3919. namespace GGUFMeta {
  3920. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  3921. struct GKV_Base_Type {
  3922. static constexpr gguf_type gt = gt_;
  3923. static T getter(const gguf_context * ctx, const int kid) {
  3924. return gfun(ctx, kid);
  3925. }
  3926. };
  3927. template<typename T> struct GKV_Base;
  3928. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  3929. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  3930. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  3931. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  3932. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  3933. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  3934. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  3935. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  3936. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  3937. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  3938. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  3939. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  3940. template<> struct GKV_Base<std::string> {
  3941. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  3942. static std::string getter(const gguf_context * ctx, const int kid) {
  3943. return gguf_get_val_str(ctx, kid);
  3944. }
  3945. };
  3946. struct ArrayInfo {
  3947. const gguf_type gt;
  3948. const size_t length;
  3949. const void * data;
  3950. };
  3951. template<> struct GKV_Base<ArrayInfo> {
  3952. public:
  3953. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  3954. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  3955. return ArrayInfo {
  3956. gguf_get_arr_type(ctx, k),
  3957. size_t(gguf_get_arr_n(ctx, k)),
  3958. gguf_get_arr_data(ctx, k),
  3959. };
  3960. }
  3961. };
  3962. template<typename T>
  3963. class GKV : public GKV_Base<T> {
  3964. GKV() = delete;
  3965. public:
  3966. static T get_kv(const gguf_context * ctx, const int k) {
  3967. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  3968. if (kt != GKV::gt) {
  3969. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  3970. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  3971. }
  3972. return GKV::getter(ctx, k);
  3973. }
  3974. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  3975. switch (ty) {
  3976. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  3977. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  3978. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  3979. case LLAMA_KV_OVERRIDE_TYPE_STR: return "str";
  3980. }
  3981. return "unknown";
  3982. }
  3983. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  3984. if (!ovrd) { return false; }
  3985. if (ovrd->tag == expected_type) {
  3986. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  3987. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  3988. switch (ovrd->tag) {
  3989. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  3990. LLAMA_LOG_INFO("%s\n", ovrd->val_bool ? "true" : "false");
  3991. } break;
  3992. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  3993. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->val_i64);
  3994. } break;
  3995. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  3996. LLAMA_LOG_INFO("%.6f\n", ovrd->val_f64);
  3997. } break;
  3998. case LLAMA_KV_OVERRIDE_TYPE_STR: {
  3999. LLAMA_LOG_INFO("%s\n", ovrd->val_str);
  4000. } break;
  4001. default:
  4002. // Shouldn't be possible to end up here, but just in case...
  4003. throw std::runtime_error(
  4004. format("Unsupported attempt to override %s type for metadata key %s\n",
  4005. override_type_to_str(ovrd->tag), ovrd->key));
  4006. }
  4007. return true;
  4008. }
  4009. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  4010. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  4011. return false;
  4012. }
  4013. template<typename OT>
  4014. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  4015. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  4016. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  4017. target = ovrd->val_bool;
  4018. return true;
  4019. }
  4020. return false;
  4021. }
  4022. template<typename OT>
  4023. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  4024. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  4025. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  4026. target = ovrd->val_i64;
  4027. return true;
  4028. }
  4029. return false;
  4030. }
  4031. template<typename OT>
  4032. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  4033. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  4034. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  4035. target = ovrd->val_f64;
  4036. return true;
  4037. }
  4038. return false;
  4039. }
  4040. template<typename OT>
  4041. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  4042. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  4043. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_STR, ovrd)) {
  4044. target = ovrd->val_str;
  4045. return true;
  4046. }
  4047. return false;
  4048. }
  4049. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  4050. if (try_override<T>(target, ovrd)) {
  4051. return true;
  4052. }
  4053. if (k < 0) { return false; }
  4054. target = get_kv(ctx, k);
  4055. return true;
  4056. }
  4057. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  4058. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  4059. }
  4060. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  4061. return set(ctx, key.c_str(), target, ovrd);
  4062. }
  4063. };
  4064. }
  4065. using llama_buf_map = std::unordered_map<uint32_t, ggml_backend_buffer_t>;
  4066. static size_t llama_model_max_nodes(const llama_model & model) {
  4067. return std::max<size_t>(8192, model.tensors_by_name.size()*5);
  4068. }
  4069. struct llama_model_loader {
  4070. int n_kv = 0;
  4071. int n_tensors = 0;
  4072. int n_created = 0;
  4073. uint64_t n_elements = 0;
  4074. size_t n_bytes = 0;
  4075. bool use_mmap = false;
  4076. bool check_tensors;
  4077. llama_files files;
  4078. llama_ftype ftype;
  4079. llama_fver fver;
  4080. llama_mmaps mappings;
  4081. // Holds information on a model weight
  4082. struct llama_tensor_weight {
  4083. uint16_t idx; // source file index
  4084. size_t offs; // tensor data offset in the original file
  4085. ggml_tensor * tensor;
  4086. llama_tensor_weight(const llama_file * file, uint16_t idx, const struct gguf_context * gguf_ctx, ggml_tensor * tensor) : idx(idx), tensor(tensor) {
  4087. const int tensor_idx = gguf_find_tensor(gguf_ctx, ggml_get_name(tensor));
  4088. if (tensor_idx < 0) {
  4089. throw std::runtime_error(format("tensor '%s' not found in the model", ggml_get_name(tensor)));
  4090. }
  4091. offs = gguf_get_data_offset(gguf_ctx) + gguf_get_tensor_offset(gguf_ctx, tensor_idx);
  4092. if (offs + ggml_nbytes(tensor) < offs || offs + ggml_nbytes(tensor) > file->size) {
  4093. throw std::runtime_error(format("tensor '%s' data is not within the file bounds, model is corrupted or incomplete", ggml_get_name(tensor)));
  4094. }
  4095. }
  4096. };
  4097. // custom comparator to sort weights more nicely by layer
  4098. struct weight_name_comparer {
  4099. bool operator()(const std::string & a, const std::string & b) const {
  4100. int a_layer = -1;
  4101. int b_layer = -1;
  4102. sscanf(a.c_str(), "blk.%d.", &a_layer);
  4103. sscanf(b.c_str(), "blk.%d.", &b_layer);
  4104. if (a_layer != b_layer) {
  4105. return a_layer < b_layer;
  4106. }
  4107. return a < b;
  4108. }
  4109. };
  4110. std::map<std::string, struct llama_tensor_weight, weight_name_comparer> weights_map;
  4111. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  4112. gguf_context_ptr meta;
  4113. std::vector<ggml_context_ptr> contexts;
  4114. std::string arch_name;
  4115. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  4116. llama_model_loader(const std::string & fname, bool use_mmap, bool check_tensors, const struct llama_model_kv_override * param_overrides_p) {
  4117. int trace = 0;
  4118. if (getenv("LLAMA_TRACE")) {
  4119. trace = atoi(getenv("LLAMA_TRACE"));
  4120. }
  4121. if (param_overrides_p != nullptr) {
  4122. for (const struct llama_model_kv_override * p = param_overrides_p; p->key[0] != 0; p++) {
  4123. kv_overrides.insert({std::string(p->key), *p});
  4124. }
  4125. }
  4126. struct ggml_context * ctx = NULL;
  4127. struct gguf_init_params params = {
  4128. /*.no_alloc = */ true,
  4129. /*.ctx = */ &ctx,
  4130. };
  4131. meta.reset(gguf_init_from_file(fname.c_str(), params));
  4132. if (!meta) {
  4133. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  4134. }
  4135. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  4136. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  4137. files.emplace_back(new llama_file(fname.c_str(), "rb"));
  4138. contexts.emplace_back(ctx);
  4139. // Save tensors data offset of the main file.
  4140. // For subsidiary files, `meta` tensor data offset must not be used,
  4141. // so we build a unified tensors index for weights.
  4142. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  4143. std::string tensor_name = std::string(cur->name);
  4144. // make sure there is no duplicated tensor names
  4145. if (weights_map.find(tensor_name) != weights_map.end()) {
  4146. throw std::runtime_error(format("invalid model: tensor '%s' is duplicated", ggml_get_name(cur)));
  4147. }
  4148. n_elements += ggml_nelements(cur);
  4149. n_bytes += ggml_nbytes(cur);
  4150. weights_map.emplace(tensor_name, llama_tensor_weight(files.back().get(), 0, meta.get(), cur));
  4151. }
  4152. uint16_t n_split = 0;
  4153. get_key(llm_kv(LLM_KV_SPLIT_COUNT), n_split, false);
  4154. // Load additional GGML contexts
  4155. if (n_split > 1) {
  4156. uint16_t idx = 0;
  4157. get_key(llm_kv(LLM_KV_SPLIT_NO), idx);
  4158. if (idx != 0) {
  4159. throw std::runtime_error(format("illegal split file: %d, model must be loaded with the first split", idx));
  4160. }
  4161. char split_prefix[PATH_MAX] = {0};
  4162. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), fname.c_str(), idx, n_split)) {
  4163. throw std::runtime_error(format("invalid split file: %s", fname.c_str()));
  4164. }
  4165. if (trace > 0) {
  4166. LLAMA_LOG_INFO("%s: loading additional %d GGUFs\n", __func__, n_split);
  4167. }
  4168. char split_path[PATH_MAX] = {0};
  4169. for (idx = 1; idx < n_split; idx++) {
  4170. llama_split_path(split_path, sizeof(split_path), split_prefix, idx, n_split);
  4171. struct gguf_init_params split_params = {
  4172. /*.no_alloc = */ true,
  4173. /*.ctx = */ &ctx,
  4174. };
  4175. gguf_context_ptr ctx_gguf { gguf_init_from_file(split_path, split_params) };
  4176. if (!ctx_gguf) {
  4177. throw std::runtime_error(format("%s: failed to load GGUF split from %s\n", __func__, split_path));
  4178. }
  4179. files.emplace_back(new llama_file(split_path, "rb"));
  4180. contexts.emplace_back(ctx);
  4181. // Save tensors data offset info of the shard.
  4182. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  4183. std::string tensor_name = std::string(cur->name);
  4184. // make sure there is no duplicated tensor names
  4185. if (weights_map.find(tensor_name) != weights_map.end()) {
  4186. throw std::runtime_error(format("invalid model: tensor '%s' is duplicated", ggml_get_name(cur)));
  4187. }
  4188. n_elements += ggml_nelements(cur);
  4189. n_bytes += ggml_nbytes(cur);
  4190. weights_map.emplace(tensor_name, llama_tensor_weight(files.back().get(), idx, ctx_gguf.get(), cur));
  4191. }
  4192. }
  4193. get_key(llm_kv(LLM_KV_SPLIT_TENSORS_COUNT), n_tensors);
  4194. // sanity check
  4195. {
  4196. const int n_tensors_loaded = (int) weights_map.size();
  4197. if (n_tensors != n_tensors_loaded) {
  4198. throw std::runtime_error(format("corrupted model: %d tensors expected but %d found", n_tensors, n_tensors_loaded));
  4199. }
  4200. }
  4201. LLAMA_LOG_INFO("%s: additional %d GGUFs metadata loaded.\n", __func__, n_split - 1);
  4202. }
  4203. n_kv = gguf_get_n_kv(meta.get());
  4204. n_tensors = weights_map.size();
  4205. fver = (enum llama_fver) gguf_get_version(meta.get());
  4206. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  4207. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  4208. // determine file type based on the number of tensors for each quantization and print meta data
  4209. // TODO: make optional
  4210. {
  4211. std::map<enum ggml_type, uint32_t> n_type;
  4212. uint32_t n_type_max = 0;
  4213. enum ggml_type type_max = GGML_TYPE_F32;
  4214. for (const auto & it : weights_map) {
  4215. const llama_tensor_weight & w = it.second;
  4216. const ggml_tensor * tensor = w.tensor;
  4217. enum ggml_type type = tensor->type;
  4218. n_type[type]++;
  4219. if (n_type_max < n_type[type]) {
  4220. n_type_max = n_type[type];
  4221. type_max = type;
  4222. }
  4223. if (trace > 0) {
  4224. const uint16_t sid = w.idx;
  4225. LLAMA_LOG_INFO("%s: - tensor split %2d: %32s %-8s [ %s ]\n", __func__, sid, ggml_get_name(tensor), ggml_type_name(type), llama_format_tensor_shape(tensor).c_str());
  4226. }
  4227. }
  4228. switch (type_max) {
  4229. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  4230. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  4231. case GGML_TYPE_BF16: ftype = LLAMA_FTYPE_MOSTLY_BF16; break;
  4232. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  4233. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  4234. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  4235. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  4236. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  4237. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  4238. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  4239. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  4240. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  4241. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  4242. case GGML_TYPE_TQ1_0: ftype = LLAMA_FTYPE_MOSTLY_TQ1_0; break;
  4243. case GGML_TYPE_TQ2_0: ftype = LLAMA_FTYPE_MOSTLY_TQ2_0; break;
  4244. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  4245. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  4246. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  4247. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  4248. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  4249. case GGML_TYPE_IQ1_M: ftype = LLAMA_FTYPE_MOSTLY_IQ1_M; break;
  4250. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  4251. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  4252. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  4253. case GGML_TYPE_Q4_0_4_4: ftype = LLAMA_FTYPE_MOSTLY_Q4_0_4_4; break;
  4254. case GGML_TYPE_Q4_0_4_8: ftype = LLAMA_FTYPE_MOSTLY_Q4_0_4_8; break;
  4255. case GGML_TYPE_Q4_0_8_8: ftype = LLAMA_FTYPE_MOSTLY_Q4_0_8_8; break;
  4256. default:
  4257. {
  4258. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  4259. ftype = LLAMA_FTYPE_ALL_F32;
  4260. } break;
  4261. }
  4262. // this is a way to mark that we have "guessed" the file type
  4263. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  4264. {
  4265. const int kid = gguf_find_key(meta.get(), "general.file_type"); // TODO: use LLM_KV
  4266. if (kid >= 0) {
  4267. ftype = (llama_ftype) gguf_get_val_u32(meta.get(), kid);
  4268. }
  4269. }
  4270. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  4271. for (int i = 0; i < n_kv; i++) {
  4272. const char * name = gguf_get_key(meta.get(), i);
  4273. const enum gguf_type type = gguf_get_kv_type(meta.get(), i);
  4274. const std::string type_name =
  4275. type == GGUF_TYPE_ARRAY
  4276. ? format("%s[%s,%d]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(meta.get(), i)), gguf_get_arr_n(meta.get(), i))
  4277. : gguf_type_name(type);
  4278. std::string value = gguf_kv_to_str(meta.get(), i);
  4279. const size_t MAX_VALUE_LEN = 40;
  4280. if (value.size() > MAX_VALUE_LEN) {
  4281. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  4282. }
  4283. replace_all(value, "\n", "\\n");
  4284. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  4285. }
  4286. // print type counts
  4287. for (auto & kv : n_type) {
  4288. if (kv.second == 0) {
  4289. continue;
  4290. }
  4291. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  4292. }
  4293. }
  4294. if (!llama_mmap::SUPPORTED) {
  4295. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  4296. use_mmap = false;
  4297. }
  4298. this->use_mmap = use_mmap;
  4299. this->check_tensors = check_tensors;
  4300. }
  4301. template<typename T>
  4302. typename std::enable_if<std::is_integral<T>::value, bool>::type
  4303. get_arr_n(const std::string & key, T & result, const bool required = true) {
  4304. const int kid = gguf_find_key(meta.get(), key.c_str());
  4305. if (kid < 0) {
  4306. if (required) {
  4307. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  4308. }
  4309. return false;
  4310. }
  4311. struct GGUFMeta::ArrayInfo arr_info =
  4312. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta.get(), kid);
  4313. result = arr_info.length;
  4314. return true;
  4315. }
  4316. template<typename T>
  4317. typename std::enable_if<std::is_integral<T>::value, bool>::type
  4318. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  4319. return get_arr_n(llm_kv(kid), result, required);
  4320. }
  4321. template<typename T>
  4322. bool get_arr(const std::string & key, std::vector<T> & result, const bool required = true) {
  4323. const int kid = gguf_find_key(meta.get(), key.c_str());
  4324. if (kid < 0 || gguf_get_kv_type(meta.get(), kid) != GGUF_TYPE_ARRAY) {
  4325. if (required) {
  4326. throw std::runtime_error(format("array key not found in model: %s", key.c_str()));
  4327. }
  4328. return false;
  4329. }
  4330. struct GGUFMeta::ArrayInfo arr_info =
  4331. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta.get(), kid);
  4332. switch (arr_info.gt) {
  4333. case GGUF_TYPE_FLOAT32: GGML_ASSERT((std::is_same<T, float>::value)); break;
  4334. case GGUF_TYPE_INT32: GGML_ASSERT(
  4335. (std::is_same<T, int32_t>::value) ||
  4336. (std::is_same<T, uint32_t>::value)); break;
  4337. default:
  4338. throw std::runtime_error(format("%s is not a float32, int32 array", key.c_str()));
  4339. }
  4340. result.resize(arr_info.length);
  4341. result.assign((const T*)arr_info.data, (const T *)arr_info.data + arr_info.length);
  4342. return true;
  4343. }
  4344. template<typename T, size_t N_MAX>
  4345. bool get_arr(const std::string & key, std::array<T, N_MAX> & result, const bool required = true) {
  4346. const int kid = gguf_find_key(meta.get(), key.c_str());
  4347. if (kid < 0 || gguf_get_kv_type(meta.get(), kid) != GGUF_TYPE_ARRAY) {
  4348. if (required) {
  4349. throw std::runtime_error(format("array key not found in model: %s", key.c_str()));
  4350. }
  4351. return false;
  4352. }
  4353. struct GGUFMeta::ArrayInfo arr_info =
  4354. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta.get(), kid);
  4355. switch (arr_info.gt) {
  4356. case GGUF_TYPE_FLOAT32: GGML_ASSERT((std::is_same<T, float>::value)); break;
  4357. case GGUF_TYPE_INT32: GGML_ASSERT(
  4358. (std::is_same<T, int32_t>::value) ||
  4359. (std::is_same<T, uint32_t>::value)); break;
  4360. default:
  4361. throw std::runtime_error(format("%s is not a float32, int32 array", key.c_str()));
  4362. }
  4363. if (arr_info.length > N_MAX) {
  4364. throw std::runtime_error(format("array length %u for key %s exceeds max %u", (uint32_t) arr_info.length, key.c_str(), (uint32_t) N_MAX));
  4365. }
  4366. std::copy((const T*)arr_info.data, (const T *)arr_info.data + arr_info.length, result.begin());
  4367. return true;
  4368. }
  4369. template<typename T>
  4370. bool get_arr(const enum llm_kv kid, T & result, const bool required = true) {
  4371. return get_arr(llm_kv(kid), result, required);
  4372. }
  4373. template<typename T>
  4374. bool get_key(const std::string & key, T & result, const bool required = true) {
  4375. auto it = kv_overrides.find(key);
  4376. const struct llama_model_kv_override * override =
  4377. it != kv_overrides.end() ? &it->second : nullptr;
  4378. const bool found = GGUFMeta::GKV<T>::set(meta.get(), key, result, override);
  4379. if (required && !found) {
  4380. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  4381. }
  4382. return found;
  4383. }
  4384. template<typename T>
  4385. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  4386. return get_key(llm_kv(kid), result, required);
  4387. }
  4388. // get array of n <= N_MAX elements, or a single element repeated n times
  4389. template<typename T, size_t N_MAX>
  4390. bool get_key_or_arr(const std::string & key, std::array<T, N_MAX> & result, uint32_t n, const bool required = true) {
  4391. const int kid = gguf_find_key(meta.get(), key.c_str());
  4392. if (kid < 0) {
  4393. if (required) {
  4394. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  4395. }
  4396. return false;
  4397. }
  4398. if (n > N_MAX) {
  4399. throw std::runtime_error(format("n > N_MAX: %u > %u for key %s", (uint32_t) n, (uint32_t) N_MAX, key.c_str()));
  4400. }
  4401. if (gguf_get_kv_type(meta.get(), kid) == GGUF_TYPE_ARRAY) {
  4402. struct GGUFMeta::ArrayInfo arr_info =
  4403. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta.get(), kid);
  4404. if (n != arr_info.length) {
  4405. throw std::runtime_error(format("key %s has wrong array length; expected %u, got %u", key.c_str(), n, (uint32_t) arr_info.length));
  4406. }
  4407. return get_arr(key, result, required);
  4408. } else {
  4409. T value;
  4410. bool ok = get_key(key, value, required);
  4411. if (!ok) {
  4412. return false;
  4413. }
  4414. for (uint32_t i = 0; i < n; i++) {
  4415. result[i] = value;
  4416. }
  4417. return true;
  4418. }
  4419. }
  4420. template<typename T>
  4421. bool get_key_or_arr(const enum llm_kv kid, T & result, uint32_t n, const bool required = true) {
  4422. return get_key_or_arr(llm_kv(kid), result, n, required);
  4423. }
  4424. std::string get_arch_name() const {
  4425. return arch_name;
  4426. }
  4427. enum llm_arch get_arch() const {
  4428. return llm_kv.arch;
  4429. }
  4430. const llama_tensor_weight * get_weight(const char * name) const {
  4431. auto pos = weights_map.find(name);
  4432. if (pos != weights_map.end()) {
  4433. return &pos->second;
  4434. }
  4435. return nullptr;
  4436. }
  4437. const llama_tensor_weight & require_weight(const char * name) const {
  4438. const llama_tensor_weight * weight = get_weight(name);
  4439. if (!weight) {
  4440. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  4441. }
  4442. return *weight;
  4443. }
  4444. struct ggml_tensor * get_tensor_meta(const char * name) const {
  4445. const auto * weight = get_weight(name);
  4446. if (!weight) {
  4447. return nullptr;
  4448. }
  4449. return weight->tensor;
  4450. }
  4451. struct ggml_tensor * require_tensor_meta(const std::string & name) const {
  4452. struct ggml_tensor * tensor = get_tensor_meta(name.c_str());
  4453. if (!tensor) {
  4454. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  4455. }
  4456. return tensor;
  4457. }
  4458. const struct ggml_tensor * check_tensor_dims(const std::string & name, const std::vector<int64_t> & ne, bool required) const {
  4459. const struct ggml_tensor * cur = get_tensor_meta(name.c_str());
  4460. if (cur == NULL) {
  4461. if (!required) {
  4462. return NULL;
  4463. }
  4464. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  4465. }
  4466. {
  4467. bool is_ok = true;
  4468. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  4469. if ((i < ne.size() && ne[i] != cur->ne[i]) || (i >= ne.size() && cur->ne[i] != 1)) {
  4470. is_ok = false;
  4471. break;
  4472. }
  4473. }
  4474. if (!is_ok) {
  4475. throw std::runtime_error(
  4476. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  4477. __func__, name.c_str(),
  4478. llama_format_tensor_shape(ne).c_str(),
  4479. llama_format_tensor_shape(cur).c_str()));
  4480. }
  4481. }
  4482. return cur;
  4483. }
  4484. static const int TENSOR_NOT_REQUIRED = 1;
  4485. static const int TENSOR_DUPLICATED = 2;
  4486. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::initializer_list<int64_t> & ne, int flags = 0) {
  4487. const struct ggml_tensor * cur = check_tensor_dims(name, ne, !(flags & TENSOR_NOT_REQUIRED));
  4488. if (cur == NULL) {
  4489. return NULL;
  4490. }
  4491. bool duplicated = flags & TENSOR_DUPLICATED;
  4492. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, cur);
  4493. ggml_set_name(tensor, ggml_get_name(cur));
  4494. if (duplicated) {
  4495. size_data += ggml_nbytes(cur);
  4496. } else {
  4497. n_created++;
  4498. }
  4499. return tensor;
  4500. }
  4501. struct ggml_tensor * create_tensor_as_view(struct ggml_context * ctx, struct ggml_tensor * base, const std::string & name, const std::initializer_list<int64_t> & ne, size_t offset, bool required = true) {
  4502. const struct ggml_tensor * cur = check_tensor_dims(name, ne, required);
  4503. if (cur == NULL) {
  4504. return NULL;
  4505. }
  4506. if (cur->type != base->type) {
  4507. throw std::runtime_error(format("%s: tensor '%s' has wrong type; expected %s, got %s", __func__, name.c_str(), ggml_type_name(base->type), ggml_type_name(cur->type)));
  4508. }
  4509. std::array<int64_t, GGML_MAX_DIMS> dims;
  4510. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  4511. dims[i] = i < ne.size() ? ne.begin()[i] : 1;
  4512. }
  4513. struct ggml_tensor * tensor = ggml_view_4d(ctx, base,
  4514. dims[0], dims[1], dims[2], dims[3],
  4515. cur->nb[1], cur->nb[2], cur->nb[3],
  4516. offset);
  4517. ggml_set_name(tensor, name.c_str());
  4518. n_created++;
  4519. return tensor;
  4520. }
  4521. void done_getting_tensors() const {
  4522. if (n_created != n_tensors) {
  4523. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  4524. }
  4525. }
  4526. void init_mappings(bool prefetch = true, llama_mlocks * mlock_mmaps = nullptr) {
  4527. if (use_mmap) {
  4528. mappings.reserve(files.size());
  4529. mmaps_used.reserve(files.size());
  4530. for (const auto & file : files) {
  4531. auto * reg = ggml_backend_dev_backend_reg(ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU));
  4532. auto * is_numa_fn = (decltype(ggml_is_numa) *) ggml_backend_reg_get_proc_address(reg, "ggml_backend_cpu_is_numa");
  4533. std::unique_ptr<llama_mmap> mapping(new llama_mmap(file.get(), prefetch ? -1 : 0, is_numa_fn()));
  4534. mmaps_used.emplace_back(mapping->size, 0);
  4535. if (mlock_mmaps) {
  4536. std::unique_ptr<llama_mlock> mlock_mmap(new llama_mlock());
  4537. mlock_mmap->init(mapping->addr);
  4538. mlock_mmaps->emplace_back(std::move(mlock_mmap));
  4539. }
  4540. mappings.emplace_back(std::move(mapping));
  4541. }
  4542. }
  4543. // compute the total size of all tensors for progress reporting
  4544. for (const auto & it : weights_map) {
  4545. size_data += ggml_nbytes(it.second.tensor);
  4546. }
  4547. }
  4548. void get_mapping_range(size_t * first, size_t * last, void ** addr, int idx, ggml_context * ctx) const {
  4549. GGML_ASSERT(!mappings.empty());
  4550. const auto & mapping = mappings.at(idx);
  4551. *first = mapping->size;
  4552. *last = 0;
  4553. *addr = mapping->addr;
  4554. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  4555. const auto * weight = get_weight(ggml_get_name(tensor));
  4556. if (!weight || weight->idx != idx) {
  4557. continue;
  4558. }
  4559. *first = std::min(*first, weight->offs);
  4560. *last = std::max(*last, weight->offs + ggml_nbytes(tensor));
  4561. }
  4562. }
  4563. // for backwards compatibility, does not support ggml-backend
  4564. void load_data_for(struct ggml_tensor * cur) const {
  4565. const auto & w = require_weight(ggml_get_name(cur));
  4566. if (use_mmap) {
  4567. const auto & mapping = mappings.at(w.idx);
  4568. if (cur->data == nullptr) {
  4569. cur->data = (uint8_t *)mapping->addr + w.offs;
  4570. } else {
  4571. memcpy(cur->data, (uint8_t *)mapping->addr + w.offs, ggml_nbytes(cur));
  4572. }
  4573. } else {
  4574. GGML_ASSERT(cur->data != nullptr);
  4575. GGML_ASSERT(w.idx < files.size());
  4576. const auto & file = files.at(w.idx);
  4577. file->seek(w.offs, SEEK_SET);
  4578. file->read_raw(cur->data, ggml_nbytes(cur));
  4579. }
  4580. if (check_tensors && !ggml_validate_row_data(cur->type, cur->data, ggml_nbytes(cur))) {
  4581. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  4582. }
  4583. }
  4584. size_t size_done = 0;
  4585. size_t size_data = 0;
  4586. std::vector<std::pair<size_t, size_t>> mmaps_used;
  4587. // Returns false if cancelled by progress_callback
  4588. bool load_all_data(
  4589. struct ggml_context * ctx,
  4590. llama_buf_map & bufs,
  4591. llama_mlocks * lmlocks,
  4592. llama_progress_callback progress_callback,
  4593. void * progress_callback_user_data) {
  4594. GGML_ASSERT(size_data != 0 && "call init_mappings() first");
  4595. std::vector<no_init<uint8_t>> read_buf;
  4596. std::vector<std::future<std::pair<ggml_tensor *, bool>>> validation_result;
  4597. // 4 staging buffers for async uploads, each sized 1MB seems to be a good default for single NVMe drives.
  4598. // NVMe raid configurations might require more / larger buffers.
  4599. constexpr size_t n_buffers = 4;
  4600. constexpr size_t buffer_size = 1 * 1024 * 1024; // 1MB
  4601. std::vector<ggml_backend_buffer_t> host_buffers;
  4602. std::vector<ggml_backend_event_t> events;
  4603. std::vector<void *> host_ptrs;
  4604. size_t buffer_idx = 0; // buffer to use for async loads
  4605. ggml_backend_t upload_backend = [&](const char * func) -> ggml_backend_t {
  4606. if (use_mmap || check_tensors) {
  4607. return nullptr;
  4608. }
  4609. // When not using mmaped io use async uploads from pinned memory to GPU memory.
  4610. // First determine if the backend supports the necessary features for async uploads.
  4611. auto * buf = bufs.count(0) ? bufs.at(0) : nullptr;
  4612. if (!buf) {
  4613. LLAMA_LOG_DEBUG("%s: no buffer found for async uploads\n", func);
  4614. return nullptr;
  4615. }
  4616. auto * buft = ggml_backend_buffer_get_type(buf);
  4617. auto * dev = ggml_backend_buft_get_device(buft);
  4618. if (!dev) {
  4619. LLAMA_LOG_DEBUG("%s: no device found for buffer type %s for async uploads\n", func,
  4620. ggml_backend_buft_name(buft));
  4621. return nullptr;
  4622. }
  4623. if (buft != ggml_backend_dev_buffer_type(dev)) {
  4624. LLAMA_LOG_DEBUG("%s: buffer type %s is not the default buffer type for device %s for async uploads\n", func,
  4625. ggml_backend_buft_name(buft), ggml_backend_dev_name(dev));
  4626. return nullptr;
  4627. }
  4628. ggml_backend_dev_props props;
  4629. ggml_backend_dev_get_props(dev, &props);
  4630. if (!props.caps.async || !props.caps.host_buffer || !props.caps.events) {
  4631. LLAMA_LOG_DEBUG("%s: device %s does not support async, host buffers or events\n", func,
  4632. ggml_backend_dev_name(dev));
  4633. return nullptr;
  4634. }
  4635. auto * host_buft = ggml_backend_dev_host_buffer_type(dev);
  4636. if (!host_buft) {
  4637. LLAMA_LOG_DEBUG("%s: no host buffer type found for device %s\n", func,
  4638. ggml_backend_dev_name(dev));
  4639. return nullptr;
  4640. }
  4641. // If the backend is supported, create pinned memory buffers and events for synchronisation.
  4642. for (size_t idx = 0; idx < n_buffers; ++idx) {
  4643. auto * buf = ggml_backend_buft_alloc_buffer(host_buft, buffer_size);
  4644. if (!buf) {
  4645. LLAMA_LOG_DEBUG("%s: failed to allocate host buffer for async uploads for device %s\n", func,
  4646. ggml_backend_dev_name(dev));
  4647. return nullptr;
  4648. }
  4649. host_buffers.emplace_back(buf);
  4650. host_ptrs.emplace_back(ggml_backend_buffer_get_base(buf));
  4651. auto * event = ggml_backend_event_new(dev);
  4652. if (!event) {
  4653. LLAMA_LOG_DEBUG("%s: failed to create event for async uploads for device %s\n", func,
  4654. ggml_backend_dev_name(dev));
  4655. return nullptr;
  4656. }
  4657. events.emplace_back(event);
  4658. }
  4659. ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr);
  4660. if (!backend) {
  4661. LLAMA_LOG_DEBUG("%s: failed to initialize backend for device %s for async uploads\n", func,
  4662. ggml_backend_dev_name(dev));
  4663. return nullptr;
  4664. }
  4665. return backend;
  4666. }(__func__);
  4667. if (upload_backend) {
  4668. LLAMA_LOG_DEBUG("%s: using async uploads for device %s, buffer type %s, backend %s\n", __func__,
  4669. ggml_backend_dev_name(ggml_backend_get_device(upload_backend)),
  4670. ggml_backend_buft_name(ggml_backend_buffer_get_type(bufs.at(0))),
  4671. ggml_backend_name(upload_backend));
  4672. }
  4673. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  4674. const auto * weight = get_weight(ggml_get_name(cur));
  4675. if (weight == nullptr) {
  4676. // this can happen with split experts models
  4677. continue;
  4678. }
  4679. if (progress_callback) {
  4680. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  4681. return false;
  4682. }
  4683. }
  4684. size_t n_size = ggml_nbytes(cur);
  4685. if (use_mmap) {
  4686. const auto & mapping = mappings.at(weight->idx);
  4687. ggml_backend_buffer_t buf_mmap = nullptr;
  4688. if (bufs.count(weight->idx)) {
  4689. buf_mmap = bufs.at(weight->idx);
  4690. }
  4691. uint8_t * data = (uint8_t *) mapping->addr + weight->offs;
  4692. if (check_tensors) {
  4693. validation_result.emplace_back(std::async(std::launch::async, [cur, data, n_size] {
  4694. return std::make_pair(cur, ggml_validate_row_data(cur->type, data, n_size));
  4695. }));
  4696. }
  4697. GGML_ASSERT(buf_mmap || cur->data); // either we have a buffer to allocate the tensor in, or it is already allocated
  4698. if (buf_mmap && cur->data == nullptr) {
  4699. ggml_backend_tensor_alloc(buf_mmap, cur, data);
  4700. if (lmlocks) {
  4701. const auto & lmlock = lmlocks->at(weight->idx);
  4702. lmlock->grow_to(weight->offs + n_size);
  4703. }
  4704. auto & mmap_used = mmaps_used[weight->idx];
  4705. mmap_used.first = std::min(mmap_used.first, weight->offs);
  4706. mmap_used.second = std::max(mmap_used.second, weight->offs + n_size);
  4707. } else {
  4708. ggml_backend_tensor_set(cur, data, 0, n_size);
  4709. }
  4710. } else {
  4711. const auto & file = files.at(weight->idx);
  4712. if (ggml_backend_buffer_is_host(cur->buffer)) {
  4713. file->seek(weight->offs, SEEK_SET);
  4714. file->read_raw(cur->data, n_size);
  4715. if (check_tensors) {
  4716. validation_result.emplace_back(std::async(std::launch::async, [cur, n_size] {
  4717. return std::make_pair(cur, ggml_validate_row_data(cur->type, cur->data, n_size));
  4718. }));
  4719. }
  4720. } else {
  4721. // If upload_backend is valid load the tensor in chunks to pinned memory and upload the buffers asynchronously to the GPU.
  4722. if (upload_backend) {
  4723. file->seek(weight->offs, SEEK_SET);
  4724. size_t bytes_read = 0;
  4725. while (bytes_read < n_size) {
  4726. size_t read_iteration = std::min<size_t>(buffer_size, n_size - bytes_read);
  4727. ggml_backend_event_synchronize(events[buffer_idx]);
  4728. file->read_raw(host_ptrs[buffer_idx], read_iteration);
  4729. ggml_backend_tensor_set_async(upload_backend, cur, host_ptrs[buffer_idx], bytes_read, read_iteration);
  4730. ggml_backend_event_record(events[buffer_idx], upload_backend);
  4731. bytes_read += read_iteration;
  4732. ++buffer_idx;
  4733. buffer_idx %= n_buffers;
  4734. }
  4735. } else {
  4736. read_buf.resize(n_size);
  4737. file->seek(weight->offs, SEEK_SET);
  4738. file->read_raw(read_buf.data(), n_size);
  4739. ggml_backend_tensor_set(cur, read_buf.data(), 0, n_size);
  4740. if (check_tensors && !ggml_validate_row_data(cur->type, read_buf.data(), n_size)) {
  4741. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  4742. }
  4743. }
  4744. }
  4745. }
  4746. size_done += n_size;
  4747. }
  4748. // free temporary resources used for async uploads
  4749. for (auto * event : events) {
  4750. ggml_backend_event_synchronize(event);
  4751. ggml_backend_event_free(event);
  4752. }
  4753. for (auto * buf : host_buffers) {
  4754. ggml_backend_buffer_free(buf);
  4755. }
  4756. ggml_backend_free(upload_backend);
  4757. // check validation results
  4758. bool validation_failed = false;
  4759. for (auto & future : validation_result) {
  4760. auto result = future.get();
  4761. if (!result.second) {
  4762. LLAMA_LOG_ERROR("%s: tensor '%s' has invalid data\n", __func__, ggml_get_name(result.first));
  4763. validation_failed = true;
  4764. }
  4765. }
  4766. if (validation_failed) {
  4767. throw std::runtime_error("found tensors with invalid data");
  4768. }
  4769. // check if this is the last call and do final cleanup
  4770. if (size_done >= size_data) {
  4771. // unmap offloaded tensors and metadata
  4772. if (use_mmap) {
  4773. for (uint32_t idx = 0; idx < mappings.size(); idx++) {
  4774. const auto & mmap_used = mmaps_used.at(idx);
  4775. auto & mapping = mappings.at(idx);
  4776. mapping->unmap_fragment(0, mmap_used.first);
  4777. if (mmap_used.second != 0) {
  4778. mapping->unmap_fragment(mmap_used.second, mapping->size);
  4779. }
  4780. }
  4781. }
  4782. if (progress_callback) {
  4783. // Even though the model is done loading, we still honor
  4784. // cancellation since we need to free allocations.
  4785. return progress_callback(1.0f, progress_callback_user_data);
  4786. }
  4787. }
  4788. return true;
  4789. }
  4790. };
  4791. // temporary allocate memory for the input batch if needed
  4792. static const llama_seq_id batch_default_seq_id = 0;
  4793. struct llama_batch_allocr {
  4794. std::array<llama_seq_id, 1> seq_id_0 = {batch_default_seq_id};
  4795. std::vector<llama_pos> pos;
  4796. std::vector<int32_t> n_seq_id;
  4797. std::vector<llama_seq_id *> seq_id;
  4798. std::vector<int8_t> logits;
  4799. struct llama_batch batch;
  4800. // optionally fulfill the batch returned by llama_batch_get_one
  4801. llama_batch_allocr(llama_context & ctx, struct llama_batch in_batch) {
  4802. batch = in_batch;
  4803. GGML_ASSERT(batch.n_tokens > 0);
  4804. if (!batch.pos) {
  4805. // determine the last position in KV cache
  4806. llama_pos last_pos = -1;
  4807. for (const auto & cell : ctx.kv_self.cells) {
  4808. if (cell.has_seq_id(batch_default_seq_id)) {
  4809. last_pos = std::max(last_pos, cell.pos);
  4810. }
  4811. }
  4812. last_pos++; // next position
  4813. pos.resize(batch.n_tokens);
  4814. for (int32_t i = 0; i < batch.n_tokens; i++) {
  4815. pos[i] = i+last_pos;
  4816. }
  4817. batch.pos = pos.data();
  4818. }
  4819. if (!batch.n_seq_id) {
  4820. n_seq_id.resize(batch.n_tokens);
  4821. for (int32_t i = 0; i < batch.n_tokens; i++) {
  4822. n_seq_id[i] = seq_id_0.size();
  4823. }
  4824. batch.n_seq_id = n_seq_id.data();
  4825. }
  4826. if (!batch.seq_id) {
  4827. seq_id.resize(batch.n_tokens + 1);
  4828. seq_id[batch.n_tokens] = NULL;
  4829. for (int32_t i = 0; i < batch.n_tokens; i++) {
  4830. seq_id[i] = seq_id_0.data();
  4831. }
  4832. batch.seq_id = seq_id.data();
  4833. }
  4834. if (!batch.logits) {
  4835. logits.resize(batch.n_tokens);
  4836. logits[logits.size() - 1] = true;
  4837. batch.logits = logits.data();
  4838. }
  4839. }
  4840. };
  4841. template<>
  4842. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  4843. uint32_t tmp;
  4844. const bool found = get_key(kid, tmp, required);
  4845. if (found) {
  4846. result = (enum llama_pooling_type) tmp;
  4847. } else {
  4848. result = LLAMA_POOLING_TYPE_UNSPECIFIED;
  4849. }
  4850. return found;
  4851. }
  4852. //
  4853. // load LLaMA models
  4854. //
  4855. static const char * llama_model_arch_name(llm_arch arch) {
  4856. auto it = LLM_ARCH_NAMES.find(arch);
  4857. if (it == LLM_ARCH_NAMES.end()) {
  4858. return "unknown";
  4859. }
  4860. return it->second;
  4861. }
  4862. static std::string llama_model_ftype_name(llama_ftype ftype) {
  4863. if (ftype & LLAMA_FTYPE_GUESSED) {
  4864. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  4865. }
  4866. switch (ftype) {
  4867. case LLAMA_FTYPE_ALL_F32: return "all F32";
  4868. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  4869. case LLAMA_FTYPE_MOSTLY_BF16: return "BF16";
  4870. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  4871. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  4872. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  4873. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  4874. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  4875. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  4876. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  4877. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  4878. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  4879. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  4880. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  4881. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  4882. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  4883. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  4884. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  4885. case LLAMA_FTYPE_MOSTLY_TQ1_0: return "TQ1_0 - 1.69 bpw ternary";
  4886. case LLAMA_FTYPE_MOSTLY_TQ2_0: return "TQ2_0 - 2.06 bpw ternary";
  4887. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: return "IQ2_XXS - 2.0625 bpw";
  4888. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  4889. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  4890. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  4891. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  4892. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: return "IQ3_XXS - 3.0625 bpw";
  4893. case LLAMA_FTYPE_MOSTLY_IQ1_S: return "IQ1_S - 1.5625 bpw";
  4894. case LLAMA_FTYPE_MOSTLY_IQ1_M: return "IQ1_M - 1.75 bpw";
  4895. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  4896. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  4897. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  4898. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  4899. case LLAMA_FTYPE_MOSTLY_Q4_0_4_4: return "Q4_0_4_4";
  4900. case LLAMA_FTYPE_MOSTLY_Q4_0_4_8: return "Q4_0_4_8";
  4901. case LLAMA_FTYPE_MOSTLY_Q4_0_8_8: return "Q4_0_8_8";
  4902. default: return "unknown, may not work";
  4903. }
  4904. }
  4905. static const char * llama_model_type_name(e_model type) {
  4906. switch (type) {
  4907. case MODEL_14M: return "14M";
  4908. case MODEL_17M: return "17M";
  4909. case MODEL_22M: return "22M";
  4910. case MODEL_33M: return "33M";
  4911. case MODEL_60M: return "60M";
  4912. case MODEL_70M: return "70M";
  4913. case MODEL_80M: return "80M";
  4914. case MODEL_109M: return "109M";
  4915. case MODEL_137M: return "137M";
  4916. case MODEL_160M: return "160M";
  4917. case MODEL_220M: return "220M";
  4918. case MODEL_250M: return "250M";
  4919. case MODEL_270M: return "270M";
  4920. case MODEL_335M: return "335M";
  4921. case MODEL_410M: return "410M";
  4922. case MODEL_450M: return "450M";
  4923. case MODEL_770M: return "770M";
  4924. case MODEL_780M: return "780M";
  4925. case MODEL_0_5B: return "0.5B";
  4926. case MODEL_1B: return "1B";
  4927. case MODEL_1_3B: return "1.3B";
  4928. case MODEL_1_4B: return "1.4B";
  4929. case MODEL_1_5B: return "1.5B";
  4930. case MODEL_1_6B: return "1.6B";
  4931. case MODEL_2B: return "2B";
  4932. case MODEL_2_8B: return "2.8B";
  4933. case MODEL_3B: return "3B";
  4934. case MODEL_4B: return "4B";
  4935. case MODEL_6B: return "6B";
  4936. case MODEL_6_9B: return "6.9B";
  4937. case MODEL_7B: return "7B";
  4938. case MODEL_8B: return "8B";
  4939. case MODEL_9B: return "9B";
  4940. case MODEL_11B: return "11B";
  4941. case MODEL_12B: return "12B";
  4942. case MODEL_13B: return "13B";
  4943. case MODEL_14B: return "14B";
  4944. case MODEL_15B: return "15B";
  4945. case MODEL_16B: return "16B";
  4946. case MODEL_20B: return "20B";
  4947. case MODEL_30B: return "30B";
  4948. case MODEL_32B: return "32B";
  4949. case MODEL_34B: return "34B";
  4950. case MODEL_35B: return "35B";
  4951. case MODEL_40B: return "40B";
  4952. case MODEL_65B: return "65B";
  4953. case MODEL_70B: return "70B";
  4954. case MODEL_236B: return "236B";
  4955. case MODEL_314B: return "314B";
  4956. case MODEL_SMALL: return "0.1B";
  4957. case MODEL_MEDIUM: return "0.4B";
  4958. case MODEL_LARGE: return "0.8B";
  4959. case MODEL_XL: return "1.5B";
  4960. case MODEL_A1_7B: return "A1.7B";
  4961. case MODEL_A2_7B: return "A2.7B";
  4962. case MODEL_8x7B: return "8x7B";
  4963. case MODEL_8x22B: return "8x22B";
  4964. case MODEL_16x12B: return "16x12B";
  4965. case MODEL_10B_128x3_66B: return "10B+128x3.66B";
  4966. case MODEL_57B_A14B: return "57B.A14B";
  4967. case MODEL_27B: return "27B";
  4968. default: return "?B";
  4969. }
  4970. }
  4971. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  4972. switch (type) {
  4973. case LLAMA_VOCAB_TYPE_NONE: return "no vocab";
  4974. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  4975. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  4976. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  4977. case LLAMA_VOCAB_TYPE_UGM: return "UGM";
  4978. case LLAMA_VOCAB_TYPE_RWKV: return "RWKV";
  4979. default: return "unknown";
  4980. }
  4981. }
  4982. static void llm_load_stats(llama_model_loader & ml, llama_model & model) {
  4983. model.n_elements = ml.n_elements;
  4984. model.n_bytes = ml.n_bytes;
  4985. }
  4986. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  4987. model.arch = ml.get_arch();
  4988. if (model.arch == LLM_ARCH_UNKNOWN) {
  4989. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  4990. }
  4991. }
  4992. static void llm_load_hparams(
  4993. llama_model_loader & ml,
  4994. llama_model & model) {
  4995. auto & hparams = model.hparams;
  4996. const gguf_context * ctx = ml.meta.get();
  4997. // get metadata as string
  4998. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  4999. enum gguf_type type = gguf_get_kv_type(ctx, i);
  5000. if (type == GGUF_TYPE_ARRAY) {
  5001. continue;
  5002. }
  5003. const char * name = gguf_get_key(ctx, i);
  5004. const std::string value = gguf_kv_to_str(ctx, i);
  5005. model.gguf_kv.emplace(name, value);
  5006. }
  5007. // get general kv
  5008. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  5009. // get hparams kv
  5010. ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab, false) || ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  5011. // everything past this point is not vocab-related
  5012. if (hparams.vocab_only) {
  5013. return;
  5014. }
  5015. ml.get_key(LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  5016. ml.get_key(LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  5017. ml.get_key(LLM_KV_BLOCK_COUNT, hparams.n_layer);
  5018. ml.get_key(LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  5019. ml.get_key(LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  5020. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  5021. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  5022. if (hparams.n_expert > 0) {
  5023. GGML_ASSERT(hparams.n_expert_used > 0);
  5024. } else {
  5025. GGML_ASSERT(hparams.n_expert_used == 0);
  5026. }
  5027. // zero-out the per-layer hparams
  5028. std::fill(hparams.n_head_arr.begin(), hparams.n_head_arr.end(), 0);
  5029. std::fill(hparams.n_head_kv_arr.begin(), hparams.n_head_kv_arr.end(), 0);
  5030. std::fill(hparams.n_ff_arr.begin(), hparams.n_ff_arr.end(), 0);
  5031. std::fill(hparams.cross_attn_layers.begin(), hparams.cross_attn_layers.end(), -1);
  5032. ml.get_key_or_arr(LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff_arr, hparams.n_layer);
  5033. ml.get_key_or_arr(LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head_arr, hparams.n_layer);
  5034. ml.get_arr(LLM_KV_ATTENTION_CROSS_ATTENTION_LAYERS, hparams.cross_attn_layers, false);
  5035. // n_head_kv is optional, default to n_head
  5036. hparams.n_head_kv_arr = hparams.n_head_arr;
  5037. ml.get_key_or_arr(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv_arr, hparams.n_layer, false);
  5038. bool rope_finetuned = false;
  5039. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  5040. hparams.rope_finetuned = rope_finetuned;
  5041. hparams.n_ctx_orig_yarn = hparams.n_ctx_train;
  5042. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_ctx_orig_yarn, false);
  5043. // rope_freq_base (optional)
  5044. hparams.rope_freq_base_train = 10000.0f;
  5045. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  5046. std::string rope_scaling("linear");
  5047. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  5048. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  5049. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  5050. // rope_freq_scale (inverse of the kv) is optional
  5051. float ropescale = 0.0f;
  5052. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  5053. // try the old key name
  5054. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  5055. }
  5056. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  5057. ml.get_key(LLM_KV_ROPE_SCALING_ATTN_FACTOR, hparams.rope_attn_factor, false);
  5058. // non-transformer models do not have attention heads
  5059. if (hparams.n_head() > 0) {
  5060. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  5061. // gpt-j n_rot = rotary_dim
  5062. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head();
  5063. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  5064. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head();
  5065. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  5066. // sanity check for n_rot (optional)
  5067. hparams.n_rot = hparams.n_embd_head_k;
  5068. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  5069. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_MLLAMA || model.arch == LLM_ARCH_FALCON) {
  5070. if (hparams.n_rot != hparams.n_embd_head_k) {
  5071. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd_head_k));
  5072. }
  5073. }
  5074. } else {
  5075. hparams.n_rot = 0;
  5076. hparams.n_embd_head_k = 0;
  5077. hparams.n_embd_head_v = 0;
  5078. }
  5079. // arch-specific KVs
  5080. switch (model.arch) {
  5081. case LLM_ARCH_LLAMA:
  5082. {
  5083. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5084. if (hparams.n_expert == 8) {
  5085. switch (hparams.n_layer) {
  5086. case 32: model.type = e_model::MODEL_8x7B; break;
  5087. case 56: model.type = e_model::MODEL_8x22B; break;
  5088. default: model.type = e_model::MODEL_UNKNOWN;
  5089. }
  5090. } else {
  5091. switch (hparams.n_layer) {
  5092. case 16: model.type = e_model::MODEL_1B; break; // Llama 3.2 1B
  5093. case 22: model.type = e_model::MODEL_1B; break;
  5094. case 26: model.type = e_model::MODEL_3B; break;
  5095. case 28: model.type = e_model::MODEL_3B; break; // Llama 3.2 3B
  5096. // granite uses a vocab with len 49152
  5097. case 32: model.type = hparams.n_vocab == 49152 ? e_model::MODEL_3B : (hparams.n_vocab < 40000 ? e_model::MODEL_7B : e_model::MODEL_8B); break;
  5098. case 36: model.type = e_model::MODEL_8B; break; // granite
  5099. case 40: model.type = e_model::MODEL_13B; break;
  5100. case 48: model.type = e_model::MODEL_34B; break;
  5101. case 60: model.type = e_model::MODEL_30B; break;
  5102. case 80: model.type = hparams.n_head() == hparams.n_head_kv() ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  5103. default: model.type = e_model::MODEL_UNKNOWN;
  5104. }
  5105. }
  5106. } break;
  5107. case LLM_ARCH_MLLAMA:
  5108. {
  5109. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5110. switch (hparams.n_layer) {
  5111. case 40: model.type = e_model::MODEL_11B; break;
  5112. case 100: model.type = e_model::MODEL_90B; break;
  5113. default: model.type = e_model::MODEL_UNKNOWN;
  5114. }
  5115. } break;
  5116. case LLM_ARCH_MINICPM:
  5117. {
  5118. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5119. switch (hparams.n_layer) {
  5120. case 40: model.type = e_model::MODEL_2B; break;
  5121. default: model.type = e_model::MODEL_UNKNOWN;
  5122. }
  5123. } break;
  5124. case LLM_ARCH_MINICPM3:
  5125. {
  5126. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5127. ml.get_key(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q);
  5128. ml.get_key(LLM_KV_ATTENTION_KV_LORA_RANK, hparams.n_lora_kv);
  5129. switch (hparams.n_layer) {
  5130. case 62: model.type = e_model::MODEL_4B; break;
  5131. default: model.type = e_model::MODEL_UNKNOWN;
  5132. }
  5133. } break;
  5134. case LLM_ARCH_GROK:
  5135. {
  5136. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5137. switch (hparams.n_layer) {
  5138. case 64: model.type = e_model::MODEL_314B; break;
  5139. default: model.type = e_model::MODEL_UNKNOWN;
  5140. }
  5141. } break;
  5142. case LLM_ARCH_FALCON:
  5143. {
  5144. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5145. switch (hparams.n_layer) {
  5146. case 32: model.type = e_model::MODEL_7B; break;
  5147. case 60: model.type = e_model::MODEL_40B; break;
  5148. default: model.type = e_model::MODEL_UNKNOWN;
  5149. }
  5150. } break;
  5151. case LLM_ARCH_BAICHUAN:
  5152. {
  5153. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5154. switch (hparams.n_layer) {
  5155. case 32: model.type = e_model::MODEL_7B; break;
  5156. case 40: model.type = e_model::MODEL_13B; break;
  5157. default: model.type = e_model::MODEL_UNKNOWN;
  5158. }
  5159. if (model.type == e_model::MODEL_13B) {
  5160. // TODO: become GGUF KV parameter
  5161. hparams.f_max_alibi_bias = 8.0f;
  5162. }
  5163. } break;
  5164. case LLM_ARCH_STARCODER:
  5165. {
  5166. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5167. switch (hparams.n_layer) {
  5168. case 24: model.type = e_model::MODEL_1B; break;
  5169. case 36: model.type = e_model::MODEL_3B; break;
  5170. case 42: model.type = e_model::MODEL_7B; break;
  5171. case 40: model.type = e_model::MODEL_15B; break;
  5172. default: model.type = e_model::MODEL_UNKNOWN;
  5173. }
  5174. } break;
  5175. case LLM_ARCH_REFACT:
  5176. {
  5177. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5178. switch (hparams.n_layer) {
  5179. case 32: model.type = e_model::MODEL_1B; break;
  5180. default: model.type = e_model::MODEL_UNKNOWN;
  5181. }
  5182. // TODO: become GGUF KV parameter
  5183. hparams.f_max_alibi_bias = 8.0f;
  5184. } break;
  5185. case LLM_ARCH_BERT:
  5186. {
  5187. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5188. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  5189. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  5190. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  5191. switch (hparams.n_layer) {
  5192. case 3:
  5193. model.type = e_model::MODEL_17M; break; // bge-micro
  5194. case 6:
  5195. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  5196. case 12:
  5197. switch (hparams.n_embd) {
  5198. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  5199. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  5200. } break;
  5201. case 24:
  5202. model.type = e_model::MODEL_335M; break; // bge-large
  5203. }
  5204. } break;
  5205. case LLM_ARCH_JINA_BERT_V2:
  5206. {
  5207. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5208. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  5209. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  5210. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  5211. hparams.f_max_alibi_bias = 8.0f;
  5212. switch (hparams.n_layer) {
  5213. case 4: model.type = e_model::MODEL_33M; break; // jina-embeddings-small
  5214. case 12: model.type = e_model::MODEL_137M; break; // jina-embeddings-base
  5215. }
  5216. } break;
  5217. case LLM_ARCH_NOMIC_BERT:
  5218. {
  5219. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5220. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  5221. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  5222. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  5223. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  5224. model.type = e_model::MODEL_137M;
  5225. }
  5226. } break;
  5227. case LLM_ARCH_BLOOM:
  5228. {
  5229. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5230. switch (hparams.n_layer) {
  5231. case 24: model.type = e_model::MODEL_1B; break;
  5232. case 30:
  5233. switch (hparams.n_embd) {
  5234. case 2560: model.type = e_model::MODEL_3B; break;
  5235. case 4096: model.type = e_model::MODEL_7B; break;
  5236. } break;
  5237. }
  5238. // TODO: become GGUF KV parameter
  5239. hparams.f_max_alibi_bias = 8.0f;
  5240. } break;
  5241. case LLM_ARCH_MPT:
  5242. {
  5243. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5244. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  5245. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  5246. switch (hparams.n_layer) {
  5247. case 32: model.type = e_model::MODEL_7B; break;
  5248. case 48: model.type = e_model::MODEL_30B; break;
  5249. default: model.type = e_model::MODEL_UNKNOWN;
  5250. }
  5251. } break;
  5252. case LLM_ARCH_STABLELM:
  5253. {
  5254. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5255. switch (hparams.n_layer) {
  5256. case 24: model.type = e_model::MODEL_1B; break;
  5257. case 32: model.type = e_model::MODEL_3B; break;
  5258. case 40: model.type = e_model::MODEL_12B; break;
  5259. default: model.type = e_model::MODEL_UNKNOWN;
  5260. }
  5261. } break;
  5262. case LLM_ARCH_QWEN:
  5263. {
  5264. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5265. switch (hparams.n_layer) {
  5266. case 32: model.type = e_model::MODEL_7B; break;
  5267. case 40: model.type = e_model::MODEL_13B; break;
  5268. default: model.type = e_model::MODEL_UNKNOWN;
  5269. }
  5270. } break;
  5271. case LLM_ARCH_QWEN2:
  5272. {
  5273. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5274. switch (hparams.n_layer) {
  5275. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  5276. case 28: model.type = hparams.n_embd == 1536 ? e_model::MODEL_1_5B : e_model::MODEL_7B; break;
  5277. case 32: model.type = e_model::MODEL_7B; break;
  5278. case 36: model.type = e_model::MODEL_3B; break;
  5279. case 40: model.type = hparams.n_head() == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  5280. case 48: model.type = e_model::MODEL_14B; break;
  5281. case 64: model.type = e_model::MODEL_32B; break;
  5282. case 80: model.type = e_model::MODEL_70B; break;
  5283. default: model.type = e_model::MODEL_UNKNOWN;
  5284. }
  5285. } break;
  5286. case LLM_ARCH_QWEN2MOE:
  5287. {
  5288. ml.get_key(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp, false);
  5289. ml.get_key(LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, hparams.n_ff_shexp, false);
  5290. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5291. switch (hparams.n_layer) {
  5292. case 24: model.type = e_model::MODEL_A2_7B; break;
  5293. case 28: model.type = e_model::MODEL_57B_A14B; break;
  5294. default: model.type = e_model::MODEL_UNKNOWN;
  5295. }
  5296. } break;
  5297. case LLM_ARCH_PHI2:
  5298. {
  5299. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5300. switch (hparams.n_layer) {
  5301. case 24: model.type = e_model::MODEL_1B; break;
  5302. case 32: model.type = e_model::MODEL_3B; break;
  5303. default: model.type = e_model::MODEL_UNKNOWN;
  5304. }
  5305. } break;
  5306. case LLM_ARCH_PHI3:
  5307. {
  5308. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5309. switch (hparams.n_layer) {
  5310. case 24: model.type = e_model::MODEL_1B; break;
  5311. case 32: model.type = e_model::MODEL_3B; break;
  5312. case 40: model.type = e_model::MODEL_14B; break;
  5313. default: model.type = e_model::MODEL_UNKNOWN;
  5314. }
  5315. // for backward compatibility ; see: https://github.com/ggerganov/llama.cpp/pull/8931
  5316. if ((hparams.n_layer == 32 || hparams.n_layer == 40) && hparams.n_ctx_train == 4096) {
  5317. // default value for Phi-3-mini-4k-instruct and Phi-3-medium-4k-instruct
  5318. hparams.n_swa = 2047;
  5319. } else if (hparams.n_layer == 32 && hparams.n_head_kv(0) == 32 && hparams.n_ctx_train == 131072) {
  5320. // default value for Phi-3-mini-128k-instruct
  5321. hparams.n_swa = 262144;
  5322. } else if (hparams.n_layer == 40 && hparams.n_ctx_train == 131072) {
  5323. // default value for Phi-3-medium-128k-instruct
  5324. hparams.n_swa = 131072;
  5325. }
  5326. bool found_swa = ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa, false);
  5327. if (!found_swa && hparams.n_swa == 0) {
  5328. throw std::runtime_error("invalid value for sliding_window");
  5329. }
  5330. } break;
  5331. case LLM_ARCH_PLAMO:
  5332. {
  5333. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5334. switch (hparams.n_layer) {
  5335. case 40: model.type = e_model::MODEL_13B; break;
  5336. default: model.type = e_model::MODEL_UNKNOWN;
  5337. }
  5338. } break;
  5339. case LLM_ARCH_GPT2:
  5340. {
  5341. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5342. switch (hparams.n_layer) {
  5343. case 12: model.type = e_model::MODEL_SMALL; break;
  5344. case 24: model.type = e_model::MODEL_MEDIUM; break;
  5345. case 36: model.type = e_model::MODEL_LARGE; break;
  5346. case 48: model.type = e_model::MODEL_XL; break;
  5347. default: model.type = e_model::MODEL_UNKNOWN;
  5348. }
  5349. } break;
  5350. case LLM_ARCH_CODESHELL:
  5351. {
  5352. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5353. switch (hparams.n_layer) {
  5354. case 42: model.type = e_model::MODEL_7B; break;
  5355. default: model.type = e_model::MODEL_UNKNOWN;
  5356. }
  5357. } break;
  5358. case LLM_ARCH_ORION:
  5359. {
  5360. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5361. switch (hparams.n_layer) {
  5362. case 40: model.type = e_model::MODEL_14B; break;
  5363. default: model.type = e_model::MODEL_UNKNOWN;
  5364. }
  5365. } break;
  5366. case LLM_ARCH_INTERNLM2:
  5367. {
  5368. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5369. switch (hparams.n_layer) {
  5370. case 32: model.type = e_model::MODEL_7B; break;
  5371. case 48: model.type = e_model::MODEL_20B; break;
  5372. default: model.type = e_model::MODEL_UNKNOWN;
  5373. }
  5374. } break;
  5375. case LLM_ARCH_GEMMA:
  5376. {
  5377. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5378. switch (hparams.n_layer) {
  5379. case 18: model.type = e_model::MODEL_2B; break;
  5380. case 28: model.type = e_model::MODEL_7B; break;
  5381. default: model.type = e_model::MODEL_UNKNOWN;
  5382. }
  5383. } break;
  5384. case LLM_ARCH_GEMMA2:
  5385. {
  5386. hparams.n_swa = 4096; // default value of gemma 2
  5387. ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa, false);
  5388. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5389. ml.get_key(LLM_KV_ATTN_LOGIT_SOFTCAPPING, hparams.f_attn_logit_softcapping, false);
  5390. ml.get_key(LLM_KV_FINAL_LOGIT_SOFTCAPPING, hparams.f_final_logit_softcapping, false);
  5391. hparams.attn_soft_cap = true;
  5392. switch (hparams.n_layer) {
  5393. case 26: model.type = e_model::MODEL_2B; break;
  5394. case 42: model.type = e_model::MODEL_9B; break;
  5395. case 46: model.type = e_model::MODEL_27B; break;
  5396. default: model.type = e_model::MODEL_UNKNOWN;
  5397. }
  5398. } break;
  5399. case LLM_ARCH_STARCODER2:
  5400. {
  5401. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5402. switch (hparams.n_layer) {
  5403. case 30: model.type = e_model::MODEL_3B; break;
  5404. case 32: model.type = e_model::MODEL_7B; break;
  5405. case 40: model.type = e_model::MODEL_15B; break;
  5406. case 52: model.type = e_model::MODEL_20B; break; // granite
  5407. case 88: model.type = e_model::MODEL_34B; break; // granite
  5408. default: model.type = e_model::MODEL_UNKNOWN;
  5409. }
  5410. } break;
  5411. case LLM_ARCH_MAMBA:
  5412. {
  5413. ml.get_key(LLM_KV_SSM_CONV_KERNEL, hparams.ssm_d_conv);
  5414. ml.get_key(LLM_KV_SSM_INNER_SIZE, hparams.ssm_d_inner);
  5415. ml.get_key(LLM_KV_SSM_STATE_SIZE, hparams.ssm_d_state);
  5416. ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
  5417. ml.get_key(LLM_KV_SSM_DT_B_C_RMS, hparams.ssm_dt_b_c_rms, false);
  5418. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5419. switch (hparams.n_layer) {
  5420. case 24:
  5421. switch (hparams.n_embd) {
  5422. case 768: model.type = e_model::MODEL_SMALL; break;
  5423. default: model.type = e_model::MODEL_UNKNOWN;
  5424. } break;
  5425. case 48:
  5426. switch (hparams.n_embd) {
  5427. case 1024: model.type = e_model::MODEL_MEDIUM; break;
  5428. case 1536: model.type = e_model::MODEL_LARGE; break;
  5429. case 2048: model.type = e_model::MODEL_XL; break;
  5430. default: model.type = e_model::MODEL_UNKNOWN;
  5431. } break;
  5432. case 64:
  5433. switch (hparams.n_embd) {
  5434. case 2560: model.type = e_model::MODEL_3B; break;
  5435. default: model.type = e_model::MODEL_UNKNOWN;
  5436. } break;
  5437. default: model.type = e_model::MODEL_UNKNOWN;
  5438. }
  5439. } break;
  5440. case LLM_ARCH_XVERSE:
  5441. {
  5442. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5443. switch (hparams.n_layer) {
  5444. case 32: model.type = e_model::MODEL_7B; break;
  5445. case 40: model.type = e_model::MODEL_13B; break;
  5446. case 80: model.type = e_model::MODEL_65B; break;
  5447. default: model.type = e_model::MODEL_UNKNOWN;
  5448. }
  5449. } break;
  5450. case LLM_ARCH_COMMAND_R:
  5451. {
  5452. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  5453. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5454. switch (hparams.n_layer) {
  5455. case 40: model.type = e_model::MODEL_35B; break;
  5456. default: model.type = e_model::MODEL_UNKNOWN;
  5457. }
  5458. } break;
  5459. case LLM_ARCH_DBRX:
  5460. {
  5461. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5462. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv);
  5463. switch (hparams.n_layer) {
  5464. case 40: model.type = e_model::MODEL_16x12B; break;
  5465. default: model.type = e_model::MODEL_UNKNOWN;
  5466. }
  5467. } break;
  5468. case LLM_ARCH_OLMO:
  5469. {
  5470. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5471. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  5472. switch (hparams.n_layer) {
  5473. case 22: model.type = e_model::MODEL_1B; break;
  5474. case 32: model.type = e_model::MODEL_7B; break;
  5475. case 80: model.type = e_model::MODEL_70B; break;
  5476. default: model.type = e_model::MODEL_UNKNOWN;
  5477. }
  5478. } break;
  5479. case LLM_ARCH_OLMO2:
  5480. {
  5481. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5482. switch (hparams.n_layer) {
  5483. case 16: model.type = e_model::MODEL_1B; break;
  5484. case 32: model.type = e_model::MODEL_7B; break;
  5485. case 40: model.type = e_model::MODEL_13B; break;
  5486. default: model.type = e_model::MODEL_UNKNOWN;
  5487. }
  5488. } break;
  5489. case LLM_ARCH_OLMOE:
  5490. {
  5491. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5492. switch (hparams.n_layer) {
  5493. case 16: model.type = e_model::MODEL_A1_7B; break;
  5494. default: model.type = e_model::MODEL_UNKNOWN;
  5495. }
  5496. } break;
  5497. case LLM_ARCH_OPENELM:
  5498. {
  5499. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5500. switch (hparams.n_layer) {
  5501. case 16: model.type = e_model::MODEL_270M; break;
  5502. case 20: model.type = e_model::MODEL_450M; break;
  5503. case 28: model.type = e_model::MODEL_1B; break;
  5504. case 36: model.type = e_model::MODEL_3B; break;
  5505. default: model.type = e_model::MODEL_UNKNOWN;
  5506. }
  5507. } break;
  5508. case LLM_ARCH_GPTNEOX:
  5509. {
  5510. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5511. ml.get_key(LLM_KV_USE_PARALLEL_RESIDUAL, hparams.use_par_res);
  5512. switch (hparams.n_layer) {
  5513. case 6:
  5514. switch (hparams.n_ff()) {
  5515. case 512: model.type = e_model::MODEL_14M; break;
  5516. case 2048: model.type = e_model::MODEL_70M; break;
  5517. default: model.type = e_model::MODEL_UNKNOWN;
  5518. } break;
  5519. case 12:
  5520. switch (hparams.n_ff()) {
  5521. case 3072: model.type = e_model::MODEL_160M; break;
  5522. default: model.type = e_model::MODEL_UNKNOWN;
  5523. } break;
  5524. case 16:
  5525. switch (hparams.n_ff()) {
  5526. case 8192: model.type = e_model::MODEL_1B; break;
  5527. default: model.type = e_model::MODEL_UNKNOWN;
  5528. } break;
  5529. case 24:
  5530. switch (hparams.n_ff()) {
  5531. case 4096: model.type = e_model::MODEL_410M; break;
  5532. case 8192: model.type = e_model::MODEL_1_4B; break;
  5533. default: model.type = e_model::MODEL_UNKNOWN;
  5534. } break;
  5535. case 32:
  5536. switch (hparams.n_ff()) {
  5537. case 10240: model.type = e_model::MODEL_2_8B; break;
  5538. case 16384: model.type = e_model::MODEL_6_9B; break;
  5539. default: model.type = e_model::MODEL_UNKNOWN;
  5540. } break;
  5541. case 36:
  5542. switch (hparams.n_ff()) {
  5543. case 20480: model.type = e_model::MODEL_12B; break;
  5544. default: model.type = e_model::MODEL_UNKNOWN;
  5545. } break;
  5546. case 44:
  5547. switch (hparams.n_ff()) {
  5548. case 24576: model.type = e_model::MODEL_20B; break;
  5549. default: model.type = e_model::MODEL_UNKNOWN;
  5550. } break;
  5551. default: model.type = e_model::MODEL_UNKNOWN;
  5552. }
  5553. } break;
  5554. case LLM_ARCH_ARCTIC:
  5555. {
  5556. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5557. if (hparams.n_expert == 128) {
  5558. switch (hparams.n_layer) {
  5559. case 35: model.type = e_model::MODEL_10B_128x3_66B; break;
  5560. default: model.type = e_model::MODEL_UNKNOWN;
  5561. }
  5562. } else {
  5563. model.type = e_model::MODEL_UNKNOWN;
  5564. }
  5565. } break;
  5566. case LLM_ARCH_DEEPSEEK2:
  5567. {
  5568. bool is_lite = (hparams.n_layer == 27);
  5569. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5570. ml.get_key(LLM_KV_LEADING_DENSE_BLOCK_COUNT, hparams.n_layer_dense_lead);
  5571. if (!is_lite) {
  5572. ml.get_key(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q);
  5573. }
  5574. ml.get_key(LLM_KV_ATTENTION_KV_LORA_RANK, hparams.n_lora_kv);
  5575. ml.get_key(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp);
  5576. ml.get_key(LLM_KV_EXPERT_SHARED_COUNT, hparams.n_expert_shared);
  5577. ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale);
  5578. ml.get_key(LLM_KV_ROPE_SCALING_YARN_LOG_MUL, hparams.rope_yarn_log_mul);
  5579. switch (hparams.n_layer) {
  5580. case 27: model.type = e_model::MODEL_16B; break;
  5581. case 60: model.type = e_model::MODEL_236B; break;
  5582. default: model.type = e_model::MODEL_UNKNOWN;
  5583. }
  5584. } break;
  5585. case LLM_ARCH_CHATGLM:
  5586. {
  5587. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5588. switch (hparams.n_layer) {
  5589. case 28: model.type = e_model::MODEL_6B; break;
  5590. case 40: model.type = e_model::MODEL_9B; break;
  5591. default: model.type = e_model::MODEL_UNKNOWN;
  5592. }
  5593. } break;
  5594. case LLM_ARCH_BITNET:
  5595. {
  5596. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5597. switch (hparams.n_layer) {
  5598. case 26: model.type = e_model::MODEL_3B; break;
  5599. default: model.type = e_model::MODEL_UNKNOWN;
  5600. }
  5601. } break;
  5602. case LLM_ARCH_T5:
  5603. {
  5604. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5605. ml.get_key(LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, hparams.n_rel_attn_bkts);
  5606. uint32_t dec_start_token_id;
  5607. if (ml.get_key(LLM_KV_DECODER_START_TOKEN_ID, dec_start_token_id, false)) {
  5608. hparams.dec_start_token_id = dec_start_token_id;
  5609. }
  5610. switch (hparams.n_layer) {
  5611. case 6: model.type = e_model::MODEL_60M; break; // t5-small
  5612. case 8: model.type = e_model::MODEL_80M; break; // flan-t5-small
  5613. case 12:
  5614. switch (hparams.n_ff()) {
  5615. case 3072: model.type = e_model::MODEL_220M; break; // t5-base
  5616. case 2048: model.type = e_model::MODEL_250M; break; // flan-t5-base
  5617. default: model.type = e_model::MODEL_UNKNOWN;
  5618. } break;
  5619. case 24:
  5620. switch (hparams.n_ff()) {
  5621. case 4096: model.type = e_model::MODEL_770M; break; // t5-large
  5622. case 2816: model.type = e_model::MODEL_780M; break; // flan-t5-large
  5623. case 16384: model.type = e_model::MODEL_3B; break; // t5-3b
  5624. case 5120: model.type = e_model::MODEL_3B; break; // flan-t5-xl
  5625. case 65536: model.type = e_model::MODEL_11B; break; // t5-11b
  5626. case 10240: model.type = e_model::MODEL_11B; break; // flan-t5-xxl
  5627. default: model.type = e_model::MODEL_UNKNOWN;
  5628. } break;
  5629. default: model.type = e_model::MODEL_UNKNOWN;
  5630. }
  5631. } break;
  5632. case LLM_ARCH_T5ENCODER:
  5633. {
  5634. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5635. ml.get_key(LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, hparams.n_rel_attn_bkts);
  5636. model.type = e_model::MODEL_UNKNOWN;
  5637. } break;
  5638. case LLM_ARCH_JAIS:
  5639. {
  5640. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5641. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  5642. switch (hparams.n_layer) {
  5643. case 24: model.type = e_model::MODEL_1_3B; break;
  5644. case 40: model.type = e_model::MODEL_13B; break;
  5645. /* TODO: add variants */
  5646. default: model.type = e_model::MODEL_UNKNOWN;
  5647. }
  5648. } break;
  5649. case LLM_ARCH_NEMOTRON:
  5650. {
  5651. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5652. switch (hparams.n_layer) {
  5653. case 32: model.type = e_model::MODEL_4B; break;
  5654. default: model.type = e_model::MODEL_UNKNOWN;
  5655. }
  5656. } break;
  5657. case LLM_ARCH_EXAONE:
  5658. {
  5659. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5660. switch (hparams.n_layer) {
  5661. case 32: model.type = e_model::MODEL_8B; break;
  5662. default: model.type = e_model::MODEL_UNKNOWN;
  5663. }
  5664. } break;
  5665. case LLM_ARCH_RWKV6:
  5666. {
  5667. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5668. ml.get_key(LLM_KV_WKV_HEAD_SIZE, hparams.wkv_head_size);
  5669. ml.get_key(LLM_KV_TIME_MIX_EXTRA_DIM, hparams.time_mix_extra_dim);
  5670. ml.get_key(LLM_KV_TIME_DECAY_EXTRA_DIM, hparams.time_decay_extra_dim);
  5671. ml.get_key(LLM_KV_RESCALE_EVERY_N_LAYERS, hparams.rescale_every_n_layers, false);
  5672. switch (hparams.n_layer) {
  5673. case 24: model.type = e_model::MODEL_1_6B; break;
  5674. case 32:
  5675. switch (hparams.n_embd) {
  5676. case 2560: model.type = e_model::MODEL_3B; break;
  5677. case 4096: model.type = e_model::MODEL_7B; break;
  5678. default: model.type = e_model::MODEL_UNKNOWN;
  5679. } break;
  5680. case 61: model.type = e_model::MODEL_14B; break;
  5681. default: model.type = e_model::MODEL_UNKNOWN;
  5682. }
  5683. } break;
  5684. case LLM_ARCH_GRANITE:
  5685. case LLM_ARCH_GRANITE_MOE:
  5686. {
  5687. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5688. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  5689. ml.get_key(LLM_KV_RESIDUAL_SCALE, hparams.f_residual_scale);
  5690. ml.get_key(LLM_KV_EMBEDDING_SCALE, hparams.f_embedding_scale);
  5691. ml.get_key(LLM_KV_ATTENTION_SCALE, hparams.f_attention_scale);
  5692. switch (hparams.n_layer) {
  5693. case 32: model.type = e_model::MODEL_3B; break;
  5694. case 40: model.type = e_model::MODEL_3B; break;
  5695. // Add additional layer/vocab/etc checks here for other model sizes
  5696. default: model.type = e_model::MODEL_UNKNOWN;
  5697. }
  5698. } break;
  5699. case LLM_ARCH_CHAMELEON:
  5700. {
  5701. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5702. hparams.f_norm_eps = 1e-5; // eps for qk-norm, torch default
  5703. ml.get_key(LLM_KV_SWIN_NORM, hparams.swin_norm);
  5704. switch (hparams.n_layer) {
  5705. case 32: model.type = e_model::MODEL_7B; break;
  5706. case 48: model.type = e_model::MODEL_34B; break;
  5707. default: model.type = e_model::MODEL_UNKNOWN;
  5708. }
  5709. } break;
  5710. case LLM_ARCH_SOLAR:
  5711. {
  5712. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5713. for (int i = 0; i < hparams.n_bskcn_arr.max_size(); ++i) {
  5714. auto & bskcn = hparams.n_bskcn_arr.at(i);
  5715. bskcn.fill(0);
  5716. ml.get_key_or_arr(::format(LLM_KV_NAMES.at(LLM_KV_ATTENTION_BLOCK_SKIP_CONNECTION), LLM_ARCH_NAMES.at(ml.llm_kv.arch), i), bskcn, hparams.n_layer, false);
  5717. }
  5718. switch (hparams.n_layer) {
  5719. case 64: model.type = e_model::MODEL_22B; break;
  5720. default: model.type = e_model::MODEL_UNKNOWN;
  5721. }
  5722. }
  5723. default: (void)0;
  5724. }
  5725. model.ftype = ml.ftype;
  5726. if (hparams.f_max_alibi_bias > 0.0f) {
  5727. hparams.use_alibi = true;
  5728. }
  5729. hparams.rope_type = llama_rope_type(&model);
  5730. }
  5731. static void llm_load_vocab(
  5732. llama_model_loader & ml,
  5733. llama_model & model) {
  5734. auto & vocab = model.vocab;
  5735. struct gguf_context * ctx = ml.meta.get();
  5736. const auto kv = LLM_KV(model.arch);
  5737. // determine vocab type
  5738. {
  5739. std::string tokenizer_model;
  5740. std::string tokenizer_pre;
  5741. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_model);
  5742. ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false);
  5743. if (tokenizer_model == "no_vocab") {
  5744. vocab.type = LLAMA_VOCAB_TYPE_NONE;
  5745. // default special tokens
  5746. vocab.special_bos_id = LLAMA_TOKEN_NULL;
  5747. vocab.special_eos_id = LLAMA_TOKEN_NULL;
  5748. vocab.special_unk_id = LLAMA_TOKEN_NULL;
  5749. vocab.special_sep_id = LLAMA_TOKEN_NULL;
  5750. vocab.special_pad_id = LLAMA_TOKEN_NULL;
  5751. vocab.special_cls_id = LLAMA_TOKEN_NULL;
  5752. vocab.special_mask_id = LLAMA_TOKEN_NULL;
  5753. vocab.linefeed_id = LLAMA_TOKEN_NULL;
  5754. // read vocab size from metadata
  5755. if (!ml.get_key(LLM_KV_VOCAB_SIZE, vocab.n_vocab, false)) {
  5756. vocab.n_vocab = 0;
  5757. LLAMA_LOG_WARN("%s: there is no vocab_size in metadata, vocab.n_vocab will be set to %u\n", __func__, vocab.n_vocab);
  5758. }
  5759. return;
  5760. }
  5761. if (tokenizer_model == "llama") {
  5762. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  5763. // default special tokens
  5764. vocab.special_bos_id = 1;
  5765. vocab.special_eos_id = 2;
  5766. vocab.special_unk_id = 0;
  5767. vocab.special_sep_id = LLAMA_TOKEN_NULL;
  5768. vocab.special_pad_id = LLAMA_TOKEN_NULL;
  5769. vocab.special_cls_id = LLAMA_TOKEN_NULL;
  5770. vocab.special_mask_id = LLAMA_TOKEN_NULL;
  5771. } else if (tokenizer_model == "bert") {
  5772. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  5773. // default special tokens
  5774. vocab.special_bos_id = LLAMA_TOKEN_NULL;
  5775. vocab.special_eos_id = LLAMA_TOKEN_NULL;
  5776. vocab.special_unk_id = 100;
  5777. vocab.special_sep_id = 102;
  5778. vocab.special_pad_id = 0;
  5779. vocab.special_cls_id = 101;
  5780. vocab.special_mask_id = 103;
  5781. } else if (tokenizer_model == "gpt2") {
  5782. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  5783. // read bpe merges and populate bpe ranks
  5784. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  5785. if (merges_keyidx == -1) {
  5786. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  5787. }
  5788. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  5789. for (int i = 0; i < n_merges; i++) {
  5790. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  5791. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  5792. std::string first;
  5793. std::string second;
  5794. const size_t pos = word.find(' ', 1);
  5795. if (pos != std::string::npos) {
  5796. first = word.substr(0, pos);
  5797. second = word.substr(pos + 1);
  5798. }
  5799. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  5800. }
  5801. // default special tokens
  5802. vocab.special_bos_id = 11;
  5803. vocab.special_eos_id = 11;
  5804. vocab.special_unk_id = LLAMA_TOKEN_NULL;
  5805. vocab.special_sep_id = LLAMA_TOKEN_NULL;
  5806. vocab.special_pad_id = LLAMA_TOKEN_NULL;
  5807. vocab.special_cls_id = LLAMA_TOKEN_NULL;
  5808. vocab.special_mask_id = LLAMA_TOKEN_NULL;
  5809. } else if (tokenizer_model == "t5") {
  5810. vocab.type = LLAMA_VOCAB_TYPE_UGM;
  5811. // default special tokens
  5812. vocab.special_bos_id = LLAMA_TOKEN_NULL;
  5813. vocab.special_eos_id = 1;
  5814. vocab.special_unk_id = 2;
  5815. vocab.special_sep_id = LLAMA_TOKEN_NULL;
  5816. vocab.special_pad_id = 0;
  5817. vocab.special_cls_id = LLAMA_TOKEN_NULL;
  5818. vocab.special_mask_id = LLAMA_TOKEN_NULL;
  5819. const int precompiled_charsmap_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP).c_str());
  5820. if (precompiled_charsmap_keyidx != -1) {
  5821. size_t n_precompiled_charsmap = gguf_get_arr_n(ctx, precompiled_charsmap_keyidx);
  5822. const char * precompiled_charsmap = (const char *) gguf_get_arr_data(ctx, precompiled_charsmap_keyidx);
  5823. vocab.precompiled_charsmap.assign(precompiled_charsmap, precompiled_charsmap + n_precompiled_charsmap);
  5824. #ifdef IS_BIG_ENDIAN
  5825. // correct endiannes of data in precompiled_charsmap binary blob
  5826. uint32_t * xcda_blob_size = (uint32_t *) &vocab.precompiled_charsmap[0];
  5827. *xcda_blob_size = __builtin_bswap32(*xcda_blob_size);
  5828. assert(*xcda_blob_size + sizeof(uint32_t) < n_precompiled_charsmap);
  5829. size_t xcda_array_size = *xcda_blob_size / sizeof(uint32_t);
  5830. uint32_t * xcda_array = (uint32_t *) &vocab.precompiled_charsmap[sizeof(uint32_t)];
  5831. for (size_t i = 0; i < xcda_array_size; ++i) {
  5832. xcda_array[i] = __builtin_bswap32(xcda_array[i]);
  5833. }
  5834. #endif
  5835. }
  5836. } else if (tokenizer_model == "rwkv") {
  5837. vocab.type = LLAMA_VOCAB_TYPE_RWKV;
  5838. // default special tokens
  5839. vocab.special_bos_id = LLAMA_TOKEN_NULL;
  5840. vocab.special_eos_id = LLAMA_TOKEN_NULL;
  5841. vocab.special_unk_id = LLAMA_TOKEN_NULL;
  5842. vocab.special_sep_id = LLAMA_TOKEN_NULL;
  5843. vocab.special_pad_id = LLAMA_TOKEN_NULL;
  5844. } else {
  5845. throw std::runtime_error(format("unknown tokenizer: '%s'", tokenizer_model.c_str()));
  5846. }
  5847. // for now, only BPE models have pre-tokenizers
  5848. if (vocab.type == LLAMA_VOCAB_TYPE_BPE) {
  5849. vocab.tokenizer_add_space_prefix = false;
  5850. vocab.tokenizer_clean_spaces = true;
  5851. if (tokenizer_pre == "default") {
  5852. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5853. } else if (
  5854. tokenizer_pre == "llama3" ||
  5855. tokenizer_pre == "llama-v3" ||
  5856. tokenizer_pre == "llama-bpe") {
  5857. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_LLAMA3;
  5858. vocab.tokenizer_ignore_merges = true;
  5859. vocab.tokenizer_add_bos = true;
  5860. } else if (
  5861. tokenizer_pre == "deepseek-llm") {
  5862. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM;
  5863. vocab.tokenizer_clean_spaces = false;
  5864. } else if (
  5865. tokenizer_pre == "deepseek-coder") {
  5866. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER;
  5867. vocab.tokenizer_clean_spaces = false;
  5868. } else if (
  5869. tokenizer_pre == "falcon") {
  5870. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_FALCON;
  5871. } else if (
  5872. tokenizer_pre == "mpt") {
  5873. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_MPT;
  5874. } else if (
  5875. tokenizer_pre == "starcoder") {
  5876. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_STARCODER;
  5877. } else if (
  5878. tokenizer_pre == "gpt-2" ||
  5879. tokenizer_pre == "phi-2" ||
  5880. tokenizer_pre == "jina-es" ||
  5881. tokenizer_pre == "jina-de" ||
  5882. tokenizer_pre == "jina-v1-en" ||
  5883. tokenizer_pre == "jina-v2-es" ||
  5884. tokenizer_pre == "jina-v2-de" ||
  5885. tokenizer_pre == "jina-v2-code") {
  5886. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_GPT2;
  5887. } else if (
  5888. tokenizer_pre == "refact") {
  5889. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_REFACT;
  5890. } else if (
  5891. tokenizer_pre == "command-r") {
  5892. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_COMMAND_R;
  5893. vocab.tokenizer_clean_spaces = false;
  5894. } else if (
  5895. tokenizer_pre == "qwen2") {
  5896. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_QWEN2;
  5897. vocab.tokenizer_clean_spaces = false;
  5898. } else if (
  5899. tokenizer_pre == "stablelm2") {
  5900. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_STABLELM2;
  5901. } else if (
  5902. tokenizer_pre == "olmo") {
  5903. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_OLMO;
  5904. } else if (
  5905. tokenizer_pre == "dbrx") {
  5906. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DBRX;
  5907. } else if (
  5908. tokenizer_pre == "smaug-bpe") {
  5909. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_SMAUG;
  5910. } else if (
  5911. tokenizer_pre == "poro-chat") {
  5912. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_PORO;
  5913. vocab.tokenizer_clean_spaces = false;
  5914. } else if (
  5915. tokenizer_pre == "chatglm-bpe") {
  5916. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_CHATGLM4;
  5917. vocab.special_bos_id = LLAMA_TOKEN_NULL;
  5918. } else if (
  5919. tokenizer_pre == "viking") {
  5920. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_VIKING;
  5921. vocab.tokenizer_clean_spaces = false;
  5922. } else if (
  5923. tokenizer_pre == "jais") {
  5924. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_JAIS;
  5925. } else if (
  5926. tokenizer_pre == "tekken") {
  5927. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_TEKKEN;
  5928. vocab.tokenizer_clean_spaces = false;
  5929. vocab.tokenizer_ignore_merges = true;
  5930. vocab.tokenizer_add_bos = true;
  5931. } else if (
  5932. tokenizer_pre == "smollm") {
  5933. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_SMOLLM;
  5934. vocab.tokenizer_clean_spaces = false;
  5935. } else if (
  5936. tokenizer_pre == "codeshell") {
  5937. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_CODESHELL;
  5938. } else if (
  5939. tokenizer_pre == "bloom") {
  5940. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_BLOOM;
  5941. } else if (
  5942. tokenizer_pre == "gpt3-finnish") {
  5943. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_GPT3_FINNISH;
  5944. } else if (
  5945. tokenizer_pre == "exaone") {
  5946. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_EXAONE;
  5947. } else if (
  5948. tokenizer_pre == "chameleon") {
  5949. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_CHAMELEON;
  5950. vocab.tokenizer_add_bos = true;
  5951. vocab.tokenizer_clean_spaces = false;
  5952. } else {
  5953. LLAMA_LOG_WARN("%s: missing or unrecognized pre-tokenizer type, using: 'default'\n", __func__);
  5954. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5955. }
  5956. } else if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  5957. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5958. vocab.tokenizer_add_space_prefix = true;
  5959. vocab.tokenizer_clean_spaces = false;
  5960. vocab.tokenizer_add_bos = true;
  5961. vocab.tokenizer_add_eos = false;
  5962. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  5963. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5964. vocab.tokenizer_add_space_prefix = false;
  5965. vocab.tokenizer_clean_spaces = true;
  5966. vocab.tokenizer_add_bos = true;
  5967. vocab.tokenizer_add_eos = false;
  5968. } else if (vocab.type == LLAMA_VOCAB_TYPE_UGM) {
  5969. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5970. vocab.tokenizer_add_bos = false;
  5971. vocab.tokenizer_add_eos = true;
  5972. } else if (vocab.type == LLAMA_VOCAB_TYPE_RWKV) {
  5973. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5974. vocab.tokenizer_add_space_prefix = false;
  5975. vocab.tokenizer_clean_spaces = false;
  5976. vocab.tokenizer_add_bos = false;
  5977. vocab.tokenizer_add_eos = false;
  5978. } else {
  5979. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5980. }
  5981. ml.get_key(LLM_KV_TOKENIZER_ADD_PREFIX, vocab.tokenizer_add_space_prefix, false);
  5982. ml.get_key(LLM_KV_TOKENIZER_REMOVE_EXTRA_WS, vocab.tokenizer_remove_extra_whitespaces, false);
  5983. }
  5984. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  5985. if (token_idx == -1) {
  5986. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  5987. }
  5988. const float * scores = nullptr;
  5989. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  5990. if (score_idx != -1) {
  5991. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  5992. }
  5993. const int * toktypes = nullptr;
  5994. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  5995. if (toktype_idx != -1) {
  5996. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  5997. }
  5998. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  5999. vocab.n_vocab = n_vocab;
  6000. vocab.id_to_token.resize(n_vocab);
  6001. for (uint32_t i = 0; i < n_vocab; i++) {
  6002. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  6003. //GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  6004. if (word.empty()) {
  6005. LLAMA_LOG_WARN("%s: empty token at index %u\n", __func__, i);
  6006. word = "[EMPTY_" + std::to_string(i) + "]";
  6007. }
  6008. vocab.token_to_id[word] = i;
  6009. vocab.max_token_len = std::max(vocab.max_token_len, (int) word.size());
  6010. auto & token_data = vocab.id_to_token[i];
  6011. token_data.text = std::move(word);
  6012. token_data.score = scores ? scores[i] : 0.0f;
  6013. token_data.attr = LLAMA_TOKEN_ATTR_NORMAL;
  6014. if (toktypes) { //TODO: remove, required until per token attributes are available from GGUF file
  6015. switch(toktypes[i]) {
  6016. case LLAMA_TOKEN_TYPE_UNKNOWN: token_data.attr = LLAMA_TOKEN_ATTR_UNKNOWN; break;
  6017. case LLAMA_TOKEN_TYPE_UNUSED: token_data.attr = LLAMA_TOKEN_ATTR_UNUSED; break;
  6018. case LLAMA_TOKEN_TYPE_NORMAL: token_data.attr = LLAMA_TOKEN_ATTR_NORMAL; break;
  6019. case LLAMA_TOKEN_TYPE_CONTROL: token_data.attr = LLAMA_TOKEN_ATTR_CONTROL; break;
  6020. case LLAMA_TOKEN_TYPE_USER_DEFINED: token_data.attr = LLAMA_TOKEN_ATTR_USER_DEFINED; break;
  6021. case LLAMA_TOKEN_TYPE_BYTE: token_data.attr = LLAMA_TOKEN_ATTR_BYTE; break;
  6022. case LLAMA_TOKEN_TYPE_UNDEFINED: token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED; break;
  6023. default: token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED; break;
  6024. }
  6025. }
  6026. }
  6027. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  6028. vocab.init_tokenizer();
  6029. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  6030. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  6031. try {
  6032. vocab.linefeed_id = llama_byte_to_token_impl(vocab, '\n');
  6033. } catch (const std::exception & e) {
  6034. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  6035. vocab.linefeed_id = vocab.special_pad_id;
  6036. }
  6037. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  6038. vocab.linefeed_id = vocab.special_pad_id;
  6039. } else if (vocab.type == LLAMA_VOCAB_TYPE_RWKV) {
  6040. const std::vector<int> ids = llama_tokenize_internal(vocab, "\n", false);
  6041. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  6042. vocab.linefeed_id = ids[0];
  6043. } else {
  6044. const std::vector<int> ids = llama_tokenize_internal(vocab, "\xC4\x8A", false); // U+010A
  6045. //GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  6046. if (ids.empty()) {
  6047. LLAMA_LOG_WARN("%s: model vocab missing newline token, using special_pad_id instead\n", __func__);
  6048. vocab.linefeed_id = vocab.special_pad_id;
  6049. } else {
  6050. vocab.linefeed_id = ids[0];
  6051. }
  6052. }
  6053. // special tokens
  6054. {
  6055. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  6056. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  6057. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  6058. { LLM_KV_TOKENIZER_EOT_ID, vocab.special_eot_id },
  6059. { LLM_KV_TOKENIZER_EOM_ID, vocab.special_eom_id },
  6060. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  6061. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  6062. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  6063. { LLM_KV_TOKENIZER_CLS_ID, vocab.special_cls_id },
  6064. { LLM_KV_TOKENIZER_MASK_ID, vocab.special_mask_id },
  6065. { LLM_KV_TOKENIZER_FIM_PRE_ID, vocab.special_fim_pre_id },
  6066. { LLM_KV_TOKENIZER_FIM_SUF_ID, vocab.special_fim_suf_id },
  6067. { LLM_KV_TOKENIZER_FIM_MID_ID, vocab.special_fim_mid_id },
  6068. { LLM_KV_TOKENIZER_FIM_PAD_ID, vocab.special_fim_pad_id },
  6069. { LLM_KV_TOKENIZER_FIM_REP_ID, vocab.special_fim_rep_id },
  6070. { LLM_KV_TOKENIZER_FIM_SEP_ID, vocab.special_fim_sep_id },
  6071. // deprecated
  6072. { LLM_KV_TOKENIZER_PREFIX_ID, vocab.special_fim_pre_id },
  6073. { LLM_KV_TOKENIZER_SUFFIX_ID, vocab.special_fim_suf_id },
  6074. { LLM_KV_TOKENIZER_MIDDLE_ID, vocab.special_fim_mid_id },
  6075. };
  6076. for (const auto & it : special_token_types) {
  6077. const std::string & key = kv(std::get<0>(it));
  6078. int32_t & id = std::get<1>(it);
  6079. uint32_t new_id;
  6080. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  6081. continue;
  6082. }
  6083. if (new_id >= vocab.id_to_token.size()) {
  6084. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  6085. __func__, key.c_str(), new_id, id);
  6086. } else {
  6087. id = new_id;
  6088. }
  6089. }
  6090. // Handle add_bos_token and add_eos_token
  6091. {
  6092. bool temp = true;
  6093. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  6094. vocab.tokenizer_add_bos = temp;
  6095. }
  6096. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  6097. vocab.tokenizer_add_eos = temp;
  6098. }
  6099. }
  6100. // auto-detect special tokens by text
  6101. // TODO: convert scripts should provide these tokens through the KV metadata LLM_KV_TOKENIZER_...
  6102. // for now, we apply this workaround to find the tokens based on their text
  6103. for (const auto & t : vocab.token_to_id) {
  6104. // find EOT token: "<|eot_id|>", "<|im_end|>", "<end_of_turn>", etc.
  6105. if (vocab.special_eot_id == LLAMA_TOKEN_NULL) {
  6106. if (false
  6107. || t.first == "<|eot_id|>"
  6108. || t.first == "<|im_end|>"
  6109. || t.first == "<|end|>"
  6110. || t.first == "<end_of_turn>"
  6111. || t.first == "<|endoftext|>"
  6112. || t.first == "<EOT>"
  6113. || t.first == "<|end▁of▁sentence|>" // DeepSeek
  6114. ) {
  6115. vocab.special_eot_id = t.second;
  6116. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6117. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  6118. __func__, t.second, t.first.c_str());
  6119. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6120. }
  6121. }
  6122. }
  6123. // find EOM token: "<|eom_id|>"
  6124. if (vocab.special_eom_id == LLAMA_TOKEN_NULL) {
  6125. if (false
  6126. || t.first == "<|eom_id|>"
  6127. ) {
  6128. vocab.special_eom_id = t.second;
  6129. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6130. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  6131. __func__, t.second, t.first.c_str());
  6132. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6133. }
  6134. }
  6135. }
  6136. // find FIM_PRE token: "<|fim_prefix|>", "<fim-prefix>", "<PRE>", etc.
  6137. if (vocab.special_fim_pre_id == LLAMA_TOKEN_NULL) {
  6138. if (false
  6139. || t.first == "<|fim_prefix|>" // Qwen
  6140. || t.first == "<fim-prefix>"
  6141. || t.first == "<|fim▁begin|>" // DeepSeek
  6142. || t.first == "<PRE>"
  6143. ) {
  6144. vocab.special_fim_pre_id = t.second;
  6145. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6146. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  6147. __func__, t.second, t.first.c_str());
  6148. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6149. }
  6150. }
  6151. }
  6152. // find FIM_SUF token: "<|fim_suffix|>", "<fim-suffix>", "<SUF>", etc.
  6153. if (vocab.special_fim_suf_id == LLAMA_TOKEN_NULL) {
  6154. if (false
  6155. || t.first == "<|fim_suffix|>" // Qwen
  6156. || t.first == "<fim-suffix>"
  6157. || t.first == "<|fim▁hole|>" // DeepSeek
  6158. || t.first == "<SUF>"
  6159. ) {
  6160. vocab.special_fim_suf_id = t.second;
  6161. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6162. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  6163. __func__, t.second, t.first.c_str());
  6164. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6165. }
  6166. }
  6167. }
  6168. // find FIM_MID token: "<|fim_middle|>", "<fim-middle>", "<MID>", etc.
  6169. if (vocab.special_fim_mid_id == LLAMA_TOKEN_NULL) {
  6170. if (false
  6171. || t.first == "<|fim_middle|>" // Qwen
  6172. || t.first == "<fim-middle>"
  6173. || t.first == "<|fim▁end|>" // DeepSeek
  6174. || t.first == "<MID>"
  6175. ) {
  6176. vocab.special_fim_mid_id = t.second;
  6177. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6178. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  6179. __func__, t.second, t.first.c_str());
  6180. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6181. }
  6182. }
  6183. }
  6184. // find FIM_PAD token: "<|fim_pad|>", "<fim-pad>", "<PAD>", etc.
  6185. if (vocab.special_fim_pad_id == LLAMA_TOKEN_NULL) {
  6186. if (false
  6187. || t.first == "<|fim_pad|>" // Qwen
  6188. || t.first == "<fim-pad>"
  6189. || t.first == "<PAD>"
  6190. ) {
  6191. vocab.special_fim_pad_id = t.second;
  6192. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6193. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  6194. __func__, t.second, t.first.c_str());
  6195. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6196. }
  6197. }
  6198. }
  6199. // find FIM_REP token: "<|fim_repo|>", "<fim-repo>", "<REP>", etc.
  6200. if (vocab.special_fim_rep_id == LLAMA_TOKEN_NULL) {
  6201. if (false
  6202. || t.first == "<|fim_repo|>" // Qwen
  6203. || t.first == "<|repo_name|>"
  6204. || t.first == "<fim-repo>"
  6205. || t.first == "<REPO>"
  6206. ) {
  6207. vocab.special_fim_rep_id = t.second;
  6208. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6209. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  6210. __func__, t.second, t.first.c_str());
  6211. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6212. }
  6213. }
  6214. }
  6215. // find FIM_SEP token: "<|file_sep|>"
  6216. if (vocab.special_fim_sep_id == LLAMA_TOKEN_NULL) {
  6217. if (false
  6218. || t.first == "<|file_sep|>" // Qwen
  6219. ) {
  6220. vocab.special_fim_sep_id = t.second;
  6221. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6222. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  6223. __func__, t.second, t.first.c_str());
  6224. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6225. }
  6226. }
  6227. }
  6228. }
  6229. // maintain a list of tokens that cause end-of-generation
  6230. // this is currently determined based on the token text, which is obviously not ideal
  6231. // ref: https://github.com/ggerganov/llama.cpp/issues/9606
  6232. vocab.special_eog_ids.clear();
  6233. if (vocab.special_fim_pad_id != LLAMA_TOKEN_NULL && vocab.special_eog_ids.count(vocab.special_fim_pad_id) == 0) {
  6234. vocab.special_eog_ids.insert(vocab.special_fim_pad_id);
  6235. }
  6236. if (vocab.special_fim_rep_id != LLAMA_TOKEN_NULL && vocab.special_eog_ids.count(vocab.special_fim_rep_id) == 0) {
  6237. vocab.special_eog_ids.insert(vocab.special_fim_rep_id);
  6238. }
  6239. if (vocab.special_fim_sep_id != LLAMA_TOKEN_NULL && vocab.special_eog_ids.count(vocab.special_fim_sep_id) == 0) {
  6240. vocab.special_eog_ids.insert(vocab.special_fim_sep_id);
  6241. }
  6242. for (const auto & t : vocab.token_to_id) {
  6243. if (false
  6244. || t.first == "<|eot_id|>"
  6245. || t.first == "<|im_end|>"
  6246. || t.first == "<|end|>"
  6247. || t.first == "<end_of_turn>"
  6248. || t.first == "<|endoftext|>"
  6249. || t.first == "<|eom_id|>"
  6250. || t.first == "<EOT>"
  6251. ) {
  6252. vocab.special_eog_ids.insert(t.second);
  6253. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6254. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  6255. __func__, t.second, t.first.c_str());
  6256. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6257. }
  6258. } else {
  6259. // token is control, but not marked as EOG -> print a debug log
  6260. if (vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL && vocab.special_eog_ids.count(t.second) == 0) {
  6261. LLAMA_LOG_DEBUG("%s: control token: %6d '%s' is not marked as EOG\n",
  6262. __func__, t.second, t.first.c_str());
  6263. }
  6264. }
  6265. }
  6266. // sanity checks
  6267. if (vocab.special_eos_id != LLAMA_TOKEN_NULL && vocab.special_eog_ids.count(vocab.special_eos_id) == 0) {
  6268. vocab.special_eog_ids.insert(vocab.special_eos_id);
  6269. LLAMA_LOG_WARN("%s: special_eos_id is not in special_eog_ids - the tokenizer config may be incorrect\n", __func__);
  6270. }
  6271. if (vocab.special_eot_id != LLAMA_TOKEN_NULL && vocab.special_eog_ids.count(vocab.special_eot_id) == 0) {
  6272. vocab.special_eog_ids.insert(vocab.special_eot_id);
  6273. LLAMA_LOG_WARN("%s: special_eot_id is not in special_eog_ids - the tokenizer config may be incorrect\n", __func__);
  6274. }
  6275. if (vocab.special_eom_id != LLAMA_TOKEN_NULL && vocab.special_eog_ids.count(vocab.special_eom_id) == 0) {
  6276. vocab.special_eog_ids.insert(vocab.special_eom_id);
  6277. LLAMA_LOG_WARN("%s: special_eom_id is not in special_eog_ids - the tokenizer config may be incorrect\n", __func__);
  6278. }
  6279. }
  6280. // build special tokens cache
  6281. {
  6282. for (llama_vocab::id id = 0; id < (llama_vocab::id)n_vocab; ++id) {
  6283. if (vocab.id_to_token[id].attr & (LLAMA_TOKEN_ATTR_CONTROL | LLAMA_TOKEN_ATTR_USER_DEFINED | LLAMA_TOKEN_ATTR_UNKNOWN)) {
  6284. vocab.cache_special_tokens.push_back(id);
  6285. }
  6286. }
  6287. std::sort(vocab.cache_special_tokens.begin(), vocab.cache_special_tokens.end(),
  6288. [&] (const llama_vocab::id a, const llama_vocab::id b) {
  6289. return vocab.id_to_token[a].text.size() > vocab.id_to_token[b].text.size();
  6290. }
  6291. );
  6292. LLAMA_LOG_INFO("%s: special tokens cache size = %u\n", __func__, (uint32_t)vocab.cache_special_tokens.size());
  6293. }
  6294. // build token to piece cache
  6295. {
  6296. size_t size_cache = 0;
  6297. std::vector<llama_vocab::token> cache_token_to_piece(n_vocab);
  6298. for (uint32_t id = 0; id < n_vocab; ++id) {
  6299. cache_token_to_piece[id] = llama_token_to_piece(&model, id, true);
  6300. size_cache += cache_token_to_piece[id].size();
  6301. }
  6302. std::swap(vocab.cache_token_to_piece, cache_token_to_piece);
  6303. LLAMA_LOG_INFO("%s: token to piece cache size = %.4f MB\n", __func__, size_cache / 1024.0 / 1024.0);
  6304. }
  6305. // Handle per token attributes
  6306. //NOTE: Each model customizes per token attributes.
  6307. //NOTE: Per token attributes are missing from the GGUF file.
  6308. //TODO: Extract attributes from GGUF file.
  6309. {
  6310. auto _contains_any = [] (const std::string &str, const std::vector<std::string> &substrs) -> bool {
  6311. for (auto substr : substrs) {
  6312. if (str.find(substr) < std::string::npos) {
  6313. return true;
  6314. }
  6315. }
  6316. return false;
  6317. };
  6318. auto _set_tokenid_attr = [&] (const llama_vocab::id id, llama_token_attr attr, bool value) {
  6319. uint32_t current = vocab.id_to_token.at(id).attr;
  6320. current = value ? (current | attr) : (current & ~attr);
  6321. vocab.id_to_token[id].attr = (llama_token_attr) current;
  6322. };
  6323. auto _set_token_attr = [&] (const std::string & token, llama_token_attr attr, bool value) {
  6324. _set_tokenid_attr(vocab.token_to_id.at(token), attr, value);
  6325. };
  6326. std::string model_name;
  6327. std::string tokenizer_pre;
  6328. ml.get_key(LLM_KV_GENERAL_NAME, model_name, false);
  6329. ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false);
  6330. // model name to lowercase
  6331. std::transform(model_name.begin(), model_name.end(), model_name.begin(),
  6332. [] (const std::string::value_type x) {
  6333. return std::tolower(x);
  6334. }
  6335. );
  6336. // set attributes by model/tokenizer name
  6337. if (_contains_any(tokenizer_pre, {"jina-v2-de", "jina-v2-es", "jina-v2-code"})) {
  6338. _set_token_attr("<mask>", LLAMA_TOKEN_ATTR_LSTRIP, true);
  6339. } else if (_contains_any(model_name, {"phi-3", "phi3"})) {
  6340. for (auto id : vocab.cache_special_tokens) {
  6341. _set_tokenid_attr(id, LLAMA_TOKEN_ATTR_RSTRIP, true);
  6342. }
  6343. for (auto token : {"</s>"}) {
  6344. _set_token_attr(token, LLAMA_TOKEN_ATTR_RSTRIP, true);
  6345. }
  6346. for (auto token : {"<unk>", "<s>", "<|endoftext|>"}) {
  6347. _set_token_attr(token, LLAMA_TOKEN_ATTR_RSTRIP, false);
  6348. }
  6349. }
  6350. }
  6351. }
  6352. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  6353. const auto & hparams = model.hparams;
  6354. const auto & vocab = model.vocab;
  6355. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  6356. auto print_f = [](const std::function<uint32_t(uint32_t)> & f, uint32_t n) {
  6357. bool is_var = false;
  6358. std::vector<uint32_t> v;
  6359. for (uint32_t i = 0; i < n; ++i) {
  6360. v.push_back(f(i));
  6361. if (v[i] != v[0]) {
  6362. is_var = true;
  6363. }
  6364. }
  6365. std::stringstream ss;
  6366. if (is_var) {
  6367. ss << "[";
  6368. for (uint32_t i = 0; i < n; ++i) {
  6369. ss << v[i];
  6370. if (i < n - 1) {
  6371. ss << ", ";
  6372. }
  6373. }
  6374. ss << "]";
  6375. } else {
  6376. ss << v[0];
  6377. }
  6378. return ss.str();
  6379. };
  6380. // hparams
  6381. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  6382. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  6383. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  6384. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  6385. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  6386. LLAMA_LOG_INFO("%s: vocab_only = %d\n", __func__, hparams.vocab_only);
  6387. if (!hparams.vocab_only) {
  6388. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  6389. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  6390. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  6391. LLAMA_LOG_INFO("%s: n_head = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_head(il); }, hparams.n_layer).c_str());
  6392. LLAMA_LOG_INFO("%s: n_head_kv = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_head_kv(il); }, hparams.n_layer).c_str());
  6393. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  6394. LLAMA_LOG_INFO("%s: n_swa = %u\n", __func__, hparams.n_swa);
  6395. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  6396. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  6397. LLAMA_LOG_INFO("%s: n_gqa = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_gqa(il); }, hparams.n_layer).c_str());
  6398. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_embd_k_gqa(il); }, hparams.n_layer).c_str());
  6399. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_embd_v_gqa(il); }, hparams.n_layer).c_str());
  6400. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  6401. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  6402. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  6403. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  6404. LLAMA_LOG_INFO("%s: f_logit_scale = %.1e\n", __func__, hparams.f_logit_scale);
  6405. LLAMA_LOG_INFO("%s: n_ff = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_ff(il); }, hparams.n_layer).c_str());
  6406. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  6407. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  6408. LLAMA_LOG_INFO("%s: causal attn = %d\n", __func__, hparams.causal_attn);
  6409. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  6410. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  6411. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  6412. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  6413. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  6414. LLAMA_LOG_INFO("%s: n_ctx_orig_yarn = %u\n", __func__, hparams.n_ctx_orig_yarn);
  6415. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  6416. LLAMA_LOG_INFO("%s: ssm_d_conv = %u\n", __func__, hparams.ssm_d_conv);
  6417. LLAMA_LOG_INFO("%s: ssm_d_inner = %u\n", __func__, hparams.ssm_d_inner);
  6418. LLAMA_LOG_INFO("%s: ssm_d_state = %u\n", __func__, hparams.ssm_d_state);
  6419. LLAMA_LOG_INFO("%s: ssm_dt_rank = %u\n", __func__, hparams.ssm_dt_rank);
  6420. LLAMA_LOG_INFO("%s: ssm_dt_b_c_rms = %d\n", __func__, hparams.ssm_dt_b_c_rms);
  6421. }
  6422. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  6423. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  6424. if (ml.n_elements >= 1e12) {
  6425. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  6426. } else if (ml.n_elements >= 1e9) {
  6427. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  6428. } else if (ml.n_elements >= 1e6) {
  6429. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  6430. } else {
  6431. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  6432. }
  6433. if (ml.n_bytes < GiB) {
  6434. 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);
  6435. } else {
  6436. 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);
  6437. }
  6438. // general kv
  6439. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  6440. // special tokens
  6441. 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() ); }
  6442. 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() ); }
  6443. if (vocab.special_eot_id != -1) { LLAMA_LOG_INFO( "%s: EOT token = %d '%s'\n", __func__, vocab.special_eot_id, vocab.id_to_token[vocab.special_eot_id].text.c_str() ); }
  6444. if (vocab.special_eom_id != -1) { LLAMA_LOG_INFO( "%s: EOM token = %d '%s'\n", __func__, vocab.special_eom_id, vocab.id_to_token[vocab.special_eom_id].text.c_str() ); }
  6445. 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() ); }
  6446. 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() ); }
  6447. 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() ); }
  6448. if (vocab.special_cls_id != -1) { LLAMA_LOG_INFO( "%s: CLS token = %d '%s'\n", __func__, vocab.special_cls_id, vocab.id_to_token[vocab.special_cls_id].text.c_str() ); }
  6449. if (vocab.special_mask_id != -1) { LLAMA_LOG_INFO( "%s: MASK token = %d '%s'\n", __func__, vocab.special_mask_id, vocab.id_to_token[vocab.special_mask_id].text.c_str() ); }
  6450. 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() ); }
  6451. if (vocab.special_fim_pre_id != -1) { LLAMA_LOG_INFO( "%s: FIM PRE token = %d '%s'\n", __func__, vocab.special_fim_pre_id, vocab.id_to_token[vocab.special_fim_pre_id].text.c_str() ); }
  6452. if (vocab.special_fim_suf_id != -1) { LLAMA_LOG_INFO( "%s: FIM SUF token = %d '%s'\n", __func__, vocab.special_fim_suf_id, vocab.id_to_token[vocab.special_fim_suf_id].text.c_str() ); }
  6453. if (vocab.special_fim_mid_id != -1) { LLAMA_LOG_INFO( "%s: FIM MID token = %d '%s'\n", __func__, vocab.special_fim_mid_id, vocab.id_to_token[vocab.special_fim_mid_id].text.c_str() ); }
  6454. if (vocab.special_fim_pad_id != -1) { LLAMA_LOG_INFO( "%s: FIM PAD token = %d '%s'\n", __func__, vocab.special_fim_pad_id, vocab.id_to_token[vocab.special_fim_pad_id].text.c_str() ); }
  6455. if (vocab.special_fim_rep_id != -1) { LLAMA_LOG_INFO( "%s: FIM REP token = %d '%s'\n", __func__, vocab.special_fim_rep_id, vocab.id_to_token[vocab.special_fim_rep_id].text.c_str() ); }
  6456. if (vocab.special_fim_sep_id != -1) { LLAMA_LOG_INFO( "%s: FIM SEP token = %d '%s'\n", __func__, vocab.special_fim_sep_id, vocab.id_to_token[vocab.special_fim_sep_id].text.c_str() ); }
  6457. for (const auto & id : vocab.special_eog_ids) {
  6458. LLAMA_LOG_INFO( "%s: EOG token = %d '%s'\n", __func__, id, vocab.id_to_token[id].text.c_str() );
  6459. }
  6460. LLAMA_LOG_INFO("%s: max token length = %d\n", __func__, vocab.max_token_len);
  6461. if (model.arch == LLM_ARCH_DEEPSEEK2) {
  6462. LLAMA_LOG_INFO("%s: n_layer_dense_lead = %d\n", __func__, hparams.n_layer_dense_lead);
  6463. LLAMA_LOG_INFO("%s: n_lora_q = %d\n", __func__, hparams.n_lora_q);
  6464. LLAMA_LOG_INFO("%s: n_lora_kv = %d\n", __func__, hparams.n_lora_kv);
  6465. LLAMA_LOG_INFO("%s: n_ff_exp = %d\n", __func__, hparams.n_ff_exp);
  6466. LLAMA_LOG_INFO("%s: n_expert_shared = %d\n", __func__, hparams.n_expert_shared);
  6467. LLAMA_LOG_INFO("%s: expert_weights_scale = %.1f\n", __func__, hparams.expert_weights_scale);
  6468. LLAMA_LOG_INFO("%s: rope_yarn_log_mul = %.4f\n", __func__, hparams.rope_yarn_log_mul);
  6469. }
  6470. if (model.arch == LLM_ARCH_QWEN2MOE) {
  6471. LLAMA_LOG_INFO("%s: n_ff_exp = %d\n", __func__, hparams.n_ff_exp);
  6472. LLAMA_LOG_INFO("%s: n_ff_shexp = %d\n", __func__, hparams.n_ff_shexp);
  6473. }
  6474. if (model.arch == LLM_ARCH_GRANITE || model.arch == LLM_ARCH_GRANITE_MOE) {
  6475. LLAMA_LOG_INFO("%s: f_embedding_scale = %f\n", __func__, hparams.f_embedding_scale);
  6476. LLAMA_LOG_INFO("%s: f_residual_scale = %f\n", __func__, hparams.f_residual_scale);
  6477. LLAMA_LOG_INFO("%s: f_attention_scale = %f\n", __func__, hparams.f_attention_scale);
  6478. }
  6479. }
  6480. enum llm_tensor_layer {
  6481. LLM_TENSOR_LAYER_INPUT,
  6482. LLM_TENSOR_LAYER_REPEATING,
  6483. LLM_TENSOR_LAYER_OUTPUT,
  6484. };
  6485. struct llm_tensor_info {
  6486. llm_tensor_layer layer;
  6487. ggml_op op;
  6488. };
  6489. static const std::map<llm_tensor, llm_tensor_info> llm_tensor_info_mapping = {
  6490. {LLM_TENSOR_TOKEN_EMBD, {LLM_TENSOR_LAYER_INPUT, GGML_OP_GET_ROWS}},
  6491. {LLM_TENSOR_POS_EMBD, {LLM_TENSOR_LAYER_INPUT, GGML_OP_GET_ROWS}},
  6492. {LLM_TENSOR_TOKEN_EMBD_NORM, {LLM_TENSOR_LAYER_INPUT, GGML_OP_GET_ROWS}},
  6493. {LLM_TENSOR_TOKEN_TYPES, {LLM_TENSOR_LAYER_INPUT, GGML_OP_GET_ROWS}},
  6494. {LLM_TENSOR_OUTPUT, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}},
  6495. {LLM_TENSOR_CLS, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}},
  6496. {LLM_TENSOR_CLS_OUT, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}},
  6497. {LLM_TENSOR_OUTPUT_NORM, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL}},
  6498. {LLM_TENSOR_DEC_OUTPUT_NORM, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL}},
  6499. {LLM_TENSOR_ENC_OUTPUT_NORM, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL}},
  6500. {LLM_TENSOR_ROPE_FREQS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ROPE}},
  6501. {LLM_TENSOR_ROPE_FACTORS_LONG, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ROPE}},
  6502. {LLM_TENSOR_ROPE_FACTORS_SHORT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ROPE}},
  6503. {LLM_TENSOR_ATTN_Q, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6504. {LLM_TENSOR_ATTN_K, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6505. {LLM_TENSOR_ATTN_V, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6506. {LLM_TENSOR_ATTN_QKV, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6507. {LLM_TENSOR_ATTN_OUT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6508. {LLM_TENSOR_FFN_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6509. {LLM_TENSOR_FFN_DOWN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6510. {LLM_TENSOR_FFN_UP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6511. {LLM_TENSOR_FFN_DOWN_SHEXP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6512. {LLM_TENSOR_FFN_GATE_SHEXP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6513. {LLM_TENSOR_FFN_UP_SHEXP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6514. {LLM_TENSOR_ATTN_Q_A, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6515. {LLM_TENSOR_ATTN_Q_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6516. {LLM_TENSOR_ATTN_KV_A_MQA, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6517. {LLM_TENSOR_ATTN_KV_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6518. {LLM_TENSOR_DEC_ATTN_Q, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6519. {LLM_TENSOR_DEC_ATTN_K, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6520. {LLM_TENSOR_ATTN_Q, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6521. {LLM_TENSOR_ATTN_K, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6522. {LLM_TENSOR_ATTN_V, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6523. {LLM_TENSOR_ATTN_QKV, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6524. {LLM_TENSOR_ATTN_OUT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6525. {LLM_TENSOR_FFN_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6526. {LLM_TENSOR_FFN_DOWN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6527. {LLM_TENSOR_FFN_UP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6528. {LLM_TENSOR_FFN_DOWN_SHEXP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6529. {LLM_TENSOR_FFN_GATE_SHEXP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6530. {LLM_TENSOR_FFN_UP_SHEXP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6531. {LLM_TENSOR_ATTN_Q_A, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6532. {LLM_TENSOR_ATTN_Q_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6533. {LLM_TENSOR_ATTN_KV_A_MQA, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6534. {LLM_TENSOR_ATTN_KV_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6535. {LLM_TENSOR_DEC_ATTN_Q, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6536. {LLM_TENSOR_DEC_ATTN_K, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6537. {LLM_TENSOR_DEC_ATTN_V, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6538. {LLM_TENSOR_DEC_ATTN_OUT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6539. {LLM_TENSOR_DEC_CROSS_ATTN_Q, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6540. {LLM_TENSOR_DEC_CROSS_ATTN_K, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6541. {LLM_TENSOR_DEC_CROSS_ATTN_V, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6542. {LLM_TENSOR_DEC_CROSS_ATTN_OUT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6543. {LLM_TENSOR_DEC_FFN_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6544. {LLM_TENSOR_DEC_FFN_DOWN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6545. {LLM_TENSOR_DEC_FFN_UP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6546. {LLM_TENSOR_ENC_ATTN_Q, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6547. {LLM_TENSOR_ENC_ATTN_K, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6548. {LLM_TENSOR_ENC_ATTN_V, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6549. {LLM_TENSOR_ENC_ATTN_OUT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6550. {LLM_TENSOR_ENC_FFN_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6551. {LLM_TENSOR_ENC_FFN_DOWN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6552. {LLM_TENSOR_ENC_FFN_UP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6553. {LLM_TENSOR_FFN_GATE_INP_SHEXP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6554. {LLM_TENSOR_FFN_GATE_INP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6555. {LLM_TENSOR_SSM_IN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6556. {LLM_TENSOR_SSM_X, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6557. {LLM_TENSOR_SSM_DT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6558. {LLM_TENSOR_SSM_OUT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6559. {LLM_TENSOR_TIME_MIX_W1, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6560. {LLM_TENSOR_TIME_MIX_W2, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6561. {LLM_TENSOR_TIME_MIX_DECAY_W1, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6562. {LLM_TENSOR_TIME_MIX_DECAY_W2, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6563. {LLM_TENSOR_TIME_MIX_KEY, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6564. {LLM_TENSOR_TIME_MIX_VALUE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6565. {LLM_TENSOR_TIME_MIX_RECEPTANCE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6566. {LLM_TENSOR_TIME_MIX_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6567. {LLM_TENSOR_TIME_MIX_OUTPUT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6568. {LLM_TENSOR_CHANNEL_MIX_KEY, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6569. {LLM_TENSOR_CHANNEL_MIX_RECEPTANCE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6570. {LLM_TENSOR_CHANNEL_MIX_VALUE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6571. {LLM_TENSOR_FFN_ACT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_DIV}},
  6572. {LLM_TENSOR_SSM_CONV1D, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_SSM_CONV}},
  6573. {LLM_TENSOR_SSM_A, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_SSM_SCAN}},
  6574. {LLM_TENSOR_SSM_D, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6575. {LLM_TENSOR_TIME_MIX_LERP_X, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6576. {LLM_TENSOR_TIME_MIX_LN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6577. {LLM_TENSOR_CHANNEL_MIX_LERP_K, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6578. {LLM_TENSOR_CHANNEL_MIX_LERP_R, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6579. {LLM_TENSOR_TIME_MIX_LERP_W, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}},
  6580. {LLM_TENSOR_TIME_MIX_LERP_K, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}},
  6581. {LLM_TENSOR_TIME_MIX_LERP_V, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}},
  6582. {LLM_TENSOR_TIME_MIX_LERP_R, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}},
  6583. {LLM_TENSOR_TIME_MIX_LERP_G, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}},
  6584. {LLM_TENSOR_TIME_MIX_DECAY, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}},
  6585. {LLM_TENSOR_TIME_MIX_FIRST, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_RWKV_WKV6}},
  6586. {LLM_TENSOR_ATTN_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6587. {LLM_TENSOR_ATTN_NORM_2, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6588. {LLM_TENSOR_ATTN_OUT_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6589. {LLM_TENSOR_ATTN_POST_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6590. {LLM_TENSOR_FFN_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6591. {LLM_TENSOR_FFN_POST_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6592. {LLM_TENSOR_FFN_NORM_EXPS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6593. {LLM_TENSOR_ATTN_Q_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6594. {LLM_TENSOR_ATTN_K_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6595. {LLM_TENSOR_LAYER_OUT_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6596. {LLM_TENSOR_ATTN_Q_A_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6597. {LLM_TENSOR_ATTN_KV_A_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6598. {LLM_TENSOR_ATTN_SUB_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6599. {LLM_TENSOR_FFN_SUB_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6600. {LLM_TENSOR_DEC_ATTN_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6601. {LLM_TENSOR_DEC_CROSS_ATTN_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6602. {LLM_TENSOR_DEC_FFN_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6603. {LLM_TENSOR_ENC_ATTN_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6604. {LLM_TENSOR_ENC_FFN_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6605. {LLM_TENSOR_DEC_ATTN_REL_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_GET_ROWS}},
  6606. {LLM_TENSOR_ENC_ATTN_REL_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_GET_ROWS}},
  6607. {LLM_TENSOR_FFN_DOWN_EXPS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT_ID}},
  6608. {LLM_TENSOR_FFN_GATE_EXPS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT_ID}},
  6609. {LLM_TENSOR_FFN_UP_EXPS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT_ID}},
  6610. // this tensor is loaded for T5, but never used
  6611. {LLM_TENSOR_DEC_CROSS_ATTN_REL_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_NONE}},
  6612. {LLM_TENSOR_BSKCN_TV, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6613. {LLM_TENSOR_CROSS_ATTN_K_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6614. {LLM_TENSOR_CROSS_ATTN_K_PROJ, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6615. {LLM_TENSOR_CROSS_ATTN_O_PROJ, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6616. {LLM_TENSOR_CROSS_ATTN_Q_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6617. {LLM_TENSOR_CROSS_ATTN_Q_PROJ, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6618. {LLM_TENSOR_CROSS_ATTN_V_PROJ, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6619. {LLM_TENSOR_CROSS_ATTN_ATTN_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6620. {LLM_TENSOR_CROSS_ATTN_MLP_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6621. };
  6622. // checks if the weight tensor can be used with the specified buffer type and device
  6623. static bool weight_buft_supported(const llama_hparams & hparams, ggml_tensor * w, ggml_op op, ggml_backend_buffer_type_t buft, ggml_backend_dev_t dev) {
  6624. GGML_ASSERT(w != nullptr);
  6625. if (op == GGML_OP_NONE) {
  6626. return true;
  6627. }
  6628. ggml_init_params params = {
  6629. /*.mem_size =*/ ggml_tensor_overhead()*8,
  6630. /*.mem_buffer =*/ NULL,
  6631. /*.no_alloc =*/ true,
  6632. };
  6633. ggml_context_ptr ctx_ptr { ggml_init(params) };
  6634. if (!ctx_ptr) {
  6635. throw std::runtime_error(format("failed to create ggml context"));
  6636. }
  6637. ggml_context * ctx = ctx_ptr.get();
  6638. ggml_tensor * op_tensor = nullptr;
  6639. switch (op) {
  6640. case GGML_OP_GET_ROWS:
  6641. {
  6642. ggml_tensor * b = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 512);
  6643. op_tensor = ggml_get_rows(ctx, w, b);
  6644. } break;
  6645. case GGML_OP_MUL_MAT:
  6646. {
  6647. ggml_tensor * b = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, w->ne[0], 512, w->ne[2], w->ne[3]);
  6648. op_tensor = ggml_mul_mat(ctx, w, b);
  6649. } break;
  6650. case GGML_OP_MUL_MAT_ID:
  6651. {
  6652. int n_expert_used = hparams.n_expert_used;
  6653. ggml_tensor * b = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, w->ne[0], n_expert_used, 512);
  6654. ggml_tensor * ids = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, n_expert_used, 512);
  6655. op_tensor = ggml_mul_mat_id(ctx, w, b, ids);
  6656. } break;
  6657. case GGML_OP_ADD:
  6658. {
  6659. ggml_tensor * a = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, w->ne[0], w->ne[1], w->ne[2], w->ne[3]);
  6660. op_tensor = ggml_add(ctx, a, w);
  6661. } break;
  6662. case GGML_OP_MUL:
  6663. {
  6664. ggml_tensor * a = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, w->ne[0], w->ne[1], w->ne[2], w->ne[3]);
  6665. op_tensor = ggml_mul(ctx, a, w);
  6666. } break;
  6667. case GGML_OP_DIV:
  6668. {
  6669. ggml_tensor * a = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, w->ne[0]);
  6670. op_tensor = ggml_div(ctx, a, w);
  6671. } break;
  6672. case GGML_OP_ROPE:
  6673. {
  6674. int n_embd_head = hparams.n_embd_head_v;
  6675. int n_head = hparams.n_head();
  6676. ggml_tensor * a = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n_embd_head, n_head, 512);
  6677. ggml_tensor * b = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 512);
  6678. op_tensor = ggml_rope_ext(
  6679. ctx, a, b, w,
  6680. 0, 0, 0, 0, 0,
  6681. 0, 0, 0, 0
  6682. );
  6683. } break;
  6684. case GGML_OP_SSM_CONV:
  6685. {
  6686. // FIXME
  6687. ggml_tensor * conv_x = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, 12345, w->ne[1], 6789);
  6688. op_tensor = ggml_ssm_conv(ctx, conv_x, w);
  6689. } break;
  6690. case GGML_OP_SSM_SCAN:
  6691. {
  6692. // FIXME
  6693. const int64_t d_state = w->ne[0];
  6694. const int64_t d_inner = w->ne[1];
  6695. const int64_t n_seq_tokens = 512;
  6696. const int64_t n_seqs = 1;
  6697. ggml_tensor * s = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, d_state, d_inner, n_seqs);
  6698. ggml_tensor * x = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, d_inner, n_seq_tokens, n_seqs);
  6699. ggml_tensor * dt = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, d_inner, n_seq_tokens, n_seqs);
  6700. ggml_tensor * B = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, d_state, n_seq_tokens, n_seqs);
  6701. ggml_tensor * C = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, d_state, n_seq_tokens, n_seqs);
  6702. op_tensor = ggml_ssm_scan(ctx, s, x, dt, w, B, C);
  6703. } break;
  6704. case GGML_OP_RWKV_WKV6:
  6705. {
  6706. // FIXME
  6707. const int64_t S = 123;
  6708. const int64_t H = 123;
  6709. const int64_t n_tokens = 123;
  6710. const int64_t n_seqs = 123;
  6711. ggml_tensor * k = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, 1, H, n_tokens);
  6712. ggml_tensor * v = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 1, S, H, n_tokens);
  6713. ggml_tensor * r = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 1, S, H, n_tokens);
  6714. ggml_tensor * tf = w;
  6715. ggml_tensor * td = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 1, S, H, n_tokens);
  6716. ggml_tensor * state = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, n_seqs, S, H);
  6717. op_tensor = ggml_rwkv_wkv6(ctx, k, v, r, tf, td, state);
  6718. } break;
  6719. default:
  6720. GGML_ABORT("%s: missing test for op %s for tensor %s", __func__, ggml_op_name(op), w->name);
  6721. }
  6722. // create a temporary dummy buffer for the weight so that supports_op can check the buffer type
  6723. GGML_ASSERT(w->buffer == nullptr);
  6724. w->buffer = ggml_backend_buft_alloc_buffer(buft, 0);
  6725. bool op_supported = ggml_backend_dev_supports_op(dev, op_tensor);
  6726. ggml_backend_buffer_free(w->buffer);
  6727. w->buffer = nullptr;
  6728. return op_supported;
  6729. }
  6730. // find the first buffer type in the list that can use the tensor
  6731. static ggml_backend_buffer_type_t select_weight_buft(const llama_model & model, ggml_tensor * tensor, ggml_op op, const llama_model::buft_list_t & buft_list) {
  6732. GGML_ASSERT(!buft_list.empty());
  6733. for (const auto & cur : buft_list) {
  6734. ggml_backend_dev_t cur_dev = cur.first;
  6735. ggml_backend_buffer_type_t cur_buft = cur.second;
  6736. if (weight_buft_supported(model.hparams, tensor, op, cur_buft, cur_dev)) {
  6737. return cur_buft;
  6738. }
  6739. }
  6740. return nullptr;
  6741. }
  6742. // CPU: ACCEL -> CPU extra -> GPU host -> CPU
  6743. static llama_model::buft_list_t make_cpu_buft_list(llama_model & model) {
  6744. llama_model::buft_list_t buft_list;
  6745. // add ACCEL buffer types
  6746. for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
  6747. ggml_backend_dev_t dev = ggml_backend_dev_get(i);
  6748. if (ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_ACCEL) {
  6749. auto * buft = ggml_backend_dev_buffer_type(dev);
  6750. // skip
  6751. if (buft != ggml_backend_cpu_buffer_type()) {
  6752. buft_list.emplace_back(dev, buft);
  6753. }
  6754. }
  6755. }
  6756. // add extra buffer types
  6757. auto * cpu_dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
  6758. auto * cpu_reg = ggml_backend_dev_backend_reg(cpu_dev);
  6759. auto ggml_backend_dev_get_extra_bufts_fn = (ggml_backend_dev_get_extra_bufts_t)
  6760. ggml_backend_reg_get_proc_address(cpu_reg, "ggml_backend_dev_get_extra_bufts");
  6761. if (ggml_backend_dev_get_extra_bufts_fn) {
  6762. ggml_backend_buffer_type_t * extra_bufts = ggml_backend_dev_get_extra_bufts_fn(cpu_dev);
  6763. while (extra_bufts && *extra_bufts) {
  6764. buft_list.emplace_back(cpu_dev, *extra_bufts);
  6765. ++extra_bufts;
  6766. }
  6767. }
  6768. // add a host buffer type
  6769. // storing the tensors in a host buffer is useful when the processing of large batches
  6770. // is offloaded to a GPU device, since it reduces the time spent on data transfers
  6771. // generally, this will be done using the first device in the list
  6772. // a better approach would be to handle this on a weight-by-weight basis using the offload_op
  6773. // function of the device to determine if it would benefit from being stored in a host buffer
  6774. for (auto * dev : model.devices) {
  6775. ggml_backend_buffer_type_t buft = ggml_backend_dev_host_buffer_type(dev);
  6776. if (buft) {
  6777. buft_list.emplace_back(dev, buft);
  6778. break;
  6779. }
  6780. }
  6781. // add the CPU buffer type
  6782. for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
  6783. ggml_backend_dev_t dev = ggml_backend_dev_get(i);
  6784. if (ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_CPU) {
  6785. buft_list.emplace_back(dev, ggml_backend_dev_buffer_type(dev));
  6786. }
  6787. }
  6788. return buft_list;
  6789. }
  6790. // GPU: split if LLAMA_SPLIT_MODE_ROW -> GPU
  6791. static llama_model::buft_list_t make_gpu_buft_list(ggml_backend_dev_t dev, enum llama_split_mode split_mode, const float * tensor_split) {
  6792. llama_model::buft_list_t buft_list;
  6793. // add the device split buffer type if requested and available
  6794. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  6795. ggml_backend_reg_t reg = ggml_backend_dev_backend_reg(dev);
  6796. auto ggml_backend_split_buffer_type_fn = (ggml_backend_split_buffer_type_t)
  6797. ggml_backend_reg_get_proc_address(reg, "ggml_backend_split_buffer_type");
  6798. if (ggml_backend_split_buffer_type_fn) {
  6799. size_t dev_index = [&]() {
  6800. auto * reg = ggml_backend_dev_backend_reg(dev);
  6801. for (size_t i = 0; i < ggml_backend_reg_dev_count(reg); ++i) {
  6802. if (ggml_backend_reg_dev_get(reg, i) == dev) {
  6803. return i;
  6804. }
  6805. }
  6806. throw std::runtime_error(format("device %s not found in its backend reg", ggml_backend_dev_name(dev)));
  6807. }();
  6808. auto * buft = ggml_backend_split_buffer_type_fn(dev_index, tensor_split);
  6809. if (buft != nullptr) {
  6810. buft_list.emplace_back(dev, buft);
  6811. }
  6812. }
  6813. }
  6814. // add the device default buffer type
  6815. buft_list.emplace_back(dev, ggml_backend_dev_buffer_type(dev));
  6816. return buft_list;
  6817. }
  6818. // Returns false if cancelled by progress_callback
  6819. static bool llm_load_tensors(
  6820. llama_model_loader & ml,
  6821. llama_model & model,
  6822. int n_gpu_layers,
  6823. enum llama_split_mode split_mode,
  6824. int main_gpu,
  6825. const float * tensor_split,
  6826. bool use_mlock,
  6827. llama_progress_callback progress_callback,
  6828. void * progress_callback_user_data) {
  6829. auto & hparams = model.hparams;
  6830. model.split_mode = split_mode;
  6831. model.main_gpu = main_gpu;
  6832. model.n_gpu_layers = n_gpu_layers;
  6833. const int n_layer = hparams.n_layer;
  6834. bool use_mmap_buffer = true;
  6835. // build a list of buffer types for the CPU and GPU devices
  6836. model.cpu_buft_list = make_cpu_buft_list(model);
  6837. for (auto * dev : model.devices) {
  6838. llama_model::buft_list_t buft_list = make_gpu_buft_list(dev, split_mode, tensor_split);
  6839. // add CPU buffer types as a fallback
  6840. buft_list.insert(buft_list.end(), model.cpu_buft_list.begin(), model.cpu_buft_list.end());
  6841. model.gpu_buft_list.emplace(dev, std::move(buft_list));
  6842. }
  6843. // calculate the split points
  6844. int device_count = llama_get_device_count(model);
  6845. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  6846. std::vector<float> splits(device_count);
  6847. if (all_zero) {
  6848. // default split, by free memory
  6849. for (int i = 0; i < device_count; ++i) {
  6850. ggml_backend_dev_t dev = model.devices[i];
  6851. size_t total;
  6852. size_t free;
  6853. ggml_backend_dev_memory(dev, &free, &total);
  6854. splits[i] = free;
  6855. }
  6856. } else {
  6857. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  6858. }
  6859. // sum and normalize the splits to get the split points
  6860. float split_sum = 0.0f;
  6861. for (int i = 0; i < device_count; ++i) {
  6862. split_sum += splits[i];
  6863. splits[i] = split_sum;
  6864. }
  6865. for (int i = 0; i < device_count; ++i) {
  6866. splits[i] /= split_sum;
  6867. }
  6868. ggml_backend_dev_t cpu_dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
  6869. const int i_gpu_start = std::max((int) hparams.n_layer - n_gpu_layers, (int) 0);
  6870. const int act_gpu_layers = model.devices.empty() ? 0 : std::min(n_gpu_layers, (int)n_layer + 1);
  6871. auto get_layer_buft_list = [&](int il) -> llama_model::layer_dev {
  6872. if (il < i_gpu_start || (il - i_gpu_start) >= act_gpu_layers) {
  6873. return {cpu_dev, &model.cpu_buft_list};
  6874. }
  6875. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(il - i_gpu_start)/act_gpu_layers) - splits.begin();
  6876. auto * dev = model.devices.at(layer_gpu);
  6877. return {dev, &model.gpu_buft_list.at(dev)};
  6878. };
  6879. // assign the input layer
  6880. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  6881. model.dev_input = { cpu_dev, &model.cpu_buft_list };
  6882. // assign the repeating layers to the devices according to the splits
  6883. model.dev_layer.resize(n_layer);
  6884. for (int il = 0; il < n_layer; ++il) {
  6885. model.dev_layer[il] = get_layer_buft_list(il);
  6886. }
  6887. // assign the output layer
  6888. model.dev_output = get_layer_buft_list(n_layer);
  6889. // one ggml context per buffer type
  6890. int max_n_tensors = ml.n_tensors;
  6891. max_n_tensors += 1; // duplicated output tensor
  6892. max_n_tensors += n_layer*2; // duplicated rope freq tensors
  6893. const size_t ctx_size = ggml_tensor_overhead()*max_n_tensors;
  6894. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  6895. auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
  6896. auto it = ctx_map.find(buft);
  6897. if (it == ctx_map.end()) {
  6898. ggml_init_params params = {
  6899. /*.mem_size =*/ ctx_size,
  6900. /*.mem_buffer =*/ NULL,
  6901. /*.no_alloc =*/ true,
  6902. };
  6903. ggml_context * ctx = ggml_init(params);
  6904. if (!ctx) {
  6905. throw std::runtime_error(format("failed to create ggml context"));
  6906. }
  6907. ctx_map[buft] = ctx;
  6908. model.ctxs.emplace_back(ctx);
  6909. return ctx;
  6910. }
  6911. return it->second;
  6912. };
  6913. // create tensors for the weights
  6914. {
  6915. // note: cast to int64_t since we will use these for the tensor dimensions
  6916. const int64_t n_head = hparams.n_head();
  6917. const int64_t n_head_kv = hparams.n_head_kv();
  6918. const int64_t n_embd = hparams.n_embd;
  6919. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  6920. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  6921. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  6922. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  6923. const int64_t n_ff = hparams.n_ff();
  6924. const int64_t n_embd_gqa = n_embd_v_gqa;
  6925. const int64_t n_vocab = hparams.n_vocab;
  6926. const int64_t n_vocab_type = hparams.n_vocab_type;
  6927. const int64_t n_rot = hparams.n_rot;
  6928. const int64_t n_expert = hparams.n_expert;
  6929. const int64_t n_expert_used = hparams.n_expert_used;
  6930. const int64_t n_ctx_train = hparams.n_ctx_train;
  6931. if (n_expert > 0 && hparams.n_expert_used == 0) {
  6932. throw std::runtime_error("model has expert layers but no expert layers are used");
  6933. }
  6934. int n_moved_tensors = 0;
  6935. ggml_tensor * first_moved_tensor = nullptr;
  6936. ggml_backend_buffer_type_t first_moved_from_buft = nullptr;
  6937. ggml_backend_buffer_type_t first_moved_to_buft = nullptr;
  6938. auto create_tensor = [&](const LLM_TN_IMPL & tn, const std::initializer_list<int64_t> & ne, int flags) -> ggml_tensor * {
  6939. ggml_tensor * t_meta = ml.get_tensor_meta(tn.str().c_str());
  6940. if (!t_meta) {
  6941. if (flags & llama_model_loader::TENSOR_NOT_REQUIRED) {
  6942. return nullptr;
  6943. }
  6944. throw std::runtime_error(format("missing tensor '%s'", tn.str().c_str()));
  6945. }
  6946. // some models use the token embedding tensor as the output, but since these are used in different layers and with different ops
  6947. // the tensor is duplicated
  6948. // to handle this, we check if the tensor is duplicated, and if so, we assume that it is being loaded as the output tensor
  6949. llm_tensor tn_tensor = tn.tensor;
  6950. if (tn.tensor == LLM_TENSOR_TOKEN_EMBD && flags & llama_model_loader::TENSOR_DUPLICATED) {
  6951. tn_tensor = LLM_TENSOR_OUTPUT;
  6952. }
  6953. auto it = llm_tensor_info_mapping.find(tn_tensor);
  6954. if (it == llm_tensor_info_mapping.end()) {
  6955. throw std::runtime_error(format("missing tensor info mapping for %s", tn.str().c_str()));
  6956. }
  6957. const auto & info = it->second;
  6958. // tensors with "bias" suffix are always used with GGML_OP_ADD
  6959. ggml_op op;
  6960. bool bias = tn.suffix != nullptr && strcmp(tn.suffix, "bias") == 0;
  6961. if (bias) {
  6962. op = GGML_OP_ADD;
  6963. } else {
  6964. op = info.op;
  6965. }
  6966. // sanity checks
  6967. if (info.layer == LLM_TENSOR_LAYER_INPUT || info.layer == LLM_TENSOR_LAYER_OUTPUT) {
  6968. if (tn.bid != -1) {
  6969. GGML_ABORT("input/output layer tensor %s used with a layer number", tn.str().c_str());
  6970. }
  6971. } else {
  6972. if (tn.bid == -1) {
  6973. GGML_ABORT("repeating layer tensor %s used without a layer number", tn.str().c_str());
  6974. }
  6975. }
  6976. // select the buffer type for this tensor
  6977. llama_model::buft_list_t * buft_list;
  6978. switch (info.layer) {
  6979. case LLM_TENSOR_LAYER_INPUT:
  6980. buft_list = model.dev_input.buft_list;
  6981. break;
  6982. case LLM_TENSOR_LAYER_OUTPUT:
  6983. buft_list = model.dev_output.buft_list;
  6984. break;
  6985. case LLM_TENSOR_LAYER_REPEATING:
  6986. buft_list = model.dev_layer.at(tn.bid).buft_list;
  6987. break;
  6988. default:
  6989. GGML_ABORT("invalid layer %d for tensor %s", info.layer, tn.str().c_str());
  6990. }
  6991. ggml_backend_buffer_type_t buft = select_weight_buft(model, t_meta, op, *buft_list);
  6992. if (!buft) {
  6993. throw std::runtime_error(format("failed to find a compatible buffer type for tensor %s", tn.str().c_str()));
  6994. }
  6995. // avoid using a host buffer when using mmap
  6996. auto * buft_dev = ggml_backend_buft_get_device(buft);
  6997. if (ml.use_mmap && buft_dev && buft == ggml_backend_dev_host_buffer_type(buft_dev)) {
  6998. auto * cpu_dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
  6999. buft = ggml_backend_dev_buffer_type(cpu_dev);
  7000. }
  7001. if (buft != buft_list->front().second) {
  7002. n_moved_tensors++;
  7003. if (!first_moved_tensor) {
  7004. first_moved_tensor = t_meta;
  7005. first_moved_from_buft = buft_list->front().second;
  7006. first_moved_to_buft = buft;
  7007. }
  7008. }
  7009. ggml_context * ctx = ctx_for_buft(buft);
  7010. // if duplicated, check if the original tensor was allocated in the same buffer type context and avoid creating a new one
  7011. if (flags & llama_model_loader::TENSOR_DUPLICATED) {
  7012. ggml_tensor * t = ggml_get_tensor(ctx, tn.str().c_str());
  7013. if (t) {
  7014. return t;
  7015. }
  7016. }
  7017. return ml.create_tensor(ctx, tn, ne, flags);
  7018. };
  7019. model.layers.resize(n_layer);
  7020. // TODO: move to a separate function
  7021. const auto tn = LLM_TN(model.arch);
  7022. switch (model.arch) {
  7023. case LLM_ARCH_LLAMA:
  7024. case LLM_ARCH_REFACT:
  7025. case LLM_ARCH_MINICPM:
  7026. case LLM_ARCH_GRANITE:
  7027. case LLM_ARCH_GRANITE_MOE:
  7028. {
  7029. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7030. // output
  7031. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7032. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7033. // if output is NULL, init from the input tok embed
  7034. if (model.output == NULL) {
  7035. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7036. }
  7037. for (int i = 0; i < n_layer; ++i) {
  7038. auto & layer = model.layers[i];
  7039. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7040. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head}, 0);
  7041. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  7042. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  7043. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd}, 0);
  7044. // optional bias tensors
  7045. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7046. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7047. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7048. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7049. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7050. layer.rope_freqs = create_tensor(tn(LLM_TENSOR_ROPE_FREQS, "weight", i), {n_rot/2}, llama_model_loader::TENSOR_NOT_REQUIRED | (i != 0 ? llama_model_loader::TENSOR_DUPLICATED : 0));
  7051. if (n_expert == 0) {
  7052. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7053. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7054. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7055. // optional MLP bias
  7056. layer.ffn_gate_b = create_tensor(tn(LLM_TENSOR_FFN_GATE, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7057. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7058. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7059. } else {
  7060. layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0);
  7061. layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7062. layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert}, 0);
  7063. layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert}, 0);
  7064. }
  7065. }
  7066. } break;
  7067. case LLM_ARCH_MLLAMA:
  7068. {
  7069. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab+8}, 0);
  7070. // output
  7071. {
  7072. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7073. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7074. // if output is NULL, init from the input tok embed
  7075. if (model.output == NULL) {
  7076. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7077. }
  7078. }
  7079. for (int i = 0; i < n_layer; ++i) {
  7080. auto & layer = model.layers[i];
  7081. if (hparams.cross_attention_layers(i)) {
  7082. layer.cross_attn_k_norm = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_K_NORM, "weight", i), {128}, 0);
  7083. layer.cross_attn_k_proj = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_K_PROJ, "weight", i), {n_embd, 1024}, 0);
  7084. layer.cross_attn_o_proj = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_O_PROJ, "weight", i), {n_embd, n_embd}, 0);
  7085. layer.cross_attn_q_norm = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_Q_NORM, "weight", i), {128}, 0);
  7086. layer.cross_attn_q_proj = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_Q_PROJ, "weight", i), {n_embd, n_embd}, 0);
  7087. layer.cross_attn_v_proj = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_V_PROJ, "weight", i), {n_embd, 1024}, 0);
  7088. layer.cross_attn_attn_gate = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_ATTN_GATE, i), {1}, 0);
  7089. layer.cross_attn_mlp_gate = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_MLP_GATE, i), {1}, 0);
  7090. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7091. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7092. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7093. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7094. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7095. } else {
  7096. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7097. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head}, 0);
  7098. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  7099. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  7100. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd}, 0);
  7101. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7102. layer.rope_freqs = create_tensor(tn(LLM_TENSOR_ROPE_FREQS, "weight", i), {n_rot/2}, llama_model_loader::TENSOR_NOT_REQUIRED | (i != 0 ? llama_model_loader::TENSOR_DUPLICATED : 0));
  7103. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7104. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7105. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7106. }
  7107. }
  7108. } break;
  7109. case LLM_ARCH_MINICPM3:
  7110. {
  7111. const int64_t n_embd_head_qk_rope = hparams.n_rot;
  7112. const int64_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  7113. const int64_t q_lora_rank = hparams.n_lora_q;
  7114. const int64_t kv_lora_rank = hparams.n_lora_kv;
  7115. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7116. // output
  7117. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7118. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7119. // if output is NULL, init from the input tok embed
  7120. if (model.output == NULL) {
  7121. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7122. }
  7123. for (int i = 0; i < n_layer; ++i) {
  7124. auto & layer = model.layers[i];
  7125. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7126. layer.attn_q_a_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_A_NORM, "weight", i), {q_lora_rank}, 0);
  7127. layer.attn_kv_a_norm = create_tensor(tn(LLM_TENSOR_ATTN_KV_A_NORM, "weight", i), {kv_lora_rank}, 0);
  7128. layer.wq_a = create_tensor(tn(LLM_TENSOR_ATTN_Q_A, "weight", i), {n_embd, q_lora_rank}, 0);
  7129. layer.wq_b = create_tensor(tn(LLM_TENSOR_ATTN_Q_B, "weight", i), {q_lora_rank, n_head * n_embd_head_k}, 0);
  7130. layer.wkv_a_mqa = create_tensor(tn(LLM_TENSOR_ATTN_KV_A_MQA, "weight", i), {n_embd, kv_lora_rank + (n_embd_head_qk_rope)}, 0);
  7131. layer.wkv_b = create_tensor(tn(LLM_TENSOR_ATTN_KV_B, "weight", i), {kv_lora_rank, n_head * (n_embd_head_qk_nope + n_embd_head_v)}, 0);
  7132. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_head * ( n_embd_head_v), n_embd}, 0);
  7133. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7134. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7135. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7136. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7137. layer.rope_long = create_tensor(tn(LLM_TENSOR_ROPE_FACTORS_LONG, "weight", i), { n_embd_head_qk_rope/2 }, llama_model_loader::TENSOR_NOT_REQUIRED | (i != 0 ? llama_model_loader::TENSOR_DUPLICATED : 0));
  7138. layer.rope_short = create_tensor(tn(LLM_TENSOR_ROPE_FACTORS_SHORT, "weight", i), { n_embd_head_qk_rope/2 }, llama_model_loader::TENSOR_NOT_REQUIRED | (i != 0 ? llama_model_loader::TENSOR_DUPLICATED : 0));
  7139. }
  7140. } break;
  7141. case LLM_ARCH_GROK:
  7142. {
  7143. if (n_expert == 0) {
  7144. throw std::runtime_error("Grok model cannot have zero experts");
  7145. }
  7146. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7147. // output
  7148. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7149. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7150. // if output is NULL, init from the input tok embed
  7151. if (model.output == NULL) {
  7152. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7153. }
  7154. for (int i = 0; i < n_layer; ++i) {
  7155. auto & layer = model.layers[i];
  7156. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7157. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7158. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7159. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7160. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7161. layer.attn_out_norm = create_tensor(tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd}, 0);
  7162. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7163. layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0);
  7164. layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7165. layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert}, 0);
  7166. layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert}, 0);
  7167. layer.layer_out_norm = create_tensor(tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd}, 0);
  7168. }
  7169. } break;
  7170. case LLM_ARCH_DBRX:
  7171. {
  7172. if (n_expert == 0) {
  7173. throw std::runtime_error("DBRX model cannot have zero experts");
  7174. }
  7175. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7176. // output
  7177. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7178. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7179. for (int i = 0; i < n_layer; ++i) {
  7180. auto & layer = model.layers[i];
  7181. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7182. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7183. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7184. layer.attn_out_norm = create_tensor(tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd}, 0);
  7185. layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0);
  7186. layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, 0);
  7187. layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff, n_embd, n_expert}, 0);
  7188. layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert}, 0);
  7189. }
  7190. } break;
  7191. case LLM_ARCH_BAICHUAN:
  7192. {
  7193. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7194. {
  7195. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7196. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7197. }
  7198. for (int i = 0; i < n_layer; ++i) {
  7199. auto & layer = model.layers[i];
  7200. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7201. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7202. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7203. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7204. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7205. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7206. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7207. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7208. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7209. }
  7210. } break;
  7211. case LLM_ARCH_FALCON:
  7212. {
  7213. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7214. // output
  7215. {
  7216. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7217. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7218. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7219. if (!model.output) {
  7220. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED); // needs to be on GPU
  7221. }
  7222. }
  7223. for (int i = 0; i < n_layer; ++i) {
  7224. auto & layer = model.layers[i];
  7225. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7226. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7227. layer.attn_norm_2 = create_tensor(tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7228. layer.attn_norm_2_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7229. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7230. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7231. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7232. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7233. }
  7234. } break;
  7235. case LLM_ARCH_STARCODER:
  7236. {
  7237. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7238. model.pos_embd = create_tensor(tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train}, 0);
  7239. // output
  7240. {
  7241. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7242. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7243. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7244. if (!model.output) {
  7245. // needs to be on GPU
  7246. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7247. }
  7248. }
  7249. for (int i = 0; i < n_layer; ++i) {
  7250. auto & layer = model.layers[i];
  7251. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7252. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7253. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7254. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, 0);
  7255. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7256. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  7257. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7258. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  7259. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7260. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  7261. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7262. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0);
  7263. }
  7264. } break;
  7265. case LLM_ARCH_BERT:
  7266. case LLM_ARCH_NOMIC_BERT:
  7267. {
  7268. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7269. model.type_embd = create_tensor(tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type}, 0);
  7270. if (model.arch == LLM_ARCH_BERT) {
  7271. model.pos_embd = create_tensor(tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train}, 0);
  7272. model.cls = create_tensor(tn(LLM_TENSOR_CLS, "weight"), {n_embd, n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7273. model.cls_b = create_tensor(tn(LLM_TENSOR_CLS, "bias"), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7274. model.cls_out = create_tensor(tn(LLM_TENSOR_CLS_OUT, "weight"), {n_embd, 1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7275. model.cls_out_b = create_tensor(tn(LLM_TENSOR_CLS_OUT, "bias"), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7276. }
  7277. model.tok_norm = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd}, 0);
  7278. model.tok_norm_b = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd}, 0);
  7279. for (int i = 0; i < n_layer; ++i) {
  7280. auto & layer = model.layers[i];
  7281. if (model.arch == LLM_ARCH_BERT) {
  7282. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7283. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, 0);
  7284. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7285. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, 0);
  7286. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7287. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, 0);
  7288. } else {
  7289. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7290. }
  7291. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7292. layer.attn_out_norm = create_tensor(tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd}, 0);
  7293. layer.attn_out_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd}, 0);
  7294. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7295. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7296. if (model.arch == LLM_ARCH_BERT) {
  7297. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  7298. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0);
  7299. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  7300. } else {
  7301. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7302. }
  7303. layer.layer_out_norm = create_tensor(tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd}, 0);
  7304. layer.layer_out_norm_b = create_tensor(tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd}, 0);
  7305. }
  7306. } break;
  7307. case LLM_ARCH_JINA_BERT_V2:
  7308. {
  7309. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0); // word_embeddings
  7310. model.type_embd = create_tensor(tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type}, 0); // token_type_embeddings
  7311. model.tok_norm = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd}, 0); // LayerNorm
  7312. model.tok_norm_b = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd}, 0); //LayerNorm bias
  7313. model.cls = create_tensor(tn(LLM_TENSOR_CLS, "weight"), {n_embd, 1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7314. model.cls_b = create_tensor(tn(LLM_TENSOR_CLS, "bias"), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7315. for (int i = 0; i < n_layer; ++i) {
  7316. auto & layer = model.layers[i]; // JinaBertLayer
  7317. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7318. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, 0);
  7319. layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7320. layer.attn_q_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7321. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7322. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, 0);
  7323. layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7324. layer.attn_k_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7325. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7326. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, 0);
  7327. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0); //output_dens
  7328. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0); //output_dens
  7329. layer.attn_out_norm = create_tensor(tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd}, 0); //output_norm
  7330. layer.attn_out_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd}, 0);
  7331. layer.attn_norm_2 = create_tensor(tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7332. layer.attn_norm_2_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7333. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7334. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7335. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7336. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  7337. layer.layer_out_norm = create_tensor(tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd}, 0);
  7338. layer.layer_out_norm_b = create_tensor(tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd}, 0);
  7339. }
  7340. } break;
  7341. case LLM_ARCH_BLOOM:
  7342. {
  7343. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7344. model.tok_norm = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd}, 0);
  7345. model.tok_norm_b = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd}, 0);
  7346. // output
  7347. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7348. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7349. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7350. for (int i = 0; i < n_layer; ++i) {
  7351. auto & layer = model.layers[i];
  7352. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7353. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7354. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7355. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, 0);
  7356. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7357. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  7358. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7359. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  7360. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7361. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  7362. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7363. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0);
  7364. }
  7365. } break;
  7366. case LLM_ARCH_MPT:
  7367. {
  7368. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7369. model.pos_embd = create_tensor(tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7370. // output
  7371. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7372. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7373. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7374. if (!model.output) {
  7375. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED); // needs to be on GPU
  7376. }
  7377. for (int i = 0; i < n_layer; ++i) {
  7378. auto & layer = model.layers[i];
  7379. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7380. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7381. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7382. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7383. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7384. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7385. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7386. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7387. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7388. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7389. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7390. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7391. layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7392. layer.attn_q_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7393. layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7394. layer.attn_k_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7395. // AWQ ScaleActivation layer
  7396. layer.ffn_act = create_tensor(tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7397. }
  7398. } break;
  7399. case LLM_ARCH_STABLELM:
  7400. {
  7401. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7402. // output
  7403. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7404. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7405. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7406. for (int i = 0; i < n_layer; ++i) {
  7407. auto & layer = model.layers[i];
  7408. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7409. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7410. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7411. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7412. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7413. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7414. // optional bias tensors, present in Stable LM 2 1.6B
  7415. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7416. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7417. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7418. // optional q and k layernorms, present in StableLM 2 12B
  7419. layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k, n_head}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7420. layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k, n_head_kv}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7421. // optional FFN norm, not present in StableLM 2 12B which uses parallel residual
  7422. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7423. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7424. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7425. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7426. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7427. }
  7428. } break;
  7429. case LLM_ARCH_QWEN:
  7430. {
  7431. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7432. // output
  7433. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7434. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7435. for (int i = 0; i < n_layer; ++i) {
  7436. auto & layer = model.layers[i];
  7437. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7438. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3}, 0);
  7439. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3}, 0);
  7440. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7441. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7442. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2}, 0);
  7443. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd}, 0);
  7444. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2}, 0);
  7445. }
  7446. } break;
  7447. case LLM_ARCH_QWEN2:
  7448. {
  7449. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7450. // output
  7451. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7452. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7453. // if output is NULL, init from the input tok embed
  7454. if (model.output == NULL) {
  7455. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7456. }
  7457. for (int i = 0; i < n_layer; ++i) {
  7458. auto & layer = model.layers[i];
  7459. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7460. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7461. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7462. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7463. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7464. // optional bias tensors
  7465. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, 0);
  7466. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, 0);
  7467. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, 0);
  7468. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7469. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7470. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7471. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7472. }
  7473. } break;
  7474. case LLM_ARCH_QWEN2MOE:
  7475. {
  7476. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7477. // output
  7478. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7479. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7480. for (int i = 0; i < n_layer; ++i) {
  7481. auto & layer = model.layers[i];
  7482. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7483. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7484. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7485. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7486. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7487. // optional bias tensors
  7488. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, 0);
  7489. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, 0);
  7490. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, 0);
  7491. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7492. layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0);
  7493. if (n_expert == 0) {
  7494. throw std::runtime_error("n_expert must be > 0 for QWEN2MOE");
  7495. }
  7496. if (n_expert_used == 0) {
  7497. throw std::runtime_error("n_expert_used must be > 0 for QWEN2MOE");
  7498. }
  7499. // MoE branch
  7500. const int64_t n_ff_exp = hparams.n_ff_exp ? hparams.n_ff_exp : n_ff / n_expert_used;
  7501. layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert}, 0);
  7502. layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert}, 0);
  7503. layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert}, 0);
  7504. // Shared expert branch
  7505. const int64_t n_ff_shexp = hparams.n_ff_shexp ? hparams.n_ff_shexp : n_ff;
  7506. layer.ffn_gate_inp_shexp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP_SHEXP, "weight", i), {n_embd}, 0);
  7507. layer.ffn_gate_shexp = create_tensor(tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), { n_embd, n_ff_shexp}, 0);
  7508. layer.ffn_down_shexp = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), {n_ff_shexp, n_embd}, 0);
  7509. layer.ffn_up_shexp = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), { n_embd, n_ff_shexp}, 0);
  7510. }
  7511. } break;
  7512. case LLM_ARCH_PHI2:
  7513. {
  7514. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7515. // output
  7516. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7517. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7518. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7519. model.output_b = create_tensor(tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab}, 0);
  7520. for (int i = 0; i < n_layer; ++i) {
  7521. auto & layer = model.layers[i];
  7522. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7523. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7524. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7525. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7526. if (layer.wqkv == nullptr) {
  7527. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7528. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, 0);
  7529. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7530. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, 0);
  7531. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7532. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, 0);
  7533. }
  7534. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7535. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  7536. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7537. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  7538. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7539. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0);
  7540. }
  7541. } break;
  7542. case LLM_ARCH_PHI3:
  7543. {
  7544. const int64_t n_embd_head = n_embd / n_head;
  7545. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), { n_embd, n_vocab }, 0);
  7546. // output
  7547. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), { n_embd }, 0);
  7548. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), { n_embd, n_vocab }, 0);
  7549. for (int i = 0; i < n_layer; ++i) {
  7550. auto & layer = model.layers[i];
  7551. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), { n_embd }, 0);
  7552. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), { n_embd, n_embd + 2 * n_embd_gqa }, llama_model_loader::TENSOR_NOT_REQUIRED);
  7553. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_embd, n_embd }, 0);
  7554. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), { n_embd }, 0);
  7555. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd }, 0);
  7556. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), { n_embd, 2 * n_ff }, 0);
  7557. layer.rope_long = create_tensor(tn(LLM_TENSOR_ROPE_FACTORS_LONG, "weight", i), { n_embd_head/2 }, llama_model_loader::TENSOR_NOT_REQUIRED | (i != 0 ? llama_model_loader::TENSOR_DUPLICATED : 0));
  7558. layer.rope_short = create_tensor(tn(LLM_TENSOR_ROPE_FACTORS_SHORT, "weight", i), { n_embd_head/2 }, llama_model_loader::TENSOR_NOT_REQUIRED | (i != 0 ? llama_model_loader::TENSOR_DUPLICATED : 0));
  7559. }
  7560. } break;
  7561. case LLM_ARCH_PLAMO:
  7562. {
  7563. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7564. // output
  7565. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7566. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7567. for (int i = 0; i < n_layer; ++i) {
  7568. auto & layer = model.layers[i];
  7569. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7570. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7571. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7572. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7573. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7574. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7575. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7576. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7577. }
  7578. } break;
  7579. case LLM_ARCH_GPT2:
  7580. {
  7581. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7582. model.pos_embd = create_tensor(tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train}, 0);
  7583. // output
  7584. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7585. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7586. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7587. for (int i = 0; i < n_layer; ++i) {
  7588. auto & layer = model.layers[i];
  7589. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7590. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7591. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7592. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, 0);
  7593. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7594. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  7595. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7596. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  7597. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7598. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  7599. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7600. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0);
  7601. }
  7602. } break;
  7603. case LLM_ARCH_CODESHELL:
  7604. {
  7605. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7606. // output
  7607. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7608. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7609. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7610. for (int i = 0; i < n_layer; ++i) {
  7611. auto & layer = model.layers[i];
  7612. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7613. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7614. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7615. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, 0);
  7616. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7617. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  7618. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7619. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  7620. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7621. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  7622. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7623. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0);
  7624. }
  7625. } break;
  7626. case LLM_ARCH_ORION:
  7627. {
  7628. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7629. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7630. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7631. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7632. for (int i = 0; i < n_layer; ++i) {
  7633. auto & layer = model.layers[i];
  7634. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7635. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7636. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7637. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7638. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7639. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7640. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7641. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  7642. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7643. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7644. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7645. }
  7646. } break;
  7647. case LLM_ARCH_INTERNLM2:
  7648. {
  7649. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7650. // output
  7651. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7652. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7653. for (int i = 0; i < n_layer; ++i) {
  7654. auto & layer = model.layers[i];
  7655. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7656. // layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7657. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7658. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7659. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7660. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7661. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7662. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7663. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7664. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7665. }
  7666. } break;
  7667. case LLM_ARCH_GEMMA:
  7668. {
  7669. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7670. // output
  7671. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7672. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED); // same as tok_embd, duplicated to allow offloading
  7673. for (int i = 0; i < n_layer; ++i) {
  7674. auto & layer = model.layers[i];
  7675. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7676. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head}, 0);
  7677. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  7678. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  7679. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd}, 0);
  7680. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7681. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7682. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7683. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7684. }
  7685. } break;
  7686. case LLM_ARCH_GEMMA2:
  7687. {
  7688. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7689. // output
  7690. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7691. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED); // same as tok_embd, duplicated to allow offloading
  7692. for (int i = 0; i < n_layer; ++i) {
  7693. auto & layer = model.layers[i];
  7694. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7695. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head}, 0);
  7696. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  7697. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  7698. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd}, 0);
  7699. layer.attn_post_norm = create_tensor(tn(LLM_TENSOR_ATTN_POST_NORM, "weight", i), {n_embd}, 0);
  7700. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7701. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7702. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7703. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7704. layer.ffn_post_norm = create_tensor(tn(LLM_TENSOR_FFN_POST_NORM, "weight", i), {n_embd}, 0);
  7705. }
  7706. } break;
  7707. case LLM_ARCH_STARCODER2:
  7708. {
  7709. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7710. // output
  7711. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7712. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7713. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7714. // if output is NULL, init from the input tok embed
  7715. if (model.output == NULL) {
  7716. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7717. }
  7718. for (int i = 0; i < n_layer; ++i) {
  7719. auto & layer = model.layers[i];
  7720. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7721. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7722. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7723. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7724. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7725. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7726. // optional bias tensors
  7727. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, 0);
  7728. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, 0);
  7729. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, 0);
  7730. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  7731. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7732. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  7733. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7734. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7735. // optional bias tensors
  7736. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  7737. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP , "bias", i), { n_ff}, 0);
  7738. }
  7739. } break;
  7740. case LLM_ARCH_MAMBA:
  7741. {
  7742. const int64_t d_conv = hparams.ssm_d_conv;
  7743. const int64_t d_inner = hparams.ssm_d_inner;
  7744. const int64_t d_state = hparams.ssm_d_state;
  7745. const int64_t dt_rank = hparams.ssm_dt_rank;
  7746. // only an expansion factor of 2 is supported for now
  7747. if (2 * n_embd != d_inner) {
  7748. throw std::runtime_error("only an expansion factor of 2 is supported for now");
  7749. }
  7750. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7751. // output
  7752. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7753. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7754. // if output is NULL, init from the input tok embed, duplicated to allow offloading
  7755. if (model.output == NULL) {
  7756. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7757. }
  7758. for (int i = 0; i < n_layer; ++i) {
  7759. auto & layer = model.layers[i];
  7760. // norm
  7761. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7762. layer.ssm_in = create_tensor(tn(LLM_TENSOR_SSM_IN, "weight", i), {n_embd, 2*d_inner}, 0);
  7763. layer.ssm_conv1d = create_tensor(tn(LLM_TENSOR_SSM_CONV1D, "weight", i), {d_conv, d_inner}, 0);
  7764. layer.ssm_conv1d_b = create_tensor(tn(LLM_TENSOR_SSM_CONV1D, "bias", i), {d_inner}, 0);
  7765. layer.ssm_x = create_tensor(tn(LLM_TENSOR_SSM_X, "weight", i), {d_inner, dt_rank + 2*d_state}, 0);
  7766. layer.ssm_dt = create_tensor(tn(LLM_TENSOR_SSM_DT, "weight", i), {dt_rank, d_inner}, 0);
  7767. layer.ssm_dt_b = create_tensor(tn(LLM_TENSOR_SSM_DT, "bias", i), {d_inner}, 0);
  7768. // no "weight" suffix for these
  7769. layer.ssm_a = create_tensor(tn(LLM_TENSOR_SSM_A, i), {d_state, d_inner}, 0);
  7770. layer.ssm_d = create_tensor(tn(LLM_TENSOR_SSM_D, i), {d_inner}, 0);
  7771. // out_proj
  7772. layer.ssm_out = create_tensor(tn(LLM_TENSOR_SSM_OUT, "weight", i), {d_inner, n_embd}, 0);
  7773. }
  7774. } break;
  7775. case LLM_ARCH_XVERSE:
  7776. {
  7777. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7778. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7779. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7780. for (int i = 0; i < n_layer; ++i) {
  7781. auto & layer = model.layers[i];
  7782. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7783. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7784. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7785. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7786. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7787. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7788. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7789. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7790. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7791. }
  7792. } break;
  7793. case LLM_ARCH_COMMAND_R:
  7794. {
  7795. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7796. // output
  7797. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7798. // init output from the input tok embed
  7799. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7800. for (int i = 0; i < n_layer; ++i) {
  7801. auto & layer = model.layers[i];
  7802. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7803. if (n_layer >= 64){
  7804. layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k, n_head}, 0);
  7805. layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k, n_head_kv}, 0);
  7806. }
  7807. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7808. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7809. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7810. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7811. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7812. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7813. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7814. }
  7815. } break;
  7816. case LLM_ARCH_OLMO: // adapted from LLM_ARCH_LLAMA with norm params removed
  7817. {
  7818. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7819. // output
  7820. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7821. // if output is NULL, init from the input tok embed
  7822. if (model.output == NULL) {
  7823. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7824. }
  7825. for (int i = 0; i < n_layer; ++i) {
  7826. auto & layer = model.layers[i];
  7827. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7828. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7829. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7830. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7831. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7832. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7833. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7834. }
  7835. } break;
  7836. case LLM_ARCH_OLMO2:
  7837. {
  7838. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7839. // output
  7840. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7841. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7842. for (int i = 0; i < n_layer; ++i) {
  7843. auto & layer = model.layers[i];
  7844. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7845. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7846. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7847. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7848. layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd}, 0);
  7849. layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd}, 0);
  7850. layer.attn_post_norm = create_tensor(tn(LLM_TENSOR_ATTN_POST_NORM, "weight", i), {n_embd}, 0);
  7851. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7852. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7853. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7854. layer.ffn_post_norm = create_tensor(tn(LLM_TENSOR_FFN_POST_NORM, "weight", i), {n_embd}, 0);
  7855. }
  7856. } break;
  7857. case LLM_ARCH_OLMOE:
  7858. {
  7859. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7860. // output
  7861. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7862. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7863. for (int i = 0; i < n_layer; ++i) {
  7864. auto & layer = model.layers[i];
  7865. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7866. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7867. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7868. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7869. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7870. layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd}, 0);
  7871. layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd}, 0);
  7872. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7873. layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0);
  7874. if (n_expert == 0) {
  7875. throw std::runtime_error("n_expert must be > 0");
  7876. }
  7877. if (n_expert_used == 0) {
  7878. throw std::runtime_error("n_expert_used must be > 0");
  7879. }
  7880. // MoE branch
  7881. layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, 0);
  7882. layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff, n_embd, n_expert}, 0);
  7883. layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert}, 0);
  7884. }
  7885. } break;
  7886. case LLM_ARCH_OPENELM:
  7887. {
  7888. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7889. // output
  7890. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7891. // init output from the input tok embed
  7892. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7893. for (int i = 0; i < n_layer; ++i) {
  7894. const int64_t n_head = hparams.n_head(i);
  7895. const int64_t n_head_qkv = 2*hparams.n_head_kv(i) + n_head;
  7896. const int64_t n_ff = hparams.n_ff(i);
  7897. auto & layer = model.layers[i];
  7898. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7899. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_head_qkv*n_embd_head_k}, 0);
  7900. layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k}, 0);
  7901. layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k}, 0);
  7902. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_head*n_embd_head_k, n_embd}, 0);
  7903. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7904. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7905. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7906. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7907. }
  7908. } break;
  7909. case LLM_ARCH_GPTNEOX:
  7910. {
  7911. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7912. // output
  7913. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7914. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7915. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7916. for (int i = 0; i < n_layer; ++i) {
  7917. auto & layer = model.layers[i];
  7918. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7919. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7920. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7921. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, 0);
  7922. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7923. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  7924. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7925. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  7926. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7927. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  7928. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7929. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0);
  7930. }
  7931. } break;
  7932. case LLM_ARCH_ARCTIC:
  7933. {
  7934. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7935. // output
  7936. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7937. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7938. // if output is NULL, init from the input tok embed
  7939. if (model.output == NULL) {
  7940. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7941. }
  7942. for (int i = 0; i < n_layer; ++i) {
  7943. auto & layer = model.layers[i];
  7944. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7945. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7946. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7947. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7948. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7949. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7950. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_embd}, 0);
  7951. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_embd, n_embd}, 0);
  7952. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_embd}, 0);
  7953. layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0);
  7954. layer.ffn_norm_exps = create_tensor(tn(LLM_TENSOR_FFN_NORM_EXPS, "weight", i), {n_embd}, 0);
  7955. layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, false);
  7956. layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert}, 0);
  7957. layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert}, 0);
  7958. }
  7959. } break;
  7960. case LLM_ARCH_DEEPSEEK2:
  7961. {
  7962. const bool is_lite = (hparams.n_layer == 27);
  7963. const int64_t n_embd_head_qk_rope = hparams.n_rot;
  7964. const int64_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  7965. const int64_t q_lora_rank = hparams.n_lora_q;
  7966. const int64_t kv_lora_rank = hparams.n_lora_kv;
  7967. const int64_t n_ff_exp = hparams.n_ff_exp;
  7968. const int64_t n_expert_shared = hparams.n_expert_shared;
  7969. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7970. // output
  7971. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7972. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7973. for (int i = 0; i < n_layer; ++i) {
  7974. auto & layer = model.layers[i];
  7975. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7976. if (!is_lite) {
  7977. layer.attn_q_a_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_A_NORM, "weight", i), {q_lora_rank}, 0);
  7978. }
  7979. layer.attn_kv_a_norm = create_tensor(tn(LLM_TENSOR_ATTN_KV_A_NORM, "weight", i), {kv_lora_rank}, 0);
  7980. if (!is_lite) {
  7981. layer.wq_a = create_tensor(tn(LLM_TENSOR_ATTN_Q_A, "weight", i), {n_embd, q_lora_rank}, 0);
  7982. layer.wq_b = create_tensor(tn(LLM_TENSOR_ATTN_Q_B, "weight", i), {q_lora_rank, n_head * n_embd_head_k}, 0);
  7983. } else {
  7984. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  7985. }
  7986. layer.wkv_a_mqa = create_tensor(tn(LLM_TENSOR_ATTN_KV_A_MQA, "weight", i), {n_embd, kv_lora_rank + (n_embd_head_qk_rope)}, 0);
  7987. layer.wkv_b = create_tensor(tn(LLM_TENSOR_ATTN_KV_B, "weight", i), {kv_lora_rank, n_head * (n_embd_head_qk_nope + n_embd_head_v)}, 0);
  7988. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_head * ( n_embd_head_v), n_embd}, 0);
  7989. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7990. if (i < (int) hparams.n_layer_dense_lead) {
  7991. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7992. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7993. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7994. } else {
  7995. layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0);
  7996. if (n_expert == 0) {
  7997. throw std::runtime_error("n_expert must be > 0");
  7998. }
  7999. if (n_expert_used == 0) {
  8000. throw std::runtime_error("n_expert_used must be > 0");
  8001. }
  8002. // MoE branch
  8003. layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert}, 0);
  8004. layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert}, 0);
  8005. layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert}, 0);
  8006. // Shared expert branch
  8007. layer.ffn_gate_shexp = create_tensor(tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), {n_embd, n_ff_exp * n_expert_shared}, 0);
  8008. layer.ffn_down_shexp = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), { n_ff_exp * n_expert_shared, n_embd}, 0);
  8009. layer.ffn_up_shexp = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), {n_embd, n_ff_exp * n_expert_shared}, 0);
  8010. }
  8011. }
  8012. } break;
  8013. case LLM_ARCH_BITNET:
  8014. {
  8015. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8016. // output
  8017. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8018. for (int i = 0; i < n_layer; ++i) {
  8019. auto & layer = model.layers[i];
  8020. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  8021. layer.attn_sub_norm = create_tensor(tn(LLM_TENSOR_ATTN_SUB_NORM, "weight", i), {n_embd}, 0);
  8022. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  8023. layer.wq_scale = create_tensor(tn(LLM_TENSOR_ATTN_Q, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8024. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  8025. layer.wk_scale = create_tensor(tn(LLM_TENSOR_ATTN_K, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8026. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  8027. layer.wv_scale = create_tensor(tn(LLM_TENSOR_ATTN_V, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8028. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  8029. layer.wo_scale = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8030. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  8031. layer.ffn_sub_norm = create_tensor(tn(LLM_TENSOR_FFN_SUB_NORM, "weight", i), {n_ff}, 0);
  8032. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  8033. layer.ffn_gate_scale = create_tensor(tn(LLM_TENSOR_FFN_GATE, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8034. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  8035. layer.ffn_down_scale = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8036. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8037. layer.ffn_up_scale = create_tensor(tn(LLM_TENSOR_FFN_UP, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8038. }
  8039. } break;
  8040. case LLM_ARCH_T5:
  8041. {
  8042. const auto n_rel_attn_bkts = hparams.n_rel_attn_bkts;
  8043. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8044. // output
  8045. model.output_norm_enc = create_tensor(tn(LLM_TENSOR_ENC_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8046. model.output_norm = create_tensor(tn(LLM_TENSOR_DEC_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8047. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8048. // if output is NULL, init from the input tok embed
  8049. if (model.output == NULL) {
  8050. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  8051. }
  8052. for (int i = 0; i < n_layer; ++i) {
  8053. auto & layer = model.layers[i];
  8054. layer.attn_norm_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_NORM, "weight", i), {n_embd}, 0);
  8055. layer.attn_rel_b_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_REL_B, "weight", i), {n_head, n_rel_attn_bkts}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8056. layer.wq_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8057. layer.wk_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8058. layer.wv_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  8059. layer.wo_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd}, 0);
  8060. layer.ffn_norm_enc = create_tensor(tn(LLM_TENSOR_ENC_FFN_NORM, "weight", i), {n_embd}, 0);
  8061. layer.ffn_gate_enc = create_tensor(tn(LLM_TENSOR_ENC_FFN_GATE, "weight", i), {n_embd, n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8062. layer.ffn_down_enc = create_tensor(tn(LLM_TENSOR_ENC_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  8063. layer.ffn_up_enc = create_tensor(tn(LLM_TENSOR_ENC_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8064. layer.attn_norm = create_tensor(tn(LLM_TENSOR_DEC_ATTN_NORM, "weight", i), {n_embd}, 0);
  8065. layer.attn_rel_b = create_tensor(tn(LLM_TENSOR_DEC_ATTN_REL_B, "weight", i), {n_head, n_rel_attn_bkts}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8066. layer.wq = create_tensor(tn(LLM_TENSOR_DEC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8067. layer.wk = create_tensor(tn(LLM_TENSOR_DEC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8068. layer.wv = create_tensor(tn(LLM_TENSOR_DEC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  8069. layer.wo = create_tensor(tn(LLM_TENSOR_DEC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd}, 0);
  8070. layer.attn_norm_cross = create_tensor(tn(LLM_TENSOR_DEC_CROSS_ATTN_NORM, "weight", i), {n_embd}, 0);
  8071. // this tensor seems to be unused in HF transformers implementation
  8072. layer.attn_rel_b_cross = create_tensor(tn(LLM_TENSOR_DEC_CROSS_ATTN_REL_B, "weight", i), {n_head, n_rel_attn_bkts}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8073. layer.wq_cross = create_tensor(tn(LLM_TENSOR_DEC_CROSS_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8074. layer.wk_cross = create_tensor(tn(LLM_TENSOR_DEC_CROSS_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8075. layer.wv_cross = create_tensor(tn(LLM_TENSOR_DEC_CROSS_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  8076. layer.wo_cross = create_tensor(tn(LLM_TENSOR_DEC_CROSS_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd}, 0);
  8077. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_DEC_FFN_NORM, "weight", i), {n_embd}, 0);
  8078. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_DEC_FFN_GATE, "weight", i), {n_embd, n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8079. layer.ffn_down = create_tensor(tn(LLM_TENSOR_DEC_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  8080. layer.ffn_up = create_tensor(tn(LLM_TENSOR_DEC_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8081. }
  8082. } break;
  8083. case LLM_ARCH_T5ENCODER:
  8084. {
  8085. const auto n_rel_attn_bkts = hparams.n_rel_attn_bkts;
  8086. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8087. // output
  8088. model.output_norm_enc = create_tensor(tn(LLM_TENSOR_ENC_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8089. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8090. // if output is NULL, init from the input tok embed
  8091. if (model.output == NULL) {
  8092. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  8093. }
  8094. for (int i = 0; i < n_layer; ++i) {
  8095. auto & layer = model.layers[i];
  8096. layer.attn_norm_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_NORM, "weight", i), {n_embd}, 0);
  8097. layer.attn_rel_b_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_REL_B, "weight", i), {n_head, n_rel_attn_bkts}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8098. layer.wq_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8099. layer.wk_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8100. layer.wv_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  8101. layer.wo_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd}, 0);
  8102. layer.ffn_norm_enc = create_tensor(tn(LLM_TENSOR_ENC_FFN_NORM, "weight", i), {n_embd}, 0);
  8103. layer.ffn_gate_enc = create_tensor(tn(LLM_TENSOR_ENC_FFN_GATE, "weight", i), {n_embd, n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8104. layer.ffn_down_enc = create_tensor(tn(LLM_TENSOR_ENC_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  8105. layer.ffn_up_enc = create_tensor(tn(LLM_TENSOR_ENC_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8106. }
  8107. } break;
  8108. case LLM_ARCH_JAIS:
  8109. {
  8110. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8111. // output
  8112. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8113. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  8114. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  8115. for (int i = 0; i < n_layer; ++i) {
  8116. auto & layer = model.layers[i];
  8117. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  8118. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  8119. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  8120. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, 0);
  8121. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  8122. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  8123. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  8124. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  8125. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  8126. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  8127. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  8128. layer.ffn_gate_b = create_tensor(tn(LLM_TENSOR_FFN_GATE, "bias", i), {n_ff}, 0);
  8129. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8130. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0);
  8131. }
  8132. } break;
  8133. case LLM_ARCH_CHATGLM:
  8134. {
  8135. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8136. // output
  8137. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8138. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  8139. for (int i = 0; i < n_layer; ++i) {
  8140. auto & layer = model.layers[i];
  8141. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  8142. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  8143. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, 0);
  8144. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  8145. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  8146. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff * 2}, 0);
  8147. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  8148. }
  8149. } break;
  8150. case LLM_ARCH_NEMOTRON:
  8151. {
  8152. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8153. // output
  8154. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8155. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  8156. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  8157. for (int i = 0; i < n_layer; ++i) {
  8158. auto & layer = model.layers[i];
  8159. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  8160. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  8161. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  8162. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  8163. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  8164. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  8165. // optional bias tensors
  8166. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8167. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8168. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8169. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8170. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  8171. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  8172. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  8173. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8174. // optional MLP bias
  8175. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8176. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8177. }
  8178. } break;
  8179. case LLM_ARCH_EXAONE:
  8180. {
  8181. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8182. // output
  8183. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8184. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  8185. for (int i = 0; i < n_layer; ++i) {
  8186. auto & layer = model.layers[i];
  8187. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  8188. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head}, 0);
  8189. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8190. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  8191. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd}, 0);
  8192. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  8193. layer.rope_freqs = create_tensor(tn(LLM_TENSOR_ROPE_FREQS, "weight", i), {n_rot/2}, llama_model_loader::TENSOR_NOT_REQUIRED | (i != 0 ? llama_model_loader::TENSOR_DUPLICATED : 0));
  8194. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  8195. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  8196. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8197. }
  8198. } break;
  8199. case LLM_ARCH_RWKV6:
  8200. {
  8201. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8202. // Block 0, LN0
  8203. model.tok_norm = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd}, 0);
  8204. model.tok_norm_b = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd}, 0);
  8205. // output
  8206. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8207. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  8208. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  8209. const int time_mix_extra_dim = hparams.time_mix_extra_dim;
  8210. const int time_decay_extra_dim = hparams.time_decay_extra_dim;
  8211. const int head_size = hparams.wkv_head_size;
  8212. const int attn_hidden_size = n_embd;
  8213. const int ffn_size = hparams.n_ff_arr[0];
  8214. for (int i = 0; i < n_layer; ++i) {
  8215. auto & layer = model.layers[i];
  8216. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  8217. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  8218. layer.attn_norm_2 = create_tensor(tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd}, 0);
  8219. layer.attn_norm_2_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd}, 0);
  8220. layer.time_mix_w1 = create_tensor(tn(LLM_TENSOR_TIME_MIX_W1, "weight", i), {n_embd, time_mix_extra_dim * 5}, 0);
  8221. layer.time_mix_w2 = create_tensor(tn(LLM_TENSOR_TIME_MIX_W2, "weight", i), {time_mix_extra_dim, n_embd, 5}, 0);
  8222. layer.time_mix_lerp_x = create_tensor(tn(LLM_TENSOR_TIME_MIX_LERP_X, "weight", i), {n_embd, 1, 1}, 0);
  8223. layer.time_mix_lerp_w = create_tensor(tn(LLM_TENSOR_TIME_MIX_LERP_W, "weight", i), {n_embd, 1, 1}, 0);
  8224. layer.time_mix_lerp_k = create_tensor(tn(LLM_TENSOR_TIME_MIX_LERP_K, "weight", i), {n_embd, 1, 1}, 0);
  8225. layer.time_mix_lerp_v = create_tensor(tn(LLM_TENSOR_TIME_MIX_LERP_V, "weight", i), {n_embd, 1, 1}, 0);
  8226. layer.time_mix_lerp_r = create_tensor(tn(LLM_TENSOR_TIME_MIX_LERP_R, "weight", i), {n_embd, 1, 1}, 0);
  8227. layer.time_mix_lerp_g = create_tensor(tn(LLM_TENSOR_TIME_MIX_LERP_G, "weight", i), {n_embd, 1, 1}, 0);
  8228. layer.time_mix_first = create_tensor(tn(LLM_TENSOR_TIME_MIX_FIRST, "weight", i), {head_size, n_embd / head_size}, 0);
  8229. layer.time_mix_decay = create_tensor(tn(LLM_TENSOR_TIME_MIX_DECAY, "weight", i), {n_embd}, 0);
  8230. layer.time_mix_decay_w1 = create_tensor(tn(LLM_TENSOR_TIME_MIX_DECAY_W1, "weight", i), {n_embd, time_decay_extra_dim}, 0);
  8231. layer.time_mix_decay_w2 = create_tensor(tn(LLM_TENSOR_TIME_MIX_DECAY_W2, "weight", i), {time_decay_extra_dim, attn_hidden_size}, 0);
  8232. layer.time_mix_key = create_tensor(tn(LLM_TENSOR_TIME_MIX_KEY, "weight", i), {attn_hidden_size, n_embd}, 0);
  8233. layer.time_mix_value = create_tensor(tn(LLM_TENSOR_TIME_MIX_VALUE, "weight", i), {attn_hidden_size, n_embd}, 0);
  8234. layer.time_mix_receptance = create_tensor(tn(LLM_TENSOR_TIME_MIX_RECEPTANCE, "weight", i), {attn_hidden_size, n_embd}, 0);
  8235. layer.time_mix_gate = create_tensor(tn(LLM_TENSOR_TIME_MIX_GATE, "weight", i), {attn_hidden_size, n_embd}, 0);
  8236. layer.time_mix_ln = create_tensor(tn(LLM_TENSOR_TIME_MIX_LN, "weight", i), {n_embd}, 0);
  8237. layer.time_mix_ln_b = create_tensor(tn(LLM_TENSOR_TIME_MIX_LN, "bias", i), {n_embd}, 0);
  8238. layer.time_mix_output = create_tensor(tn(LLM_TENSOR_TIME_MIX_OUTPUT, "weight", i), {n_embd, attn_hidden_size}, 0);
  8239. layer.channel_mix_lerp_k = create_tensor(tn(LLM_TENSOR_CHANNEL_MIX_LERP_K, "weight", i), {n_embd, 1, 1}, 0);
  8240. layer.channel_mix_lerp_r = create_tensor(tn(LLM_TENSOR_CHANNEL_MIX_LERP_R, "weight", i), {n_embd, 1, 1}, 0);
  8241. layer.channel_mix_key = create_tensor(tn(LLM_TENSOR_CHANNEL_MIX_KEY, "weight", i), {n_embd, ffn_size}, 0);
  8242. layer.channel_mix_value = create_tensor(tn(LLM_TENSOR_CHANNEL_MIX_VALUE, "weight", i), {ffn_size, n_embd}, 0);
  8243. layer.channel_mix_receptance = create_tensor(tn(LLM_TENSOR_CHANNEL_MIX_RECEPTANCE, "weight", i), {n_embd, n_embd}, 0);
  8244. }
  8245. } break;
  8246. case LLM_ARCH_CHAMELEON:
  8247. {
  8248. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8249. // output
  8250. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8251. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8252. // if output is NULL, init from the input tok embed
  8253. if (model.output == NULL) {
  8254. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  8255. }
  8256. for (int i = 0; i < n_layer; ++i) {
  8257. auto & layer = model.layers[i];
  8258. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  8259. layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k, n_head}, 0);
  8260. layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k, n_head_kv}, 0);
  8261. layer.attn_q_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {n_embd_head_k, n_head}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8262. layer.attn_k_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {n_embd_head_k, n_head_kv}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8263. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  8264. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  8265. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  8266. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  8267. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  8268. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  8269. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  8270. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8271. }
  8272. } break;
  8273. case LLM_ARCH_SOLAR:
  8274. {
  8275. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8276. // output
  8277. {
  8278. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8279. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8280. }
  8281. for (int i = 0; i < n_layer; ++i) {
  8282. auto & layer = model.layers[i];
  8283. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  8284. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head}, 0);
  8285. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8286. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  8287. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd}, 0);
  8288. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  8289. layer.bskcn_tv = create_tensor(tn(LLM_TENSOR_BSKCN_TV, "weight", i), {2}, llama_model_loader::TENSOR_NOT_REQUIRED | (i != 0 ? llama_model_loader::TENSOR_DUPLICATED : 0));
  8290. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  8291. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  8292. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8293. }
  8294. } break;
  8295. default:
  8296. throw std::runtime_error("unknown architecture");
  8297. }
  8298. if (n_moved_tensors > 0) {
  8299. LLAMA_LOG_DEBUG("%s: tensor '%s' (%s) (and %d others) cannot be used with preferred buffer type %s, using %s instead\n",
  8300. __func__, first_moved_tensor->name, ggml_type_name(first_moved_tensor->type), n_moved_tensors - 1,
  8301. ggml_backend_buft_name(first_moved_from_buft), ggml_backend_buft_name(first_moved_to_buft));
  8302. }
  8303. }
  8304. ml.done_getting_tensors();
  8305. ml.init_mappings(true, use_mlock ? &model.mlock_mmaps : nullptr);
  8306. model.mappings.reserve(ml.mappings.size());
  8307. // create the backend buffers
  8308. std::vector<std::pair<ggml_context *, llama_buf_map>> ctx_bufs;
  8309. ctx_bufs.reserve(ctx_map.size());
  8310. // Ensure we have enough capacity for the maximum backend buffer we will potentially create
  8311. const size_t n_max_backend_buffer = ctx_map.size() * ml.files.size();
  8312. model.bufs.reserve(n_max_backend_buffer);
  8313. for (auto & it : ctx_map) {
  8314. ggml_backend_buffer_type_t buft = it.first;
  8315. ggml_context * ctx = it.second;
  8316. // skip contexts without tensors
  8317. if (ggml_get_first_tensor(ctx) == nullptr) {
  8318. continue;
  8319. }
  8320. llama_buf_map bufs;
  8321. bufs.reserve(n_max_backend_buffer);
  8322. // check if it is possible to use buffer_from_host_ptr with this buffer type
  8323. ggml_backend_dev_t dev = ggml_backend_buft_get_device(buft);
  8324. if (!dev) {
  8325. // FIXME: workaround for CPU backend buft having a NULL device
  8326. dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
  8327. }
  8328. ggml_backend_dev_props props;
  8329. ggml_backend_dev_get_props(dev, &props);
  8330. bool buffer_from_host_ptr_supported = props.caps.buffer_from_host_ptr;
  8331. bool is_default_buft = buft == ggml_backend_dev_buffer_type(dev);
  8332. if (ml.use_mmap && use_mmap_buffer && buffer_from_host_ptr_supported && is_default_buft) {
  8333. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  8334. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  8335. // 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
  8336. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  8337. void * addr = nullptr;
  8338. size_t first, last; // NOLINT
  8339. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  8340. if (first >= last) {
  8341. continue;
  8342. }
  8343. const size_t max_size = ggml_get_max_tensor_size(ctx);
  8344. ggml_backend_buffer_t buf = ggml_backend_dev_buffer_from_host_ptr(dev, (char *) addr + first, last - first, max_size);
  8345. if (buf == nullptr) {
  8346. throw std::runtime_error(format("unable to allocate %s buffer", ggml_backend_buft_name(buft)));
  8347. }
  8348. model.bufs.emplace_back(buf);
  8349. bufs.emplace(idx, buf);
  8350. }
  8351. }
  8352. else {
  8353. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  8354. if (buf == nullptr) {
  8355. throw std::runtime_error(format("unable to allocate %s buffer", ggml_backend_buft_name(buft)));
  8356. }
  8357. model.bufs.emplace_back(buf);
  8358. if (use_mlock && ggml_backend_buffer_is_host(buf)) {
  8359. model.mlock_bufs.emplace_back(new llama_mlock);
  8360. auto & mlock_buf = model.mlock_bufs.back();
  8361. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  8362. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  8363. }
  8364. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  8365. bufs.emplace(idx, buf);
  8366. }
  8367. }
  8368. if (bufs.empty()) {
  8369. throw std::runtime_error("failed to allocate buffer");
  8370. }
  8371. for (auto & buf : bufs) {
  8372. // indicate that this buffer contains weights
  8373. // 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
  8374. ggml_backend_buffer_set_usage(buf.second, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  8375. }
  8376. ctx_bufs.emplace_back(ctx, bufs);
  8377. }
  8378. if (llama_supports_gpu_offload()) {
  8379. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  8380. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  8381. if (n_gpu_layers > (int) hparams.n_layer) {
  8382. LLAMA_LOG_INFO("%s: offloading output layer to GPU\n", __func__);
  8383. }
  8384. const int max_backend_supported_layers = hparams.n_layer + 1;
  8385. const int max_offloadable_layers = hparams.n_layer + 1;
  8386. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  8387. }
  8388. // print memory requirements per buffer type
  8389. for (auto & buf : model.bufs) {
  8390. LLAMA_LOG_INFO("%s: %12s model buffer size = %8.2f MiB\n", __func__, ggml_backend_buffer_name(buf.get()), ggml_backend_buffer_get_size(buf.get()) / 1024.0 / 1024.0);
  8391. }
  8392. // populate tensors_by_name
  8393. for (auto & ctx : model.ctxs) {
  8394. for (auto * cur = ggml_get_first_tensor(ctx.get()); cur != NULL; cur = ggml_get_next_tensor(ctx.get(), cur)) {
  8395. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  8396. }
  8397. }
  8398. // load tensor data
  8399. for (auto & it : ctx_bufs) {
  8400. ggml_context * ctx = it.first;
  8401. auto & bufs = it.second;
  8402. if (!ml.load_all_data(ctx, bufs, use_mlock ? &model.mlock_mmaps : NULL, progress_callback, progress_callback_user_data)) {
  8403. return false;
  8404. }
  8405. }
  8406. if (use_mmap_buffer) {
  8407. for (auto & mapping : ml.mappings) {
  8408. model.mappings.emplace_back(std::move(mapping));
  8409. }
  8410. }
  8411. return true;
  8412. }
  8413. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  8414. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  8415. model.t_start_us = ggml_time_us();
  8416. try {
  8417. llama_model_loader ml(fname, params.use_mmap, params.check_tensors, params.kv_overrides);
  8418. model.hparams.vocab_only = params.vocab_only;
  8419. try {
  8420. llm_load_arch(ml, model);
  8421. } catch(const std::exception & e) {
  8422. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  8423. }
  8424. try {
  8425. llm_load_hparams(ml, model);
  8426. } catch(const std::exception & e) {
  8427. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  8428. }
  8429. try {
  8430. llm_load_vocab(ml, model);
  8431. } catch(const std::exception & e) {
  8432. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  8433. }
  8434. llm_load_stats(ml, model);
  8435. llm_load_print_meta(ml, model);
  8436. if (model.vocab.type != LLAMA_VOCAB_TYPE_NONE &&
  8437. model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  8438. LLAMA_LOG_WARN("%s: vocab mismatch %u !- %zu ...\n", __func__, model.hparams.n_vocab, model.vocab.id_to_token.size());
  8439. }
  8440. if (params.vocab_only) {
  8441. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  8442. return 0;
  8443. }
  8444. if (!llm_load_tensors(
  8445. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  8446. params.progress_callback, params.progress_callback_user_data
  8447. )) {
  8448. return -2;
  8449. }
  8450. } catch (const std::exception & err) {
  8451. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  8452. return -1;
  8453. }
  8454. // loading time will be recalculate after the first eval, so
  8455. // we take page faults deferred by mmap() into consideration
  8456. model.t_load_us = ggml_time_us() - model.t_start_us;
  8457. return 0;
  8458. }
  8459. //
  8460. // llm_build
  8461. //
  8462. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  8463. enum llm_ffn_op_type {
  8464. LLM_FFN_SILU,
  8465. LLM_FFN_GELU,
  8466. LLM_FFN_RELU,
  8467. LLM_FFN_RELU_SQR,
  8468. LLM_FFN_SWIGLU,
  8469. };
  8470. enum llm_ffn_gate_type {
  8471. LLM_FFN_SEQ,
  8472. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  8473. };
  8474. enum llm_norm_type {
  8475. LLM_NORM,
  8476. LLM_NORM_RMS,
  8477. };
  8478. static struct ggml_tensor * llm_build_inp_embd(
  8479. struct ggml_context * ctx,
  8480. struct llama_context & lctx,
  8481. const llama_hparams & hparams,
  8482. const llama_ubatch & batch,
  8483. struct ggml_tensor * tok_embd,
  8484. const llm_build_cb & cb) {
  8485. const int64_t n_embd = hparams.n_embd;
  8486. struct ggml_tensor * inpL;
  8487. if (batch.token) {
  8488. lctx.inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  8489. cb(lctx.inp_tokens, "inp_tokens", -1);
  8490. ggml_set_input(lctx.inp_tokens);
  8491. inpL = ggml_get_rows(ctx, tok_embd, lctx.inp_tokens);
  8492. } else {
  8493. lctx.inp_embd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  8494. inpL = lctx.inp_embd;
  8495. ggml_set_input(lctx.inp_embd);
  8496. }
  8497. // For Granite architecture
  8498. if (hparams.f_embedding_scale != 0.0f) {
  8499. inpL = ggml_scale(ctx, inpL, hparams.f_embedding_scale);
  8500. }
  8501. cb(inpL, "inp_embd", -1);
  8502. return inpL;
  8503. }
  8504. static struct ggml_tensor * llm_build_inp_cross_attn_state(
  8505. struct ggml_context * ctx,
  8506. struct llama_context & lctx,
  8507. const llama_hparams & hparams,
  8508. const llm_build_cb & cb) {
  8509. const int64_t n_embd = hparams.n_embd;
  8510. struct ggml_tensor * inpCAS = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n_embd, 1601, 4);
  8511. cb(inpCAS, "inp_cross_attn_state", -1);
  8512. ggml_set_input(inpCAS);
  8513. lctx.inp_cross_attn_state = inpCAS;
  8514. return inpCAS;
  8515. }
  8516. static void llm_build_kv_store(
  8517. struct ggml_context * ctx,
  8518. const llama_hparams & hparams,
  8519. const llama_cparams & cparams,
  8520. const llama_kv_cache & kv,
  8521. struct ggml_cgraph * graph,
  8522. struct ggml_tensor * k_cur,
  8523. struct ggml_tensor * v_cur,
  8524. int32_t n_tokens,
  8525. int32_t kv_head,
  8526. const llm_build_cb & cb,
  8527. int64_t il) {
  8528. const int64_t n_ctx = cparams.n_ctx;
  8529. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  8530. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  8531. GGML_ASSERT(kv.size == n_ctx);
  8532. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa, ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa)*kv_head);
  8533. cb(k_cache_view, "k_cache_view", il);
  8534. // note: storing RoPE-ed version of K in the KV cache
  8535. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  8536. assert(v_cur->ne[0] == n_embd_v_gqa && v_cur->ne[1] == n_tokens);
  8537. struct ggml_tensor * v_cache_view = nullptr;
  8538. if (cparams.flash_attn) {
  8539. v_cache_view = ggml_view_1d(ctx, kv.v_l[il], n_tokens*n_embd_v_gqa, ggml_row_size(kv.v_l[il]->type, n_embd_v_gqa)*kv_head);
  8540. } else {
  8541. // note: the V cache is transposed when not using flash attention
  8542. v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  8543. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  8544. (kv_head)*ggml_element_size(kv.v_l[il]));
  8545. v_cur = ggml_transpose(ctx, v_cur);
  8546. }
  8547. cb(v_cache_view, "v_cache_view", il);
  8548. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur, v_cache_view));
  8549. }
  8550. // do mat_mul, while optionally apply lora
  8551. static struct ggml_tensor * llm_build_lora_mm(
  8552. struct llama_context & lctx,
  8553. struct ggml_context * ctx0,
  8554. struct ggml_tensor * w,
  8555. struct ggml_tensor * cur) {
  8556. struct ggml_tensor * res = ggml_mul_mat(ctx0, w, cur);
  8557. for (auto & it : lctx.lora_adapters) {
  8558. struct llama_lora_weight * lora = it.first->get_weight(w);
  8559. if (lora == nullptr) {
  8560. continue;
  8561. }
  8562. const float alpha = it.first->alpha;
  8563. const float rank = (float) lora->b->ne[0];
  8564. const float scale = alpha ? it.second * alpha / rank : it.second;
  8565. struct ggml_tensor * ab_cur = ggml_mul_mat(
  8566. ctx0, lora->b,
  8567. ggml_mul_mat(ctx0, lora->a, cur)
  8568. );
  8569. ab_cur = ggml_scale(ctx0, ab_cur, scale);
  8570. res = ggml_add(ctx0, res, ab_cur);
  8571. }
  8572. return res;
  8573. }
  8574. // do mat_mul_id, while optionally apply lora
  8575. static struct ggml_tensor * llm_build_lora_mm_id(
  8576. struct llama_context & lctx,
  8577. struct ggml_context * ctx0,
  8578. struct ggml_tensor * w, // struct ggml_tensor * as
  8579. struct ggml_tensor * cur, // struct ggml_tensor * b
  8580. struct ggml_tensor * ids) {
  8581. struct ggml_tensor * res = ggml_mul_mat_id(ctx0, w, cur, ids);
  8582. for (auto & it : lctx.lora_adapters) {
  8583. struct llama_lora_weight * lora = it.first->get_weight(w);
  8584. if (lora == nullptr) {
  8585. continue;
  8586. }
  8587. const float alpha = it.first->alpha;
  8588. const float rank = (float) lora->b->ne[0];
  8589. const float scale = alpha ? it.second * alpha / rank : it.second;
  8590. struct ggml_tensor * ab_cur = ggml_mul_mat_id(
  8591. ctx0, lora->b,
  8592. ggml_mul_mat_id(ctx0, lora->a, cur, ids),
  8593. ids
  8594. );
  8595. ab_cur = ggml_scale(ctx0, ab_cur, scale);
  8596. res = ggml_add(ctx0, res, ab_cur);
  8597. }
  8598. return res;
  8599. }
  8600. static struct ggml_tensor * llm_build_norm(
  8601. struct ggml_context * ctx,
  8602. struct ggml_tensor * cur,
  8603. const llama_hparams & hparams,
  8604. struct ggml_tensor * mw,
  8605. struct ggml_tensor * mb,
  8606. llm_norm_type type,
  8607. const llm_build_cb & cb,
  8608. int il) {
  8609. switch (type) {
  8610. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  8611. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  8612. }
  8613. if (mw || mb) {
  8614. cb(cur, "norm", il);
  8615. }
  8616. if (mw) {
  8617. cur = ggml_mul(ctx, cur, mw);
  8618. if (mb) {
  8619. cb(cur, "norm_w", il);
  8620. }
  8621. }
  8622. if (mb) {
  8623. cur = ggml_add(ctx, cur, mb);
  8624. }
  8625. return cur;
  8626. }
  8627. static struct ggml_tensor * llm_build_ffn(
  8628. struct ggml_context * ctx,
  8629. struct llama_context & lctx,
  8630. struct ggml_tensor * cur,
  8631. struct ggml_tensor * up,
  8632. struct ggml_tensor * up_b,
  8633. struct ggml_tensor * up_s,
  8634. struct ggml_tensor * gate,
  8635. struct ggml_tensor * gate_b,
  8636. struct ggml_tensor * gate_s,
  8637. struct ggml_tensor * down,
  8638. struct ggml_tensor * down_b,
  8639. struct ggml_tensor * down_s,
  8640. struct ggml_tensor * act_scales,
  8641. llm_ffn_op_type type_op,
  8642. llm_ffn_gate_type type_gate,
  8643. const llm_build_cb & cb,
  8644. int il) {
  8645. struct ggml_tensor * tmp = up ? llm_build_lora_mm(lctx, ctx, up, cur) : cur;
  8646. cb(tmp, "ffn_up", il);
  8647. if (up_b) {
  8648. tmp = ggml_add(ctx, tmp, up_b);
  8649. cb(tmp, "ffn_up_b", il);
  8650. }
  8651. if (up_s) {
  8652. tmp = ggml_mul(ctx, tmp, up_s);
  8653. cb(tmp, "ffn_up_s", il);
  8654. }
  8655. if (gate) {
  8656. switch (type_gate) {
  8657. case LLM_FFN_SEQ:
  8658. {
  8659. cur = llm_build_lora_mm(lctx, ctx, gate, tmp);
  8660. cb(cur, "ffn_gate", il);
  8661. } break;
  8662. case LLM_FFN_PAR:
  8663. {
  8664. cur = llm_build_lora_mm(lctx, ctx, gate, cur);
  8665. cb(cur, "ffn_gate", il);
  8666. } break;
  8667. }
  8668. if (gate_b) {
  8669. cur = ggml_add(ctx, cur, gate_b);
  8670. cb(cur, "ffn_gate_b", il);
  8671. }
  8672. if (gate_s) {
  8673. cur = ggml_mul(ctx, cur, gate_s);
  8674. cb(cur, "ffn_gate_s", il);
  8675. }
  8676. } else {
  8677. cur = tmp;
  8678. }
  8679. switch (type_op) {
  8680. case LLM_FFN_SILU:
  8681. {
  8682. cur = ggml_silu(ctx, cur);
  8683. cb(cur, "ffn_silu", il);
  8684. } break;
  8685. case LLM_FFN_GELU:
  8686. {
  8687. cur = ggml_gelu(ctx, cur);
  8688. cb(cur, "ffn_gelu", il);
  8689. if (act_scales != NULL) {
  8690. cur = ggml_div(ctx, cur, act_scales);
  8691. cb(cur, "ffn_act", il);
  8692. }
  8693. } break;
  8694. case LLM_FFN_RELU:
  8695. {
  8696. cur = ggml_relu(ctx, cur);
  8697. cb(cur, "ffn_relu", il);
  8698. } break;
  8699. case LLM_FFN_RELU_SQR:
  8700. {
  8701. cur = ggml_relu(ctx, cur);
  8702. cb(cur, "ffn_relu", il);
  8703. cur = ggml_sqr(ctx, cur);
  8704. cb(cur, "ffn_sqr(relu)", il);
  8705. } break;
  8706. case LLM_FFN_SWIGLU:
  8707. {
  8708. // Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf
  8709. int64_t split_point = cur->ne[0] / 2;
  8710. struct ggml_tensor * x0 = ggml_cont(ctx, ggml_view_2d(ctx, cur, split_point, cur->ne[1], cur->nb[1], 0));
  8711. struct ggml_tensor * x1 = ggml_cont(ctx, ggml_view_2d(ctx, cur, split_point, cur->ne[1], cur->nb[1], split_point * ggml_element_size(cur)));
  8712. x0 = ggml_silu(ctx, x0);
  8713. cb(cur, "ffn_silu", il);
  8714. cur = ggml_mul(ctx, x0, x1);
  8715. cb(cur, "ffn_mul", il);
  8716. } break;
  8717. }
  8718. if (type_gate == LLM_FFN_PAR) {
  8719. cur = ggml_mul(ctx, cur, tmp);
  8720. cb(cur, "ffn_gate_par", il);
  8721. }
  8722. if (down) {
  8723. cur = llm_build_lora_mm(lctx, ctx, down, cur);
  8724. }
  8725. if (down_b) {
  8726. cb(cur, "ffn_down", il);
  8727. }
  8728. if (down_b) {
  8729. cur = ggml_add(ctx, cur, down_b);
  8730. }
  8731. if (down_s) {
  8732. cur = ggml_mul(ctx, cur, down_s);
  8733. cb(cur, "ffn_down_s", il);
  8734. }
  8735. return cur;
  8736. }
  8737. static struct ggml_tensor * llm_build_moe_ffn(
  8738. struct ggml_context * ctx,
  8739. struct llama_context & lctx,
  8740. struct ggml_tensor * cur,
  8741. struct ggml_tensor * gate_inp,
  8742. struct ggml_tensor * up_exps,
  8743. struct ggml_tensor * gate_exps,
  8744. struct ggml_tensor * down_exps,
  8745. int64_t n_expert,
  8746. int64_t n_expert_used,
  8747. llm_ffn_op_type type_op,
  8748. bool norm_w,
  8749. bool scale_w,
  8750. float w_scale,
  8751. const llm_build_cb & cb,
  8752. int il) {
  8753. int64_t n_embd = cur->ne[0];
  8754. int64_t n_tokens = cur->ne[1];
  8755. ggml_tensor * logits = llm_build_lora_mm(lctx, ctx, gate_inp, cur); // [n_expert, n_tokens]
  8756. cb(logits, "ffn_moe_logits", il);
  8757. ggml_tensor * probs = ggml_soft_max(ctx, logits); // [n_expert, n_tokens]
  8758. cb(probs, "ffn_moe_probs", il);
  8759. // select experts
  8760. ggml_tensor * selected_experts = ggml_top_k(ctx, probs, n_expert_used); // [n_expert_used, n_tokens]
  8761. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  8762. cb(selected_experts, "ffn_moe_topk", il);
  8763. ggml_tensor * weights = ggml_get_rows(ctx,
  8764. ggml_reshape_3d(ctx, probs, 1, n_expert, n_tokens), selected_experts); // [1, n_expert_used, n_tokens]
  8765. cb(weights, "ffn_moe_weights", il);
  8766. if (norm_w) {
  8767. weights = ggml_reshape_2d(ctx, weights, n_expert_used, n_tokens);
  8768. ggml_tensor * weights_sum = ggml_sum_rows(ctx, weights); // [1, n_tokens]
  8769. cb(weights_sum, "ffn_moe_weights_sum", il);
  8770. weights = ggml_div(ctx, weights, weights_sum); // [n_expert_used, n_tokens]
  8771. cb(weights, "ffn_moe_weights_norm", il);
  8772. weights = ggml_reshape_3d(ctx, weights, 1, n_expert_used, n_tokens);
  8773. }
  8774. if (scale_w) {
  8775. weights = ggml_scale(ctx, weights, w_scale);
  8776. cb(weights, "ffn_moe_weights_scaled", il);
  8777. }
  8778. cur = ggml_reshape_3d(ctx, cur, n_embd, 1, n_tokens);
  8779. ggml_tensor * up = llm_build_lora_mm_id(lctx, ctx, up_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  8780. cb(up, "ffn_moe_up", il);
  8781. ggml_tensor * gate = llm_build_lora_mm_id(lctx, ctx, gate_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  8782. cb(gate, "ffn_moe_gate", il);
  8783. switch (type_op) {
  8784. case LLM_FFN_SILU:
  8785. {
  8786. gate = ggml_silu(ctx, gate);
  8787. cb(gate, "ffn_moe_silu", il);
  8788. } break;
  8789. case LLM_FFN_GELU:
  8790. {
  8791. gate = ggml_gelu(ctx, gate);
  8792. cb(gate, "ffn_moe_gelu", il);
  8793. } break;
  8794. default:
  8795. GGML_ABORT("fatal error");
  8796. }
  8797. ggml_tensor * par = ggml_mul(ctx, up, gate); // [n_ff, n_expert_used, n_tokens]
  8798. cb(par, "ffn_moe_gate_par", il);
  8799. ggml_tensor * experts = llm_build_lora_mm_id(lctx, ctx, down_exps, par, selected_experts); // [n_embd, n_expert_used, n_tokens]
  8800. cb(experts, "ffn_moe_down", il);
  8801. experts = ggml_mul(ctx, experts, weights);
  8802. // aggregate experts
  8803. ggml_tensor * moe_out = nullptr;
  8804. for (int i = 0; i < n_expert_used; ++i) {
  8805. ggml_tensor * cur_expert = ggml_view_2d(ctx, experts, n_embd, n_tokens,
  8806. experts->nb[2], i*experts->nb[1]);
  8807. if (i == 0) {
  8808. moe_out = cur_expert;
  8809. } else {
  8810. moe_out = ggml_add(ctx, moe_out, cur_expert);
  8811. }
  8812. }
  8813. if (n_expert_used == 1) {
  8814. // avoid returning a non-contiguous tensor
  8815. moe_out = ggml_cont(ctx, moe_out);
  8816. }
  8817. return moe_out;
  8818. }
  8819. static struct ggml_tensor * llm_build_kqv(
  8820. struct ggml_context * ctx,
  8821. struct llama_context & lctx,
  8822. const llama_kv_cache & kv,
  8823. struct ggml_cgraph * graph,
  8824. struct ggml_tensor * wo,
  8825. struct ggml_tensor * wo_b,
  8826. struct ggml_tensor * q_cur,
  8827. struct ggml_tensor * kq_mask,
  8828. int32_t n_tokens,
  8829. int32_t n_kv,
  8830. float kq_scale,
  8831. const llm_build_cb & cb,
  8832. int il) {
  8833. const llama_model & model = lctx.model;
  8834. const llama_hparams & hparams = lctx.model.hparams;
  8835. const llama_cparams & cparams = lctx.cparams;
  8836. const int64_t n_ctx = cparams.n_ctx;
  8837. const int64_t n_head = hparams.n_head(il);
  8838. const int64_t n_head_kv = hparams.n_head_kv(il);
  8839. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  8840. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  8841. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  8842. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  8843. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  8844. cb(q, "q", il);
  8845. struct ggml_tensor * k =
  8846. ggml_view_3d(ctx, kv.k_l[il],
  8847. n_embd_head_k, n_kv, n_head_kv,
  8848. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  8849. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  8850. 0);
  8851. cb(k, "k", il);
  8852. struct ggml_tensor * cur;
  8853. if (cparams.flash_attn) {
  8854. GGML_UNUSED(model);
  8855. GGML_UNUSED(n_ctx);
  8856. // split cached v into n_head heads (not transposed)
  8857. struct ggml_tensor * v =
  8858. ggml_view_3d(ctx, kv.v_l[il],
  8859. n_embd_head_v, n_kv, n_head_kv,
  8860. ggml_row_size(kv.v_l[il]->type, n_embd_v_gqa),
  8861. ggml_row_size(kv.v_l[il]->type, n_embd_head_v),
  8862. 0);
  8863. cb(v, "v", il);
  8864. cur = ggml_flash_attn_ext(ctx, q, k, v, kq_mask, kq_scale, hparams.f_max_alibi_bias,
  8865. hparams.attn_soft_cap ? hparams.f_attn_logit_softcapping : 0.0f);
  8866. ggml_flash_attn_ext_set_prec(cur, GGML_PREC_F32);
  8867. cur = ggml_reshape_2d(ctx, cur, n_embd_head_v*n_head, n_tokens);
  8868. } else {
  8869. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  8870. cb(kq, "kq", il);
  8871. // note: this op tends to require high floating point range
  8872. // while for some models F16 is enough, for others it is not, so we default to F32 here
  8873. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  8874. if (model.arch == LLM_ARCH_GROK) {
  8875. // need to do the following:
  8876. // multiply by attn_output_multiplyer of 0.08838834764831845
  8877. // and then :
  8878. // kq = 30 * tanh(kq / 30)
  8879. // before the softmax below
  8880. kq = ggml_tanh(ctx, ggml_scale(ctx, kq, 0.08838834764831845f/30.0f));
  8881. kq = ggml_scale(ctx, kq, 30);
  8882. }
  8883. if (hparams.attn_soft_cap) {
  8884. kq = ggml_scale(ctx, kq, 1.0f / hparams.f_attn_logit_softcapping);
  8885. kq = ggml_tanh(ctx, kq);
  8886. kq = ggml_scale(ctx, kq, hparams.f_attn_logit_softcapping);
  8887. }
  8888. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_scale, hparams.f_max_alibi_bias);
  8889. cb(kq, "kq_soft_max_ext", il);
  8890. GGML_ASSERT(kv.size == n_ctx);
  8891. // split cached v into n_head heads
  8892. struct ggml_tensor * v =
  8893. ggml_view_3d(ctx, kv.v_l[il],
  8894. n_kv, n_embd_head_v, n_head_kv,
  8895. ggml_element_size(kv.v_l[il])*n_ctx,
  8896. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  8897. 0);
  8898. cb(v, "v", il);
  8899. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  8900. cb(kqv, "kqv", il);
  8901. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  8902. cb(kqv_merged, "kqv_merged", il);
  8903. cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_v*n_head, n_tokens);
  8904. cb(cur, "kqv_merged_cont", il);
  8905. }
  8906. ggml_build_forward_expand(graph, cur);
  8907. if (wo) {
  8908. cur = llm_build_lora_mm(lctx, ctx, wo, cur);
  8909. }
  8910. if (wo_b) {
  8911. cb(cur, "kqv_wo", il);
  8912. }
  8913. if (wo_b) {
  8914. cur = ggml_add(ctx, cur, wo_b);
  8915. }
  8916. return cur;
  8917. }
  8918. static struct ggml_tensor * llm_build_kv(
  8919. struct ggml_context * ctx,
  8920. struct llama_context & lctx,
  8921. const llama_kv_cache & kv,
  8922. struct ggml_cgraph * graph,
  8923. struct ggml_tensor * wo,
  8924. struct ggml_tensor * wo_b,
  8925. struct ggml_tensor * k_cur,
  8926. struct ggml_tensor * v_cur,
  8927. struct ggml_tensor * q_cur,
  8928. struct ggml_tensor * kq_mask,
  8929. int32_t n_tokens,
  8930. int32_t kv_head,
  8931. int32_t n_kv,
  8932. float kq_scale,
  8933. const llm_build_cb & cb,
  8934. int il) {
  8935. const llama_hparams & hparams = lctx.model.hparams;
  8936. const llama_cparams & cparams = lctx.cparams;
  8937. // these nodes are added to the graph together so that they are not reordered
  8938. // by doing so, the number of splits in the graph is reduced
  8939. ggml_build_forward_expand(graph, q_cur);
  8940. ggml_build_forward_expand(graph, k_cur);
  8941. ggml_build_forward_expand(graph, v_cur);
  8942. llm_build_kv_store(ctx, hparams, cparams, kv, graph, k_cur, v_cur, n_tokens, kv_head, cb, il);
  8943. struct ggml_tensor * cur;
  8944. cur = llm_build_kqv(ctx, lctx, kv, graph, wo, wo_b, q_cur, kq_mask, n_tokens, n_kv, kq_scale, cb, il);
  8945. cb(cur, "kqv_out", il);
  8946. return cur;
  8947. }
  8948. static struct ggml_tensor * llm_build_copy_mask_state(
  8949. struct ggml_context * ctx,
  8950. struct ggml_cgraph * graph,
  8951. struct ggml_tensor * s,
  8952. struct ggml_tensor * state_copy,
  8953. struct ggml_tensor * state_mask,
  8954. int32_t n_state,
  8955. int32_t kv_size,
  8956. int32_t kv_head,
  8957. int32_t n_kv,
  8958. int32_t n_seqs) {
  8959. struct ggml_tensor * states = ggml_reshape_2d(ctx, s, n_state, kv_size);
  8960. // copy states
  8961. // NOTE: assuming the copy destinations are ALL contained between kv_head and kv_head + n_kv
  8962. // this shrinks the tensors's ne[1] to n_kv
  8963. states = ggml_get_rows(ctx, states, state_copy);
  8964. // clear states of sequences which are starting at the beginning of this batch
  8965. // FIXME: zero-out NANs?
  8966. states = ggml_mul(ctx, states, state_mask);
  8967. // copy states which won't be changed further (between n_seqs and n_kv)
  8968. ggml_build_forward_expand(graph,
  8969. ggml_cpy(ctx,
  8970. ggml_view_1d(ctx, states, n_state*(n_kv - n_seqs), n_seqs*n_state*ggml_element_size(states)),
  8971. ggml_view_1d(ctx, s, n_state*(n_kv - n_seqs), (kv_head + n_seqs)*n_state*ggml_element_size(s))));
  8972. // the part of the states that will be used and modified
  8973. return ggml_view_2d(ctx, states, n_state, n_seqs, states->nb[1], 0);
  8974. }
  8975. // TODO: split
  8976. static struct ggml_tensor * llm_build_mamba(
  8977. struct ggml_context * ctx,
  8978. struct llama_context & lctx,
  8979. const llama_ubatch & batch,
  8980. struct ggml_cgraph * graph,
  8981. struct ggml_tensor * cur,
  8982. struct ggml_tensor * state_copy,
  8983. struct ggml_tensor * state_mask,
  8984. int32_t kv_head,
  8985. int32_t n_kv,
  8986. const llm_build_cb & cb,
  8987. int il) {
  8988. const llama_model & model = lctx.model;
  8989. const llama_hparams & hparams = model.hparams;
  8990. const llama_kv_cache & kv = lctx.kv_self;
  8991. const int64_t d_conv = hparams.ssm_d_conv;
  8992. const int64_t d_inner = hparams.ssm_d_inner;
  8993. const int64_t d_state = hparams.ssm_d_state;
  8994. const int64_t dt_rank = hparams.ssm_dt_rank;
  8995. const int64_t n_seqs = batch.n_seqs;
  8996. // Some variants of Mamba arch (e.g. FalconMamba do apply layer norm on B and Dt layers)
  8997. const bool ssm_dt_b_c_rms = hparams.ssm_dt_b_c_rms;
  8998. // Use the same RMS norm as the final layer norm
  8999. const float norm_rms_eps = hparams.f_norm_rms_eps;
  9000. const int64_t n_seq_tokens = batch.n_seq_tokens;
  9001. GGML_ASSERT(n_seqs != 0);
  9002. GGML_ASSERT(batch.equal_seqs);
  9003. GGML_ASSERT(batch.n_tokens == n_seq_tokens * n_seqs);
  9004. struct ggml_tensor * conv_states_all = kv.k_l[il];
  9005. struct ggml_tensor * ssm_states_all = kv.v_l[il];
  9006. // (ab)using the KV cache to store the states
  9007. struct ggml_tensor * conv = llm_build_copy_mask_state(ctx,
  9008. graph, conv_states_all, state_copy, state_mask,
  9009. hparams.n_embd_k_s(), kv.size, kv_head, n_kv, n_seqs);
  9010. conv = ggml_reshape_3d(ctx, conv, d_conv - 1, d_inner, n_seqs);
  9011. struct ggml_tensor * ssm = llm_build_copy_mask_state(ctx,
  9012. graph, ssm_states_all, state_copy, state_mask,
  9013. hparams.n_embd_v_s(), kv.size, kv_head, n_kv, n_seqs);
  9014. ssm = ggml_reshape_3d(ctx, ssm, d_state, d_inner, n_seqs);
  9015. // {n_embd, n_tokens} => {n_embd, n_seq_tokens, n_seqs}
  9016. cur = ggml_reshape_3d(ctx, cur, cur->ne[0], n_seq_tokens, n_seqs);
  9017. // {n_embd, 2*d_inner} @ {n_embd, n_seq_tokens, n_seqs} => {2*d_inner, n_seq_tokens, n_seqs}
  9018. struct ggml_tensor * xz = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_in, cur);
  9019. // split the above in two
  9020. // => {d_inner, n_seq_tokens, n_seqs}
  9021. struct ggml_tensor * x = ggml_view_3d(ctx, xz, d_inner, xz->ne[1], xz->ne[2], xz->nb[1], xz->nb[2], 0);
  9022. struct ggml_tensor * z = ggml_view_3d(ctx, xz, d_inner, xz->ne[1], xz->ne[2], xz->nb[1], xz->nb[2], d_inner*ggml_element_size(xz));
  9023. // conv
  9024. {
  9025. // => {d_conv - 1 + n_seq_tokens, d_inner, n_seqs}
  9026. struct ggml_tensor * conv_x = ggml_concat(ctx, conv, ggml_transpose(ctx, x), 0);
  9027. // copy last (d_conv - 1) columns back into the state cache
  9028. struct ggml_tensor * last_conv = ggml_view_3d(ctx, conv_x, d_conv - 1, d_inner, n_seqs, conv_x->nb[1], conv_x->nb[2], n_seq_tokens*(conv_x->nb[0]));
  9029. ggml_build_forward_expand(graph,
  9030. ggml_cpy(ctx, last_conv,
  9031. ggml_view_1d(ctx, conv_states_all,
  9032. (d_conv - 1)*(d_inner)*(n_seqs),
  9033. kv_head*(d_conv - 1)*(d_inner)*ggml_element_size(conv_states_all))));
  9034. // 1D convolution
  9035. // The equivalent is to make a self-overlapping view of conv_x
  9036. // over d_conv columns at each stride in the 3rd dimension,
  9037. // then element-wise multiply that with the conv1d weight,
  9038. // then sum the elements of each row,
  9039. // (the last two steps are a dot product over rows (also doable with mul_mat))
  9040. // then permute away the ne[0] dimension,
  9041. // and then you're left with the resulting x tensor.
  9042. // For simultaneous sequences, all sequences need to have the same length.
  9043. x = ggml_ssm_conv(ctx, conv_x, model.layers[il].ssm_conv1d);
  9044. // bias
  9045. x = ggml_add(ctx, x, model.layers[il].ssm_conv1d_b);
  9046. x = ggml_silu(ctx, x);
  9047. }
  9048. // ssm
  9049. {
  9050. // {d_inner, dt_rank + 2*d_state} @ {d_inner, n_seq_tokens, n_seqs} => {dt_rank + 2*d_state, n_seq_tokens, n_seqs}
  9051. struct ggml_tensor * x_db = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_x, x);
  9052. // split
  9053. struct ggml_tensor * dt = ggml_view_3d(ctx, x_db, dt_rank, n_seq_tokens, n_seqs, x_db->nb[1], x_db->nb[2], 0);
  9054. struct ggml_tensor * B = ggml_view_3d(ctx, x_db, d_state, n_seq_tokens, n_seqs, x_db->nb[1], x_db->nb[2], ggml_element_size(x_db)*dt_rank);
  9055. struct ggml_tensor * C = ggml_view_3d(ctx, x_db, d_state, n_seq_tokens, n_seqs, x_db->nb[1], x_db->nb[2], ggml_element_size(x_db)*(dt_rank+d_state));
  9056. // Some Mamba variants (e.g. FalconMamba) apply RMS norm in B, C & Dt layers
  9057. if (ssm_dt_b_c_rms) {
  9058. dt = ggml_rms_norm(ctx, dt, norm_rms_eps);
  9059. B = ggml_rms_norm(ctx, B, norm_rms_eps);
  9060. C = ggml_rms_norm(ctx, C, norm_rms_eps);
  9061. }
  9062. // {dt_rank, d_inner} @ {dt_rank, n_seq_tokens, n_seqs} => {d_inner, n_seq_tokens, n_seqs}
  9063. dt = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_dt, dt);
  9064. dt = ggml_add(ctx, dt, model.layers[il].ssm_dt_b);
  9065. // Custom operator to optimize the parallel associative scan
  9066. // as described in the Annex D of the Mamba paper.
  9067. // => {d_inner, n_seq_tokens, n_seqs} and {d_state, d_inner, n_seqs}
  9068. struct ggml_tensor * y_ssm = ggml_ssm_scan(ctx, ssm, x, dt, model.layers[il].ssm_a, B, C);
  9069. // store last states
  9070. ggml_build_forward_expand(graph,
  9071. ggml_cpy(ctx,
  9072. ggml_view_1d(ctx, y_ssm, d_state*d_inner*n_seqs, x->nb[3]),
  9073. ggml_view_1d(ctx, ssm_states_all, d_state*d_inner*n_seqs, kv_head*d_state*d_inner*ggml_element_size(ssm_states_all))));
  9074. struct ggml_tensor * y = ggml_view_3d(ctx, y_ssm, d_inner, n_seq_tokens, n_seqs, x->nb[1], x->nb[2], 0);
  9075. // TODO: skip computing output earlier for unused tokens
  9076. // {d_inner, n_seq_tokens, n_seqs} * {d_inner} => {d_inner, n_seq_tokens, n_seqs}
  9077. y = ggml_add(ctx, y, ggml_mul(ctx, x, model.layers[il].ssm_d));
  9078. y = ggml_mul(ctx, y, ggml_silu(ctx, ggml_cont(ctx, z)));
  9079. // {d_inner, n_embd} @ {d_inner, n_seq_tokens, n_seqs} => {n_embd, n_seq_tokens, n_seqs}
  9080. cur = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_out, y);
  9081. }
  9082. // {n_embd, n_seq_tokens, n_seqs} => {n_embd, n_tokens}
  9083. cur = ggml_reshape_2d(ctx, cur, cur->ne[0], n_seq_tokens * n_seqs);
  9084. cb(cur, "mamba_out", il);
  9085. return cur;
  9086. }
  9087. static struct ggml_tensor * llm_build_rwkv6_time_mix(
  9088. struct llama_context & lctx,
  9089. struct ggml_context * ctx,
  9090. const struct llama_layer * layer,
  9091. struct ggml_tensor * cur,
  9092. struct ggml_tensor * x_prev,
  9093. struct ggml_tensor ** wkv_state) {
  9094. size_t n_embd = cur->ne[0];
  9095. size_t n_seq_tokens = cur->ne[1];
  9096. size_t n_seqs = cur->ne[2];
  9097. size_t head_size = layer->time_mix_first->ne[0];
  9098. size_t head_count = layer->time_mix_first->ne[1];
  9099. size_t n_tokens = n_seqs * n_seq_tokens;
  9100. struct ggml_tensor * sx = ggml_sub(ctx, x_prev, cur);
  9101. sx = ggml_reshape_2d(ctx, sx, n_embd, n_tokens);
  9102. cur = ggml_reshape_2d(ctx, cur, n_embd, n_tokens);
  9103. struct ggml_tensor * xxx = ggml_add(ctx, ggml_mul(ctx, sx, layer->time_mix_lerp_x), cur);
  9104. xxx = ggml_reshape_4d(
  9105. ctx,
  9106. ggml_tanh(
  9107. ctx,
  9108. ggml_mul_mat(ctx, layer->time_mix_w1, xxx)
  9109. ),
  9110. layer->time_mix_w1->ne[1] / 5, 1, 5, n_tokens
  9111. );
  9112. xxx = ggml_cont(ctx, ggml_permute(ctx, xxx, 0, 1, 3, 2));
  9113. xxx = ggml_mul_mat(
  9114. ctx,
  9115. ggml_reshape_4d(
  9116. ctx,
  9117. layer->time_mix_w2,
  9118. layer->time_mix_w2->ne[0], layer->time_mix_w2->ne[1], 1, 5
  9119. ),
  9120. xxx
  9121. );
  9122. struct ggml_tensor *mw = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], 0);
  9123. struct ggml_tensor *mk = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * sizeof(float));
  9124. struct ggml_tensor *mv = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * 2 * sizeof(float));
  9125. struct ggml_tensor *mr = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * 3 * sizeof(float));
  9126. struct ggml_tensor *mg = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * 4 * sizeof(float));
  9127. struct ggml_tensor * xw = ggml_add(
  9128. ctx,
  9129. ggml_mul(
  9130. ctx,
  9131. ggml_add(ctx, mw, layer->time_mix_lerp_w),
  9132. sx
  9133. ),
  9134. cur
  9135. );
  9136. struct ggml_tensor * xk = ggml_add(
  9137. ctx,
  9138. ggml_mul(
  9139. ctx,
  9140. ggml_add(ctx, mk, layer->time_mix_lerp_k),
  9141. sx
  9142. ),
  9143. cur
  9144. );
  9145. struct ggml_tensor * xv = ggml_add(
  9146. ctx,
  9147. ggml_mul(
  9148. ctx,
  9149. ggml_add(ctx, mv, layer->time_mix_lerp_v),
  9150. sx
  9151. ),
  9152. cur
  9153. );
  9154. struct ggml_tensor * xr = ggml_add(
  9155. ctx,
  9156. ggml_mul(
  9157. ctx,
  9158. ggml_add(ctx, mr, layer->time_mix_lerp_r),
  9159. sx
  9160. ),
  9161. cur
  9162. );
  9163. struct ggml_tensor * xg = ggml_add(
  9164. ctx,
  9165. ggml_mul(
  9166. ctx,
  9167. ggml_add(ctx, mg, layer->time_mix_lerp_g),
  9168. sx
  9169. ),
  9170. cur
  9171. );
  9172. struct ggml_tensor * r = ggml_reshape_4d(ctx, llm_build_lora_mm(lctx, ctx, layer->time_mix_receptance, xr), head_size, 1, head_count, n_tokens);
  9173. struct ggml_tensor * k = ggml_reshape_4d(ctx, llm_build_lora_mm(lctx, ctx, layer->time_mix_key, xk), 1, head_size, head_count, n_tokens);
  9174. struct ggml_tensor * v = ggml_reshape_4d(ctx, llm_build_lora_mm(lctx, ctx, layer->time_mix_value, xv), head_size, 1, head_count, n_tokens);
  9175. struct ggml_tensor * g = ggml_silu(
  9176. ctx,
  9177. llm_build_lora_mm(lctx, ctx, layer->time_mix_gate, xg)
  9178. );
  9179. struct ggml_tensor * w = ggml_mul_mat(
  9180. ctx,
  9181. layer->time_mix_decay_w2,
  9182. ggml_tanh(
  9183. ctx,
  9184. ggml_mul_mat(ctx, layer->time_mix_decay_w1, xw)
  9185. )
  9186. );
  9187. w = ggml_add(ctx, w, ggml_reshape_1d(ctx, layer->time_mix_decay, n_embd));
  9188. w = ggml_exp(ctx, ggml_neg(ctx, ggml_exp(ctx, w)));
  9189. w = ggml_reshape_4d(ctx, w, 1, head_size, head_count, n_tokens);
  9190. k = ggml_transpose(ctx, k);
  9191. v = ggml_transpose(ctx, v);
  9192. r = ggml_transpose(ctx, r);
  9193. struct ggml_tensor * wkv_output = ggml_rwkv_wkv6(ctx, k, v, r, layer->time_mix_first, w, *wkv_state);
  9194. cur = ggml_view_1d(ctx, wkv_output, n_embd * n_tokens, 0);
  9195. *wkv_state = ggml_view_1d(ctx, wkv_output, n_embd * head_size * n_seqs, n_embd * n_tokens * sizeof(float));
  9196. // group norm with head_count groups
  9197. cur = ggml_reshape_3d(ctx, cur, n_embd / head_count, head_count, n_tokens);
  9198. cur = ggml_norm(ctx, cur, 64e-5f);
  9199. // Convert back to regular vectors.
  9200. cur = ggml_reshape_2d(ctx, cur, n_embd, n_tokens);
  9201. cur = ggml_add(ctx, ggml_mul(ctx, cur, layer->time_mix_ln), layer->time_mix_ln_b);
  9202. cur = ggml_mul(ctx, cur, g);
  9203. cur = llm_build_lora_mm(lctx, ctx, layer->time_mix_output, cur);
  9204. return ggml_reshape_3d(ctx, cur, n_embd, n_seq_tokens, n_seqs);
  9205. }
  9206. static struct ggml_tensor * llm_build_rwkv6_channel_mix(
  9207. struct llama_context & lctx,
  9208. struct ggml_context * ctx,
  9209. const struct llama_layer * layer,
  9210. struct ggml_tensor * cur,
  9211. struct ggml_tensor * x_prev) {
  9212. struct ggml_tensor * sx = ggml_sub(ctx, x_prev, cur);
  9213. struct ggml_tensor * xk = ggml_add(ctx, ggml_mul(ctx, sx, layer->channel_mix_lerp_k), cur);
  9214. struct ggml_tensor * xr = ggml_add(ctx, ggml_mul(ctx, sx, layer->channel_mix_lerp_r), cur);
  9215. struct ggml_tensor * r = ggml_sigmoid(ctx, llm_build_lora_mm(lctx, ctx, layer->channel_mix_receptance, xr));
  9216. struct ggml_tensor * k = ggml_sqr(
  9217. ctx,
  9218. ggml_relu(
  9219. ctx,
  9220. llm_build_lora_mm(lctx, ctx, layer->channel_mix_key, xk)
  9221. )
  9222. );
  9223. return ggml_mul(ctx, r, llm_build_lora_mm(lctx, ctx, layer->channel_mix_value, k));
  9224. }
  9225. struct llm_build_context {
  9226. const llama_model & model;
  9227. llama_context & lctx;
  9228. const llama_hparams & hparams;
  9229. const llama_cparams & cparams;
  9230. const llama_ubatch & ubatch;
  9231. const llama_kv_cache & kv_self;
  9232. const int64_t n_embd;
  9233. const int64_t n_layer;
  9234. const int64_t n_rot;
  9235. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  9236. const int64_t n_head;
  9237. const int64_t n_head_kv;
  9238. const int64_t n_embd_head_k;
  9239. const int64_t n_embd_k_gqa;
  9240. const int64_t n_embd_head_v;
  9241. const int64_t n_embd_v_gqa;
  9242. const int64_t n_expert;
  9243. const int64_t n_expert_used;
  9244. const float freq_base;
  9245. const float freq_scale;
  9246. const float ext_factor;
  9247. const float attn_factor;
  9248. const float beta_fast;
  9249. const float beta_slow;
  9250. const float norm_eps;
  9251. const float norm_rms_eps;
  9252. const int32_t n_tokens;
  9253. const int32_t n_kv; // size of KV cache to consider (n_kv <= kv_self.size)
  9254. const int32_t n_outputs;
  9255. const int32_t n_outputs_enc;
  9256. const int32_t kv_head; // index of where we store new KV data in the cache
  9257. const int32_t n_ctx_orig;
  9258. const bool flash_attn;
  9259. const enum llama_pooling_type pooling_type;
  9260. const enum llama_rope_type rope_type;
  9261. const llm_build_cb & cb;
  9262. std::vector<uint8_t> & buf_compute_meta;
  9263. struct ggml_context * ctx0 = nullptr;
  9264. // TODO: consider making the entire interface noexcept
  9265. llm_build_context(
  9266. llama_context & lctx,
  9267. const llama_ubatch & ubatch,
  9268. const llm_build_cb & cb,
  9269. bool worst_case) :
  9270. model (lctx.model),
  9271. lctx (lctx),
  9272. hparams (model.hparams),
  9273. cparams (lctx.cparams),
  9274. ubatch (ubatch),
  9275. kv_self (lctx.kv_self),
  9276. n_embd (hparams.n_embd),
  9277. n_layer (hparams.n_layer),
  9278. n_rot (hparams.n_rot),
  9279. n_ctx (cparams.n_ctx),
  9280. n_head (hparams.n_head()),
  9281. n_head_kv (hparams.n_head_kv()),
  9282. n_embd_head_k (hparams.n_embd_head_k),
  9283. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  9284. n_embd_head_v (hparams.n_embd_head_v),
  9285. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  9286. n_expert (hparams.n_expert),
  9287. n_expert_used (hparams.n_expert_used),
  9288. freq_base (cparams.rope_freq_base),
  9289. freq_scale (cparams.rope_freq_scale),
  9290. ext_factor (cparams.yarn_ext_factor),
  9291. attn_factor (cparams.yarn_attn_factor),
  9292. beta_fast (cparams.yarn_beta_fast),
  9293. beta_slow (cparams.yarn_beta_slow),
  9294. norm_eps (hparams.f_norm_eps),
  9295. norm_rms_eps (hparams.f_norm_rms_eps),
  9296. n_tokens (ubatch.n_tokens),
  9297. n_kv (worst_case ? kv_self.size : kv_self.n),
  9298. n_outputs (worst_case ? n_tokens : lctx.n_outputs),
  9299. n_outputs_enc (worst_case ? n_tokens : lctx.embd_enc.size() / hparams.n_embd),
  9300. kv_head (worst_case ? (kv_self.recurrent ? 0 : kv_self.size - n_tokens) : kv_self.head),
  9301. n_ctx_orig (cparams.n_ctx_orig_yarn),
  9302. flash_attn (cparams.flash_attn),
  9303. pooling_type (cparams.pooling_type),
  9304. rope_type (hparams.rope_type),
  9305. cb (cb),
  9306. buf_compute_meta (lctx.buf_compute_meta) {
  9307. // all initializations should be done in init()
  9308. }
  9309. void init() {
  9310. struct ggml_init_params params = {
  9311. /*.mem_size =*/ buf_compute_meta.size(),
  9312. /*.mem_buffer =*/ buf_compute_meta.data(),
  9313. /*.no_alloc =*/ true,
  9314. };
  9315. ctx0 = ggml_init(params);
  9316. lctx.inp_tokens = nullptr;
  9317. lctx.inp_embd = nullptr;
  9318. lctx.inp_pos = nullptr;
  9319. lctx.inp_out_ids = nullptr;
  9320. lctx.inp_KQ_mask = nullptr;
  9321. lctx.inp_KQ_mask_swa = nullptr;
  9322. lctx.inp_K_shift = nullptr;
  9323. lctx.inp_mean = nullptr;
  9324. lctx.inp_cls = nullptr;
  9325. lctx.inp_s_copy = nullptr;
  9326. lctx.inp_s_mask = nullptr;
  9327. lctx.inp_s_seq = nullptr;
  9328. lctx.inp_pos_bucket = nullptr;
  9329. lctx.inp_embd_enc = nullptr;
  9330. lctx.inp_KQ_mask_cross = nullptr;
  9331. lctx.inp_cross_attn_state = nullptr;
  9332. }
  9333. void free() {
  9334. ggml_free(ctx0);
  9335. ctx0 = nullptr;
  9336. }
  9337. struct ggml_cgraph * build_k_shift() {
  9338. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9339. GGML_ASSERT(kv_self.size == n_ctx);
  9340. lctx.inp_K_shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_ctx);
  9341. cb(lctx.inp_K_shift, "K_shift", -1);
  9342. ggml_set_input(lctx.inp_K_shift);
  9343. for (int il = 0; il < n_layer; ++il) {
  9344. const int64_t n_head_kv = hparams.n_head_kv(il);
  9345. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  9346. struct ggml_tensor * rope_factors = build_rope_factors(il);
  9347. struct ggml_tensor * k =
  9348. ggml_view_3d(ctx0, kv_self.k_l[il],
  9349. n_embd_head_k, n_head_kv, n_ctx,
  9350. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  9351. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  9352. 0);
  9353. struct ggml_tensor * tmp;
  9354. if (ggml_is_quantized(k->type)) {
  9355. // dequantize to f32 -> RoPE -> quantize back
  9356. tmp = ggml_cast(ctx0, k, GGML_TYPE_F32);
  9357. cb(tmp, "K_f32", il);
  9358. for (auto & backend : lctx.backends) {
  9359. // Figure out which backend KV cache belongs to
  9360. if (ggml_backend_supports_buft(backend.get(), ggml_backend_buffer_get_type(kv_self.k_l[il]->buffer))) {
  9361. ggml_backend_sched_set_tensor_backend(lctx.sched.get(), tmp, backend.get());
  9362. break;
  9363. }
  9364. }
  9365. tmp = ggml_rope_ext_inplace(ctx0, tmp,
  9366. lctx.inp_K_shift, rope_factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9367. ext_factor, attn_factor, beta_fast, beta_slow);
  9368. cb(tmp, "K_shifted_f32", il);
  9369. tmp = ggml_cpy(ctx0, tmp, k);
  9370. } else {
  9371. // we rotate only the first n_rot dimensions
  9372. tmp = ggml_rope_ext_inplace(ctx0, k,
  9373. lctx.inp_K_shift, rope_factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9374. ext_factor, attn_factor, beta_fast, beta_slow);
  9375. }
  9376. cb(tmp, "K_shifted", il);
  9377. ggml_build_forward_expand(gf, tmp);
  9378. }
  9379. return gf;
  9380. }
  9381. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  9382. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9383. for (uint32_t i = 0; i < ids.size(); ++i) {
  9384. const uint32_t id = ids[i];
  9385. if (i == id || id == ids.size()) {
  9386. continue;
  9387. }
  9388. uint32_t nm = 1;
  9389. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  9390. nm++;
  9391. }
  9392. for (int il = 0; il < n_layer; ++il) {
  9393. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  9394. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  9395. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  9396. n_embd_k_gqa, nm,
  9397. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  9398. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  9399. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  9400. n_embd_k_gqa, nm,
  9401. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  9402. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  9403. ggml_tensor * view_v_src;
  9404. ggml_tensor * view_v_dst;
  9405. if (flash_attn) {
  9406. // NOTE: the V cache is not transposed when using flash attention
  9407. view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  9408. n_embd_v_gqa, nm,
  9409. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa),
  9410. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*i));
  9411. view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  9412. n_embd_v_gqa, nm,
  9413. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa),
  9414. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*id));
  9415. } else {
  9416. view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  9417. nm, n_embd_v_gqa,
  9418. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  9419. ggml_row_size(kv_self.v_l[il]->type, i));
  9420. view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  9421. nm, n_embd_v_gqa,
  9422. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  9423. ggml_row_size(kv_self.v_l[il]->type, id));
  9424. }
  9425. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  9426. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  9427. }
  9428. i += nm - 1;
  9429. }
  9430. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  9431. return gf;
  9432. }
  9433. struct ggml_tensor * build_inp_pos() {
  9434. lctx.inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  9435. cb(lctx.inp_pos, "inp_pos", -1);
  9436. ggml_set_input(lctx.inp_pos);
  9437. return lctx.inp_pos;
  9438. }
  9439. struct ggml_tensor * build_rope_factors(int il) {
  9440. // choose long/short freq factors based on the context size
  9441. const auto n_ctx_pre_seq = cparams.n_ctx / cparams.n_seq_max;
  9442. if (model.layers[il].rope_freqs != nullptr) {
  9443. return model.layers[il].rope_freqs;
  9444. }
  9445. if (n_ctx_pre_seq > hparams.n_ctx_orig_yarn) {
  9446. return model.layers[il].rope_long;
  9447. }
  9448. return model.layers[il].rope_short;
  9449. }
  9450. struct ggml_tensor * build_inp_out_ids() {
  9451. lctx.inp_out_ids = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_outputs);
  9452. cb(lctx.inp_out_ids, "inp_out_ids", -1);
  9453. ggml_set_input(lctx.inp_out_ids);
  9454. return lctx.inp_out_ids;
  9455. }
  9456. struct ggml_tensor * build_inp_KQ_mask(bool causal = true) {
  9457. lctx.inp_KQ_mask = causal
  9458. ? ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD))
  9459. : ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  9460. cb(lctx.inp_KQ_mask, "KQ_mask", -1);
  9461. ggml_set_input(lctx.inp_KQ_mask);
  9462. return flash_attn ? ggml_cast(ctx0, lctx.inp_KQ_mask, GGML_TYPE_F16) : lctx.inp_KQ_mask;
  9463. }
  9464. struct ggml_tensor * build_inp_KQ_mask_swa(bool causal = true) {
  9465. GGML_ASSERT(hparams.n_swa > 0);
  9466. lctx.inp_KQ_mask_swa = causal
  9467. ? ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD))
  9468. : ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  9469. cb(lctx.inp_KQ_mask_swa, "KQ_mask_swa", -1);
  9470. ggml_set_input(lctx.inp_KQ_mask_swa);
  9471. return flash_attn ? ggml_cast(ctx0, lctx.inp_KQ_mask_swa, GGML_TYPE_F16) : lctx.inp_KQ_mask_swa;
  9472. }
  9473. struct ggml_tensor * build_inp_mean() {
  9474. lctx.inp_mean = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  9475. cb(lctx.inp_mean, "inp_mean", -1);
  9476. ggml_set_input(lctx.inp_mean);
  9477. return lctx.inp_mean;
  9478. }
  9479. struct ggml_tensor * build_inp_cls() {
  9480. lctx.inp_cls = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  9481. cb(lctx.inp_cls, "inp_cls", -1);
  9482. ggml_set_input(lctx.inp_cls);
  9483. return lctx.inp_cls;
  9484. }
  9485. struct ggml_tensor * build_inp_s_copy() {
  9486. lctx.inp_s_copy = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_kv);
  9487. cb(lctx.inp_s_copy, "inp_s_copy", -1);
  9488. ggml_set_input(lctx.inp_s_copy);
  9489. return lctx.inp_s_copy;
  9490. }
  9491. struct ggml_tensor * build_inp_s_mask() {
  9492. lctx.inp_s_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_kv);
  9493. cb(lctx.inp_s_mask, "inp_s_mask", -1);
  9494. ggml_set_input(lctx.inp_s_mask);
  9495. return lctx.inp_s_mask;
  9496. }
  9497. struct ggml_cgraph * append_pooling(struct ggml_cgraph * gf) {
  9498. // find result_norm tensor for input
  9499. struct ggml_tensor * inp = nullptr;
  9500. for (int i = ggml_graph_n_nodes(gf) - 1; i >= 0; --i) {
  9501. inp = ggml_graph_node(gf, i);
  9502. if (strcmp(inp->name, "result_norm") == 0 || strcmp(inp->name, "result_embd") == 0) {
  9503. break;
  9504. } else {
  9505. inp = nullptr;
  9506. }
  9507. }
  9508. GGML_ASSERT(inp != nullptr && "missing result_norm/result_embd tensor");
  9509. struct ggml_tensor * cur;
  9510. switch (pooling_type) {
  9511. case LLAMA_POOLING_TYPE_NONE:
  9512. {
  9513. cur = inp;
  9514. } break;
  9515. case LLAMA_POOLING_TYPE_MEAN:
  9516. {
  9517. struct ggml_tensor * inp_mean = build_inp_mean();
  9518. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, inp)), inp_mean);
  9519. } break;
  9520. case LLAMA_POOLING_TYPE_CLS:
  9521. case LLAMA_POOLING_TYPE_LAST:
  9522. {
  9523. struct ggml_tensor * inp_cls = build_inp_cls();
  9524. cur = ggml_get_rows(ctx0, inp, inp_cls);
  9525. } break;
  9526. case LLAMA_POOLING_TYPE_RANK:
  9527. {
  9528. struct ggml_tensor * inp_cls = build_inp_cls();
  9529. inp = ggml_get_rows(ctx0, inp, inp_cls);
  9530. // classification head
  9531. // https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/roberta/modeling_roberta.py#L1566
  9532. GGML_ASSERT(model.cls != nullptr);
  9533. GGML_ASSERT(model.cls_b != nullptr);
  9534. cur = ggml_add (ctx0, ggml_mul_mat(ctx0, model.cls, inp), model.cls_b);
  9535. cur = ggml_tanh(ctx0, cur);
  9536. // some models don't have `cls_out`, for example: https://huggingface.co/jinaai/jina-reranker-v1-tiny-en
  9537. // https://huggingface.co/jinaai/jina-reranker-v1-tiny-en/blob/cb5347e43979c3084a890e3f99491952603ae1b7/modeling_bert.py#L884-L896
  9538. if (model.cls_out) {
  9539. GGML_ASSERT(model.cls_out_b != nullptr);
  9540. cur = ggml_add (ctx0, ggml_mul_mat(ctx0, model.cls_out, cur), model.cls_out_b);
  9541. }
  9542. } break;
  9543. default:
  9544. {
  9545. GGML_ABORT("unknown pooling type");
  9546. }
  9547. }
  9548. cb(cur, "result_embd_pooled", -1);
  9549. ggml_build_forward_expand(gf, cur);
  9550. return gf;
  9551. }
  9552. struct ggml_tensor * llm_build_pos_bucket(bool causal) {
  9553. if (causal) {
  9554. lctx.inp_pos_bucket = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  9555. } else {
  9556. lctx.inp_pos_bucket = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_tokens);
  9557. }
  9558. ggml_set_input(lctx.inp_pos_bucket);
  9559. cb(lctx.inp_pos_bucket, "pos_bucket", -1);
  9560. return lctx.inp_pos_bucket;
  9561. }
  9562. struct ggml_tensor * llm_build_pos_bias(struct ggml_tensor * pos_bucket, struct ggml_tensor * attn_rel_b) {
  9563. struct ggml_tensor * pos_bucket_1d = ggml_view_1d(ctx0, pos_bucket, pos_bucket->ne[0] * pos_bucket->ne[1], 0);
  9564. cb(pos_bucket_1d, "pos_bucket_1d", -1);
  9565. struct ggml_tensor * pos_bias = ggml_get_rows(ctx0, attn_rel_b, pos_bucket_1d);
  9566. cb(pos_bias, "pos_bias", -1);
  9567. pos_bias = ggml_view_3d(ctx0, pos_bias, pos_bias->ne[0], lctx.inp_pos_bucket->ne[0], lctx.inp_pos_bucket->ne[1], ggml_element_size(pos_bias) * pos_bias->ne[0], ggml_element_size(pos_bias) * pos_bias->ne[0] * lctx.inp_pos_bucket->ne[0], 0);
  9568. cb(pos_bias, "pos_bias", -1);
  9569. pos_bias = ggml_permute(ctx0, pos_bias, 2, 0, 1, 3);
  9570. cb(pos_bias, "pos_bias", -1);
  9571. pos_bias = ggml_cont(ctx0, pos_bias);
  9572. cb(pos_bias, "pos_bias", -1);
  9573. return pos_bias;
  9574. }
  9575. struct ggml_tensor * llm_build_inp_embd_enc() {
  9576. const int64_t n_embd = hparams.n_embd;
  9577. lctx.inp_embd_enc = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, n_outputs_enc);
  9578. ggml_set_input(lctx.inp_embd_enc);
  9579. cb(lctx.inp_embd_enc, "embd_enc", -1);
  9580. return lctx.inp_embd_enc;
  9581. }
  9582. struct ggml_tensor * llm_build_inp_KQ_mask_cross() {
  9583. lctx.inp_KQ_mask_cross = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_outputs_enc, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  9584. ggml_set_input(lctx.inp_KQ_mask_cross);
  9585. cb(lctx.inp_KQ_mask_cross, "KQ_mask_cross", -1);
  9586. return lctx.inp_KQ_mask_cross;
  9587. }
  9588. struct ggml_cgraph * build_llama() {
  9589. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9590. // mutable variable, needed during the last layer of the computation to skip unused tokens
  9591. int32_t n_tokens = this->n_tokens;
  9592. const int64_t n_embd_head = hparams.n_embd_head_v;
  9593. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9594. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9595. struct ggml_tensor * cur;
  9596. struct ggml_tensor * inpL;
  9597. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  9598. // inp_pos - contains the positions
  9599. struct ggml_tensor * inp_pos = build_inp_pos();
  9600. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9601. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9602. const float kq_scale = hparams.f_attention_scale == 0.0f ? 1.0f/sqrtf(float(n_embd_head)) : hparams.f_attention_scale;
  9603. for (int il = 0; il < n_layer; ++il) {
  9604. struct ggml_tensor * inpSA = inpL;
  9605. // norm
  9606. cur = llm_build_norm(ctx0, inpL, hparams,
  9607. model.layers[il].attn_norm, NULL,
  9608. LLM_NORM_RMS, cb, il);
  9609. cb(cur, "attn_norm", il);
  9610. // self-attention
  9611. {
  9612. // rope freq factors for llama3; may return nullptr for llama2 and other models
  9613. struct ggml_tensor * rope_factors = build_rope_factors(il);
  9614. // compute Q and K and RoPE them
  9615. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9616. cb(Qcur, "Qcur", il);
  9617. if (model.layers[il].bq) {
  9618. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9619. cb(Qcur, "Qcur", il);
  9620. }
  9621. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9622. cb(Kcur, "Kcur", il);
  9623. if (model.layers[il].bk) {
  9624. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9625. cb(Kcur, "Kcur", il);
  9626. }
  9627. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9628. cb(Vcur, "Vcur", il);
  9629. if (model.layers[il].bv) {
  9630. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9631. cb(Vcur, "Vcur", il);
  9632. }
  9633. Qcur = ggml_rope_ext(
  9634. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  9635. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9636. ext_factor, attn_factor, beta_fast, beta_slow
  9637. );
  9638. cb(Qcur, "Qcur", il);
  9639. Kcur = ggml_rope_ext(
  9640. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  9641. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9642. ext_factor, attn_factor, beta_fast, beta_slow
  9643. );
  9644. cb(Kcur, "Kcur", il);
  9645. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9646. model.layers[il].wo, model.layers[il].bo,
  9647. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  9648. }
  9649. if (il == n_layer - 1) {
  9650. // skip computing output for unused tokens
  9651. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9652. n_tokens = n_outputs;
  9653. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9654. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9655. }
  9656. // For Granite architecture
  9657. if (hparams.f_residual_scale) {
  9658. cur = ggml_scale(ctx0, cur, hparams.f_residual_scale);
  9659. }
  9660. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9661. cb(ffn_inp, "ffn_inp", il);
  9662. // feed-forward network
  9663. if (model.layers[il].ffn_gate_inp == nullptr) {
  9664. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9665. model.layers[il].ffn_norm, NULL,
  9666. LLM_NORM_RMS, cb, il);
  9667. cb(cur, "ffn_norm", il);
  9668. cur = llm_build_ffn(ctx0, lctx, cur,
  9669. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9670. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  9671. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9672. NULL,
  9673. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9674. cb(cur, "ffn_out", il);
  9675. } else {
  9676. // MoE branch
  9677. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9678. model.layers[il].ffn_norm, NULL,
  9679. LLM_NORM_RMS, cb, il);
  9680. cb(cur, "ffn_norm", il);
  9681. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  9682. model.layers[il].ffn_gate_inp,
  9683. model.layers[il].ffn_up_exps,
  9684. model.layers[il].ffn_gate_exps,
  9685. model.layers[il].ffn_down_exps,
  9686. n_expert, n_expert_used,
  9687. LLM_FFN_SILU, true,
  9688. false, 0.0,
  9689. cb, il);
  9690. cb(cur, "ffn_moe_out", il);
  9691. }
  9692. // For Granite architecture
  9693. if (hparams.f_residual_scale) {
  9694. cur = ggml_scale(ctx0, cur, hparams.f_residual_scale);
  9695. }
  9696. cur = ggml_add(ctx0, cur, ffn_inp);
  9697. cb(cur, "ffn_out", il);
  9698. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9699. cb(cur, "l_out", il);
  9700. // input for next layer
  9701. inpL = cur;
  9702. }
  9703. cur = inpL;
  9704. cur = llm_build_norm(ctx0, cur, hparams,
  9705. model.output_norm, NULL,
  9706. LLM_NORM_RMS, cb, -1);
  9707. cb(cur, "result_norm", -1);
  9708. // lm_head
  9709. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9710. // For Granite architecture
  9711. if (hparams.f_logit_scale) {
  9712. cur = ggml_scale(ctx0, cur, 1.0f / hparams.f_logit_scale);
  9713. }
  9714. cb(cur, "result_output", -1);
  9715. ggml_build_forward_expand(gf, cur);
  9716. return gf;
  9717. }
  9718. struct ggml_cgraph * build_mllama() {
  9719. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9720. // mutable variable, needed during the last layer of the computation to skip unused tokens
  9721. int32_t n_tokens = this->n_tokens;
  9722. const int64_t n_embd_head = hparams.n_embd_head_v;
  9723. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9724. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9725. struct ggml_tensor * cur;
  9726. struct ggml_tensor * inpL;
  9727. struct ggml_tensor * inpCAS;
  9728. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  9729. inpCAS = llm_build_inp_cross_attn_state(ctx0, lctx, hparams, cb);
  9730. // inp_pos - contains the positions
  9731. struct ggml_tensor * inp_pos = build_inp_pos();
  9732. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9733. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9734. for (int il = 0; il < n_layer; ++il) {
  9735. struct ggml_tensor * inpSA = inpL;
  9736. // norm
  9737. cur = llm_build_norm(ctx0, inpL, hparams,
  9738. model.layers[il].attn_norm, NULL,
  9739. LLM_NORM_RMS, cb, il);
  9740. cb(cur, "attn_norm", il);
  9741. if (hparams.cross_attention_layers(il)) {
  9742. if (!ubatch.embd && !cparams.cross_attn) {
  9743. continue;
  9744. }
  9745. // cross attention layer
  9746. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].cross_attn_q_proj, cur);
  9747. cb(Qcur, "Qcur", il);
  9748. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9749. cb(Qcur, "Qcur", il);
  9750. Qcur = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 0, 2, 1, 3));
  9751. cb(Qcur, "Qcur", il);
  9752. Qcur = llm_build_norm(ctx0, Qcur, hparams, model.layers[il].cross_attn_q_norm, NULL, LLM_NORM_RMS, cb, il);
  9753. cb(Qcur, "Qcur", il);
  9754. struct ggml_tensor * Kcur, * Vcur;
  9755. if (ubatch.embd) {
  9756. Kcur = ggml_mul_mat(ctx0, model.layers[il].cross_attn_k_proj, inpCAS);
  9757. cb(Kcur, "Kcur", il);
  9758. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, 6404);
  9759. cb(Kcur, "Kcur", il);
  9760. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  9761. cb(Kcur, "Kcur", il);
  9762. Kcur = llm_build_norm(ctx0, Kcur, hparams, model.layers[il].cross_attn_k_norm, NULL, LLM_NORM_RMS, cb, il);
  9763. cb(Kcur, "Kcur", il);
  9764. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, kv_self.k_l[il]));
  9765. Vcur = ggml_mul_mat(ctx0, model.layers[il].cross_attn_v_proj, inpCAS);
  9766. cb(Vcur, "Vcur", il);
  9767. Vcur = ggml_reshape_3d(ctx0, Vcur, n_embd_head, n_head_kv, 6404);
  9768. cb(Vcur, "Vcur", il);
  9769. Vcur = ggml_permute(ctx0, Vcur, 0, 2, 1, 3);
  9770. cb(Vcur, "Vcur", il);
  9771. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, kv_self.v_l[il]));
  9772. } else {
  9773. Kcur = ggml_view_tensor(ctx0, kv_self.k_l[il]);
  9774. cb(Kcur, "Kcur (view)", il);
  9775. Vcur = ggml_view_tensor(ctx0, kv_self.v_l[il]);
  9776. cb(Vcur, "Vcur (view)", il);
  9777. }
  9778. struct ggml_tensor * kq = ggml_mul_mat(ctx0, Kcur, Qcur);
  9779. cb(kq, "kq", il);
  9780. // TODO: apply causal masks
  9781. struct ggml_tensor * kq_soft_max = ggml_soft_max_ext(ctx0, kq, nullptr, 1.f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  9782. cb(kq_soft_max, "kq_soft_max", il);
  9783. Vcur = ggml_cont(ctx0, ggml_transpose(ctx0, Vcur));
  9784. cb(Vcur, "Vcur", il);
  9785. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, Vcur, kq_soft_max);
  9786. cb(kqv, "kqv", il);
  9787. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  9788. cb(kqv_merged, "kqv_merged", il);
  9789. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_head_v*n_head, n_tokens);
  9790. cb(cur, "kqv_merged_cont", il);
  9791. cur = ggml_mul_mat(ctx0, model.layers[il].cross_attn_o_proj, cur);
  9792. cb(cur, "cur", il);
  9793. // TODO: do this in place once?
  9794. cur = ggml_mul(ctx0, cur, ggml_tanh(ctx0, model.layers[il].cross_attn_attn_gate));
  9795. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9796. cb(ffn_inp, "ffn_inp", il);
  9797. // feed-forward network
  9798. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9799. model.layers[il].ffn_norm, NULL,
  9800. LLM_NORM_RMS, cb, il);
  9801. cb(cur, "ffn_norm", il);
  9802. cur = llm_build_ffn(ctx0, lctx, cur,
  9803. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9804. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  9805. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9806. NULL,
  9807. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9808. cb(cur, "ffn_out", il);
  9809. // TODO: do this inplace once?
  9810. cur = ggml_add_inplace(ctx0, ggml_mul_inplace(ctx0, cur, ggml_tanh(ctx0, model.layers[il].cross_attn_mlp_gate)), ffn_inp);
  9811. cb(cur, "ffn_out", il);
  9812. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9813. cb(cur, "l_out", il);
  9814. // input for next layer
  9815. inpL = cur;
  9816. } else {
  9817. // self attention layer
  9818. // rope freq factors for llama3; may return nullptr for llama2 and other models
  9819. struct ggml_tensor * rope_factors = build_rope_factors(il);
  9820. // compute Q and K and RoPE them
  9821. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9822. cb(Qcur, "Qcur", il);
  9823. if (model.layers[il].bq) {
  9824. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9825. cb(Qcur, "Qcur", il);
  9826. }
  9827. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9828. cb(Kcur, "Kcur", il);
  9829. if (model.layers[il].bk) {
  9830. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9831. cb(Kcur, "Kcur", il);
  9832. }
  9833. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9834. cb(Vcur, "Vcur", il);
  9835. if (model.layers[il].bv) {
  9836. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9837. cb(Vcur, "Vcur", il);
  9838. }
  9839. Qcur = ggml_rope_ext(
  9840. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  9841. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9842. ext_factor, attn_factor, beta_fast, beta_slow
  9843. );
  9844. cb(Qcur, "Qcur", il);
  9845. Kcur = ggml_rope_ext(
  9846. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  9847. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9848. ext_factor, attn_factor, beta_fast, beta_slow
  9849. );
  9850. cb(Kcur, "Kcur", il);
  9851. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9852. model.layers[il].wo, model.layers[il].bo,
  9853. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9854. if (il == n_layer - 1) {
  9855. // skip computing output for unused tokens
  9856. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9857. n_tokens = n_outputs;
  9858. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9859. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9860. }
  9861. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9862. cb(ffn_inp, "ffn_inp", il);
  9863. // feed-forward network
  9864. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9865. model.layers[il].ffn_norm, NULL,
  9866. LLM_NORM_RMS, cb, il);
  9867. cb(cur, "ffn_norm", il);
  9868. cur = llm_build_ffn(ctx0, lctx, cur,
  9869. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9870. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  9871. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9872. NULL,
  9873. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9874. cb(cur, "ffn_out", il);
  9875. cur = ggml_add(ctx0, cur, ffn_inp);
  9876. cb(cur, "ffn_out", il);
  9877. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9878. cb(cur, "l_out", il);
  9879. // input for next layer
  9880. inpL = cur;
  9881. }
  9882. }
  9883. cur = inpL;
  9884. cur = llm_build_norm(ctx0, cur, hparams,
  9885. model.output_norm, NULL,
  9886. LLM_NORM_RMS, cb, -1);
  9887. cb(cur, "result_norm", -1);
  9888. // lm_head
  9889. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9890. cb(cur, "result_output", -1);
  9891. ggml_build_forward_expand(gf, cur);
  9892. return gf;
  9893. }
  9894. struct ggml_cgraph * build_baichuan() {
  9895. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9896. const int64_t n_embd_head = hparams.n_embd_head_v;
  9897. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9898. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9899. struct ggml_tensor * cur;
  9900. struct ggml_tensor * inpL;
  9901. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  9902. // inp_pos - contains the positions
  9903. struct ggml_tensor * inp_pos = model.type == MODEL_7B ? build_inp_pos() : nullptr;
  9904. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9905. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9906. for (int il = 0; il < n_layer; ++il) {
  9907. struct ggml_tensor * inpSA = inpL;
  9908. cur = llm_build_norm(ctx0, inpL, hparams,
  9909. model.layers[il].attn_norm, NULL,
  9910. LLM_NORM_RMS, cb, il);
  9911. cb(cur, "attn_norm", il);
  9912. // self-attention
  9913. {
  9914. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9915. cb(Qcur, "Qcur", il);
  9916. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9917. cb(Kcur, "Kcur", il);
  9918. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9919. cb(Vcur, "Vcur", il);
  9920. switch (model.type) {
  9921. case MODEL_7B:
  9922. Qcur = ggml_rope_ext(
  9923. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9924. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9925. ext_factor, attn_factor, beta_fast, beta_slow
  9926. );
  9927. Kcur = ggml_rope_ext(
  9928. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9929. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9930. ext_factor, attn_factor, beta_fast, beta_slow
  9931. );
  9932. break;
  9933. case MODEL_13B:
  9934. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  9935. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  9936. break;
  9937. default:
  9938. GGML_ABORT("fatal error");
  9939. }
  9940. cb(Qcur, "Qcur", il);
  9941. cb(Kcur, "Kcur", il);
  9942. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9943. model.layers[il].wo, NULL,
  9944. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9945. }
  9946. if (il == n_layer - 1) {
  9947. // skip computing output for unused tokens
  9948. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9949. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9950. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9951. }
  9952. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9953. cb(ffn_inp, "ffn_inp", il);
  9954. // feed-forward network
  9955. {
  9956. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9957. model.layers[il].ffn_norm, NULL,
  9958. LLM_NORM_RMS, cb, il);
  9959. cb(cur, "ffn_norm", il);
  9960. cur = llm_build_ffn(ctx0, lctx, cur,
  9961. model.layers[il].ffn_up, NULL, NULL,
  9962. model.layers[il].ffn_gate, NULL, NULL,
  9963. model.layers[il].ffn_down, NULL, NULL,
  9964. NULL,
  9965. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9966. cb(cur, "ffn_out", il);
  9967. }
  9968. cur = ggml_add(ctx0, cur, ffn_inp);
  9969. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9970. cb(cur, "l_out", il);
  9971. // input for next layer
  9972. inpL = cur;
  9973. }
  9974. cur = inpL;
  9975. cur = llm_build_norm(ctx0, cur, hparams,
  9976. model.output_norm, NULL,
  9977. LLM_NORM_RMS, cb, -1);
  9978. cb(cur, "result_norm", -1);
  9979. // lm_head
  9980. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9981. cb(cur, "result_output", -1);
  9982. ggml_build_forward_expand(gf, cur);
  9983. return gf;
  9984. }
  9985. struct ggml_cgraph * build_xverse() {
  9986. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9987. const int64_t n_embd_head = hparams.n_embd_head_v;
  9988. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9989. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9990. struct ggml_tensor * cur;
  9991. struct ggml_tensor * inpL;
  9992. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  9993. // inp_pos - contains the positions
  9994. struct ggml_tensor * inp_pos = build_inp_pos();
  9995. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9996. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9997. for (int il = 0; il < n_layer; ++il) {
  9998. struct ggml_tensor * inpSA = inpL;
  9999. cur = llm_build_norm(ctx0, inpL, hparams,
  10000. model.layers[il].attn_norm, NULL,
  10001. LLM_NORM_RMS, cb, il);
  10002. cb(cur, "attn_norm", il);
  10003. // self-attention
  10004. {
  10005. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10006. cb(Qcur, "Qcur", il);
  10007. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10008. cb(Kcur, "Kcur", il);
  10009. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10010. cb(Vcur, "Vcur", il);
  10011. Qcur = ggml_rope_ext(
  10012. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10013. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10014. ext_factor, attn_factor, beta_fast, beta_slow
  10015. );
  10016. cb(Qcur, "Qcur", il);
  10017. Kcur = ggml_rope_ext(
  10018. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10019. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10020. ext_factor, attn_factor, beta_fast, beta_slow
  10021. );
  10022. cb(Kcur, "Kcur", il);
  10023. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10024. model.layers[il].wo, NULL,
  10025. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10026. }
  10027. if (il == n_layer - 1) {
  10028. // skip computing output for unused tokens
  10029. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10030. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10031. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10032. }
  10033. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10034. cb(ffn_inp, "ffn_inp", il);
  10035. // feed-forward network
  10036. {
  10037. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10038. model.layers[il].ffn_norm, NULL,
  10039. LLM_NORM_RMS, cb, il);
  10040. cb(cur, "ffn_norm", il);
  10041. cur = llm_build_ffn(ctx0, lctx, cur,
  10042. model.layers[il].ffn_up, NULL, NULL,
  10043. model.layers[il].ffn_gate, NULL, NULL,
  10044. model.layers[il].ffn_down, NULL, NULL,
  10045. NULL,
  10046. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10047. cb(cur, "ffn_out", il);
  10048. }
  10049. cur = ggml_add(ctx0, cur, ffn_inp);
  10050. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10051. cb(cur, "l_out", il);
  10052. // input for next layer
  10053. inpL = cur;
  10054. }
  10055. cur = inpL;
  10056. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, NULL, LLM_NORM_RMS, cb, -1);
  10057. cb(cur, "result_norm", -1);
  10058. // lm_head
  10059. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10060. cb(cur, "result_output", -1);
  10061. ggml_build_forward_expand(gf, cur);
  10062. return gf;
  10063. }
  10064. struct ggml_cgraph * build_falcon() {
  10065. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10066. const int64_t n_embd_head = hparams.n_embd_head_v;
  10067. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10068. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10069. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10070. struct ggml_tensor * cur;
  10071. struct ggml_tensor * inpL;
  10072. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10073. // inp_pos - contains the positions
  10074. struct ggml_tensor * inp_pos = build_inp_pos();
  10075. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10076. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10077. for (int il = 0; il < n_layer; ++il) {
  10078. struct ggml_tensor * attn_norm;
  10079. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  10080. model.layers[il].attn_norm,
  10081. model.layers[il].attn_norm_b,
  10082. LLM_NORM, cb, il);
  10083. cb(attn_norm, "attn_norm", il);
  10084. // self-attention
  10085. {
  10086. if (model.layers[il].attn_norm_2) {
  10087. // Falcon-40B
  10088. cur = llm_build_norm(ctx0, inpL, hparams,
  10089. model.layers[il].attn_norm_2,
  10090. model.layers[il].attn_norm_2_b,
  10091. LLM_NORM, cb, il);
  10092. cb(cur, "attn_norm_2", il);
  10093. } else {
  10094. cur = attn_norm;
  10095. }
  10096. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10097. cb(cur, "wqkv", il);
  10098. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10099. 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)));
  10100. 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)));
  10101. cb(Qcur, "Qcur", il);
  10102. cb(Kcur, "Kcur", il);
  10103. cb(Vcur, "Vcur", il);
  10104. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10105. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10106. // using mode = 2 for neox mode
  10107. Qcur = ggml_rope_ext(
  10108. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  10109. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  10110. );
  10111. cb(Qcur, "Qcur", il);
  10112. Kcur = ggml_rope_ext(
  10113. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  10114. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  10115. );
  10116. cb(Kcur, "Kcur", il);
  10117. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10118. model.layers[il].wo, NULL,
  10119. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10120. }
  10121. if (il == n_layer - 1) {
  10122. // skip computing output for unused tokens
  10123. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10124. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10125. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10126. attn_norm = ggml_get_rows(ctx0, attn_norm, inp_out_ids);
  10127. }
  10128. struct ggml_tensor * ffn_inp = cur;
  10129. // feed forward
  10130. {
  10131. cur = llm_build_ffn(ctx0, lctx, attn_norm, // !! use the attn norm, not the result
  10132. model.layers[il].ffn_up, NULL, NULL,
  10133. NULL, NULL, NULL,
  10134. model.layers[il].ffn_down, NULL, NULL,
  10135. NULL,
  10136. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10137. cb(cur, "ffn_out", il);
  10138. }
  10139. cur = ggml_add(ctx0, cur, ffn_inp);
  10140. cur = ggml_add(ctx0, cur, inpL);
  10141. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10142. cb(cur, "l_out", il);
  10143. // input for next layer
  10144. inpL = cur;
  10145. }
  10146. cur = inpL;
  10147. // norm
  10148. cur = llm_build_norm(ctx0, cur, hparams,
  10149. model.output_norm,
  10150. model.output_norm_b,
  10151. LLM_NORM, cb, -1);
  10152. cb(cur, "result_norm", -1);
  10153. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10154. cb(cur, "result_output", -1);
  10155. ggml_build_forward_expand(gf, cur);
  10156. return gf;
  10157. }
  10158. struct ggml_cgraph * build_grok() {
  10159. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10160. // mutable variable, needed during the last layer of the computation to skip unused tokens
  10161. int32_t n_tokens = this->n_tokens;
  10162. const int64_t n_embd_head = hparams.n_embd_head_v;
  10163. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10164. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10165. struct ggml_tensor * cur;
  10166. struct ggml_tensor * inpL;
  10167. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10168. // multiply by embedding_multiplier_scale of 78.38367176906169
  10169. inpL = ggml_scale(ctx0, inpL, 78.38367176906169f);
  10170. // inp_pos - contains the positions
  10171. struct ggml_tensor * inp_pos = build_inp_pos();
  10172. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10173. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10174. for (int il = 0; il < n_layer; ++il) {
  10175. struct ggml_tensor * inpSA = inpL;
  10176. // norm
  10177. cur = llm_build_norm(ctx0, inpL, hparams,
  10178. model.layers[il].attn_norm, NULL,
  10179. LLM_NORM_RMS, cb, il);
  10180. cb(cur, "attn_norm", il);
  10181. // self-attention
  10182. {
  10183. // compute Q and K and RoPE them
  10184. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10185. cb(Qcur, "Qcur", il);
  10186. if (model.layers[il].bq) {
  10187. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10188. cb(Qcur, "Qcur", il);
  10189. }
  10190. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10191. cb(Kcur, "Kcur", il);
  10192. if (model.layers[il].bk) {
  10193. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10194. cb(Kcur, "Kcur", il);
  10195. }
  10196. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10197. cb(Vcur, "Vcur", il);
  10198. if (model.layers[il].bv) {
  10199. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  10200. cb(Vcur, "Vcur", il);
  10201. }
  10202. Qcur = ggml_rope_ext(
  10203. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10204. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10205. ext_factor, attn_factor, beta_fast, beta_slow
  10206. );
  10207. cb(Qcur, "Qcur", il);
  10208. Kcur = ggml_rope_ext(
  10209. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10210. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10211. ext_factor, attn_factor, beta_fast, beta_slow
  10212. );
  10213. cb(Kcur, "Kcur", il);
  10214. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10215. model.layers[il].wo, model.layers[il].bo,
  10216. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  10217. }
  10218. if (il == n_layer - 1) {
  10219. // skip computing output for unused tokens
  10220. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10221. n_tokens = n_outputs;
  10222. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10223. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10224. }
  10225. // Grok
  10226. // if attn_out_norm is present then apply it before adding the input
  10227. if (model.layers[il].attn_out_norm) {
  10228. cur = llm_build_norm(ctx0, cur, hparams,
  10229. model.layers[il].attn_out_norm, NULL,
  10230. LLM_NORM_RMS, cb, il);
  10231. cb(cur, "attn_out_norm", il);
  10232. }
  10233. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10234. cb(ffn_inp, "ffn_inp", il);
  10235. // feed-forward network
  10236. // MoE branch
  10237. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10238. model.layers[il].ffn_norm, NULL,
  10239. LLM_NORM_RMS, cb, il);
  10240. cb(cur, "ffn_norm", il);
  10241. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  10242. model.layers[il].ffn_gate_inp,
  10243. model.layers[il].ffn_up_exps,
  10244. model.layers[il].ffn_gate_exps,
  10245. model.layers[il].ffn_down_exps,
  10246. n_expert, n_expert_used,
  10247. LLM_FFN_GELU, true,
  10248. false, 0.0,
  10249. cb, il);
  10250. cb(cur, "ffn_moe_out", il);
  10251. // Grok
  10252. // if layer_out_norm is present then apply it before adding the input
  10253. // Idea: maybe ffn_out_norm is a better name
  10254. if (model.layers[il].layer_out_norm) {
  10255. cur = llm_build_norm(ctx0, cur, hparams,
  10256. model.layers[il].layer_out_norm, NULL,
  10257. LLM_NORM_RMS, cb, il);
  10258. cb(cur, "layer_out_norm", il);
  10259. }
  10260. cur = ggml_add(ctx0, cur, ffn_inp);
  10261. cb(cur, "ffn_out", il);
  10262. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10263. cb(cur, "l_out", il);
  10264. // input for next layer
  10265. inpL = cur;
  10266. }
  10267. cur = inpL;
  10268. cur = llm_build_norm(ctx0, cur, hparams,
  10269. model.output_norm, NULL,
  10270. LLM_NORM_RMS, cb, -1);
  10271. cb(cur, "result_norm", -1);
  10272. // lm_head
  10273. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10274. // Grok
  10275. // multiply logits by output_multiplier_scale of 0.5773502691896257
  10276. cur = ggml_scale(ctx0, cur, 0.5773502691896257f);
  10277. cb(cur, "result_output", -1);
  10278. ggml_build_forward_expand(gf, cur);
  10279. return gf;
  10280. }
  10281. struct ggml_cgraph * build_dbrx() {
  10282. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10283. // mutable variable, needed during the last layer of the computation to skip unused tokens
  10284. int32_t n_tokens = this->n_tokens;
  10285. const int64_t n_embd_head = hparams.n_embd_head_v;
  10286. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10287. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10288. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10289. struct ggml_tensor * cur;
  10290. struct ggml_tensor * inpL;
  10291. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10292. // inp_pos - contains the positions
  10293. struct ggml_tensor * inp_pos = build_inp_pos();
  10294. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10295. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10296. for (int il = 0; il < n_layer; ++il) {
  10297. struct ggml_tensor * inpSA = inpL;
  10298. // norm
  10299. cur = llm_build_norm(ctx0, inpL, hparams,
  10300. model.layers[il].attn_norm, NULL,
  10301. LLM_NORM, cb, il);
  10302. cb(cur, "attn_norm", il);
  10303. // self-attention
  10304. {
  10305. struct ggml_tensor * Qcur = nullptr;
  10306. struct ggml_tensor * Kcur = nullptr;
  10307. struct ggml_tensor * Vcur = nullptr;
  10308. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10309. cb(cur, "wqkv", il);
  10310. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  10311. cb(cur, "wqkv_clamped", il);
  10312. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10313. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  10314. 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)));
  10315. cb(Qcur, "Qcur", il);
  10316. cb(Kcur, "Kcur", il);
  10317. cb(Vcur, "Vcur", il);
  10318. Qcur = ggml_rope_ext(
  10319. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10320. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10321. ext_factor, attn_factor, beta_fast, beta_slow
  10322. );
  10323. cb(Qcur, "Qcur", il);
  10324. Kcur = ggml_rope_ext(
  10325. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10326. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10327. ext_factor, attn_factor, beta_fast, beta_slow
  10328. );
  10329. cb(Kcur, "Kcur", il);
  10330. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10331. model.layers[il].wo, NULL,
  10332. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10333. }
  10334. if (il == n_layer - 1) {
  10335. // skip computing output for unused tokens
  10336. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10337. n_tokens = n_outputs;
  10338. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10339. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10340. }
  10341. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10342. cb(ffn_inp, "ffn_inp", il);
  10343. // feed-forward network
  10344. // MoE branch
  10345. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10346. model.layers[il].attn_out_norm, NULL,
  10347. LLM_NORM, cb, il);
  10348. cb(cur, "attn_out_norm", il);
  10349. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  10350. model.layers[il].ffn_gate_inp,
  10351. model.layers[il].ffn_up_exps,
  10352. model.layers[il].ffn_gate_exps,
  10353. model.layers[il].ffn_down_exps,
  10354. n_expert, n_expert_used,
  10355. LLM_FFN_SILU, true,
  10356. false, 0.0,
  10357. cb, il);
  10358. cb(cur, "ffn_moe_out", il);
  10359. cur = ggml_add(ctx0, cur, ffn_inp);
  10360. cb(cur, "ffn_out", il);
  10361. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10362. cb(cur, "l_out", il);
  10363. // input for next layer
  10364. inpL = cur;
  10365. }
  10366. cur = inpL;
  10367. cur = llm_build_norm(ctx0, cur, hparams,
  10368. model.output_norm, NULL,
  10369. LLM_NORM, cb, -1);
  10370. cb(cur, "result_norm", -1);
  10371. // lm_head
  10372. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10373. cb(cur, "result_output", -1);
  10374. ggml_build_forward_expand(gf, cur);
  10375. return gf;
  10376. }
  10377. struct ggml_cgraph * build_starcoder() {
  10378. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10379. const int64_t n_embd_head = hparams.n_embd_head_v;
  10380. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10381. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10382. struct ggml_tensor * cur;
  10383. struct ggml_tensor * inpL;
  10384. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10385. // inp_pos - contains the positions
  10386. struct ggml_tensor * inp_pos = build_inp_pos();
  10387. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10388. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10389. struct ggml_tensor * pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  10390. cb(pos, "pos_embd", -1);
  10391. inpL = ggml_add(ctx0, inpL, pos);
  10392. cb(inpL, "inpL", -1);
  10393. for (int il = 0; il < n_layer; ++il) {
  10394. cur = llm_build_norm(ctx0, inpL, hparams,
  10395. model.layers[il].attn_norm,
  10396. model.layers[il].attn_norm_b,
  10397. LLM_NORM, cb, il);
  10398. cb(cur, "attn_norm", il);
  10399. // self-attention
  10400. {
  10401. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10402. cb(cur, "wqkv", il);
  10403. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10404. cb(cur, "bqkv", il);
  10405. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10406. 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)));
  10407. 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)));
  10408. cb(Qcur, "Qcur", il);
  10409. cb(Kcur, "Kcur", il);
  10410. cb(Vcur, "Vcur", il);
  10411. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10412. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10413. model.layers[il].wo, model.layers[il].bo,
  10414. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10415. }
  10416. if (il == n_layer - 1) {
  10417. // skip computing output for unused tokens
  10418. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10419. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10420. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10421. }
  10422. // add the input
  10423. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10424. cb(ffn_inp, "ffn_inp", il);
  10425. // FF
  10426. {
  10427. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10428. model.layers[il].ffn_norm,
  10429. model.layers[il].ffn_norm_b,
  10430. LLM_NORM, cb, il);
  10431. cb(cur, "ffn_norm", il);
  10432. cur = llm_build_ffn(ctx0, lctx, cur,
  10433. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10434. NULL, NULL, NULL,
  10435. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10436. NULL,
  10437. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10438. cb(cur, "ffn_out", il);
  10439. }
  10440. cur = ggml_add(ctx0, cur, ffn_inp);
  10441. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10442. cb(cur, "l_out", il);
  10443. // input for next layer
  10444. inpL = cur;
  10445. }
  10446. cur = llm_build_norm(ctx0, inpL, hparams,
  10447. model.output_norm,
  10448. model.output_norm_b,
  10449. LLM_NORM, cb, -1);
  10450. cb(cur, "result_norm", -1);
  10451. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10452. cb(cur, "result_output", -1);
  10453. ggml_build_forward_expand(gf, cur);
  10454. return gf;
  10455. }
  10456. struct ggml_cgraph * build_refact() {
  10457. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10458. const int64_t n_embd_head = hparams.n_embd_head_v;
  10459. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10460. struct ggml_tensor * cur;
  10461. struct ggml_tensor * inpL;
  10462. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10463. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10464. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10465. for (int il = 0; il < n_layer; ++il) {
  10466. struct ggml_tensor * inpSA = inpL;
  10467. cur = llm_build_norm(ctx0, inpL, hparams,
  10468. model.layers[il].attn_norm, NULL,
  10469. LLM_NORM_RMS, cb, il);
  10470. cb(cur, "attn_norm", il);
  10471. // self-attention
  10472. {
  10473. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10474. cb(Qcur, "Qcur", il);
  10475. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10476. cb(Kcur, "Kcur", il);
  10477. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10478. cb(Vcur, "Vcur", il);
  10479. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10480. cb(Kcur, "Kcur", il);
  10481. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10482. cb(Qcur, "Qcur", il);
  10483. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10484. model.layers[il].wo, NULL,
  10485. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10486. }
  10487. if (il == n_layer - 1) {
  10488. // skip computing output for unused tokens
  10489. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10490. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10491. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10492. }
  10493. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10494. cb(ffn_inp, "ffn_inp", il);
  10495. // feed-forward network
  10496. {
  10497. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10498. model.layers[il].ffn_norm, NULL,
  10499. LLM_NORM_RMS, cb, il);
  10500. cb(cur, "ffn_norm", il);
  10501. cur = llm_build_ffn(ctx0, lctx, cur,
  10502. model.layers[il].ffn_up, NULL, NULL,
  10503. model.layers[il].ffn_gate, NULL, NULL,
  10504. model.layers[il].ffn_down, NULL, NULL,
  10505. NULL,
  10506. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10507. cb(cur, "ffn_out", il);
  10508. }
  10509. cur = ggml_add(ctx0, cur, ffn_inp);
  10510. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10511. cb(cur, "l_out", il);
  10512. // input for next layer
  10513. inpL = cur;
  10514. }
  10515. cur = inpL;
  10516. cur = llm_build_norm(ctx0, cur, hparams,
  10517. model.output_norm, NULL,
  10518. LLM_NORM_RMS, cb, -1);
  10519. cb(cur, "result_norm", -1);
  10520. // lm_head
  10521. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10522. cb(cur, "result_output", -1);
  10523. ggml_build_forward_expand(gf, cur);
  10524. return gf;
  10525. }
  10526. struct ggml_cgraph * build_bert() {
  10527. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10528. const int64_t n_embd_head = hparams.n_embd_head_v;
  10529. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10530. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10531. struct ggml_tensor * cur;
  10532. struct ggml_tensor * inpL;
  10533. struct ggml_tensor * inp_pos = nullptr;
  10534. if (model.arch != LLM_ARCH_JINA_BERT_V2) {
  10535. inp_pos = build_inp_pos();
  10536. }
  10537. // construct input embeddings (token, type, position)
  10538. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10539. // token types are hardcoded to zero ("Sentence A")
  10540. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  10541. inpL = ggml_add(ctx0, inpL, type_row0);
  10542. if (model.arch == LLM_ARCH_BERT) {
  10543. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  10544. }
  10545. cb(inpL, "inp_embd", -1);
  10546. // embed layer norm
  10547. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  10548. cb(inpL, "inp_norm", -1);
  10549. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10550. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(false);
  10551. // iterate layers
  10552. for (int il = 0; il < n_layer; ++il) {
  10553. struct ggml_tensor * cur = inpL;
  10554. struct ggml_tensor * Qcur;
  10555. struct ggml_tensor * Kcur;
  10556. struct ggml_tensor * Vcur;
  10557. // self-attention
  10558. if (model.arch == LLM_ARCH_BERT || model.arch == LLM_ARCH_JINA_BERT_V2) {
  10559. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  10560. cb(Qcur, "Qcur", il);
  10561. if (model.layers[il].attn_q_norm) {
  10562. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  10563. model.layers[il].attn_q_norm,
  10564. model.layers[il].attn_q_norm_b,
  10565. LLM_NORM, cb, il);
  10566. }
  10567. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  10568. cb(Kcur, "Kcur", il);
  10569. if (model.layers[il].attn_k_norm) {
  10570. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  10571. model.layers[il].attn_k_norm,
  10572. model.layers[il].attn_k_norm_b,
  10573. LLM_NORM, cb, il);
  10574. }
  10575. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  10576. cb(Vcur, "Vcur", il);
  10577. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10578. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10579. } else {
  10580. // compute Q and K and RoPE them
  10581. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10582. cb(cur, "wqkv", il);
  10583. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10584. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  10585. 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)));
  10586. cb(Qcur, "Qcur", il);
  10587. cb(Kcur, "Kcur", il);
  10588. cb(Vcur, "Vcur", il);
  10589. Qcur = ggml_rope_ext(
  10590. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10591. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10592. ext_factor, attn_factor, beta_fast, beta_slow
  10593. );
  10594. cb(Qcur, "Qcur", il);
  10595. Kcur = ggml_rope_ext(
  10596. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10597. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10598. ext_factor, attn_factor, beta_fast, beta_slow
  10599. );
  10600. cb(Kcur, "Kcur", il);
  10601. }
  10602. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  10603. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  10604. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  10605. cb(kq, "kq", il);
  10606. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask, 1.0f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  10607. cb(kq, "kq_soft_max_ext", il);
  10608. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  10609. cb(v, "v", il);
  10610. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  10611. cb(kqv, "kqv", il);
  10612. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  10613. cb(kqv_merged, "kqv_merged", il);
  10614. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  10615. cb(cur, "kqv_merged_cont", il);
  10616. ggml_build_forward_expand(gf, cur);
  10617. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  10618. if (model.layers[il].bo) {
  10619. cb(cur, "kqv_wo", il);
  10620. }
  10621. if (model.layers[il].bo) {
  10622. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  10623. }
  10624. cb(cur, "kqv_out", il);
  10625. if (il == n_layer - 1 && pooling_type == LLAMA_POOLING_TYPE_NONE) {
  10626. // skip computing output for unused tokens
  10627. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10628. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10629. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10630. }
  10631. // re-add the layer input
  10632. cur = ggml_add(ctx0, cur, inpL);
  10633. // attention layer norm
  10634. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  10635. if (model.layers[il].attn_norm_2 != nullptr) {
  10636. cur = ggml_add(ctx0, cur, inpL); // re-add the layer input
  10637. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_norm_2, model.layers[il].attn_norm_2_b, LLM_NORM, cb, il);
  10638. }
  10639. struct ggml_tensor * ffn_inp = cur;
  10640. cb(ffn_inp, "ffn_inp", il);
  10641. // feed-forward network
  10642. if (model.arch == LLM_ARCH_BERT) {
  10643. cur = llm_build_ffn(ctx0, lctx, cur,
  10644. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10645. NULL, NULL, NULL,
  10646. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10647. NULL,
  10648. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10649. } else if (model.arch == LLM_ARCH_JINA_BERT_V2) {
  10650. cur = llm_build_ffn(ctx0, lctx, cur,
  10651. model.layers[il].ffn_up, NULL, NULL,
  10652. model.layers[il].ffn_gate, NULL, NULL,
  10653. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10654. NULL,
  10655. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  10656. } else {
  10657. cur = llm_build_ffn(ctx0, lctx, cur,
  10658. model.layers[il].ffn_up, NULL, NULL,
  10659. model.layers[il].ffn_gate, NULL, NULL,
  10660. model.layers[il].ffn_down, NULL, NULL,
  10661. NULL,
  10662. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10663. }
  10664. cb(cur, "ffn_out", il);
  10665. // attentions bypass the intermediate layer
  10666. cur = ggml_add(ctx0, cur, ffn_inp);
  10667. // output layer norm
  10668. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  10669. // input for next layer
  10670. inpL = cur;
  10671. }
  10672. cur = inpL;
  10673. cb(cur, "result_embd", -1);
  10674. ggml_build_forward_expand(gf, cur);
  10675. return gf;
  10676. }
  10677. struct ggml_cgraph * build_bloom() {
  10678. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10679. const int64_t n_embd_head = hparams.n_embd_head_v;
  10680. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10681. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10682. struct ggml_tensor * cur;
  10683. struct ggml_tensor * inpL;
  10684. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10685. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10686. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10687. inpL = llm_build_norm(ctx0, inpL, hparams,
  10688. model.tok_norm,
  10689. model.tok_norm_b,
  10690. LLM_NORM, cb, -1);
  10691. cb(inpL, "inp_norm", -1);
  10692. for (int il = 0; il < n_layer; ++il) {
  10693. cur = llm_build_norm(ctx0, inpL, hparams,
  10694. model.layers[il].attn_norm,
  10695. model.layers[il].attn_norm_b,
  10696. LLM_NORM, cb, il);
  10697. cb(cur, "attn_norm", il);
  10698. // self-attention
  10699. {
  10700. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10701. cb(cur, "wqkv", il);
  10702. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10703. cb(cur, "bqkv", il);
  10704. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10705. 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)));
  10706. 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)));
  10707. cb(Qcur, "Qcur", il);
  10708. cb(Kcur, "Kcur", il);
  10709. cb(Vcur, "Vcur", il);
  10710. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10711. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10712. model.layers[il].wo, model.layers[il].bo,
  10713. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10714. }
  10715. if (il == n_layer - 1) {
  10716. // skip computing output for unused tokens
  10717. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10718. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10719. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10720. }
  10721. // Add the input
  10722. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10723. cb(ffn_inp, "ffn_inp", il);
  10724. // FF
  10725. {
  10726. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10727. model.layers[il].ffn_norm,
  10728. model.layers[il].ffn_norm_b,
  10729. LLM_NORM, cb, il);
  10730. cb(cur, "ffn_norm", il);
  10731. cur = llm_build_ffn(ctx0, lctx, cur,
  10732. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10733. NULL, NULL, NULL,
  10734. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10735. NULL,
  10736. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10737. cb(cur, "ffn_out", il);
  10738. }
  10739. cur = ggml_add(ctx0, cur, ffn_inp);
  10740. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10741. cb(cur, "l_out", il);
  10742. // input for next layer
  10743. inpL = cur;
  10744. }
  10745. cur = llm_build_norm(ctx0, inpL, hparams,
  10746. model.output_norm,
  10747. model.output_norm_b,
  10748. LLM_NORM, cb, -1);
  10749. cb(cur, "result_norm", -1);
  10750. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10751. cb(cur, "result_output", -1);
  10752. ggml_build_forward_expand(gf, cur);
  10753. return gf;
  10754. }
  10755. struct ggml_cgraph * build_mpt() {
  10756. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10757. const int64_t n_embd_head = hparams.n_embd_head_v;
  10758. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10759. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10760. struct ggml_tensor * cur;
  10761. struct ggml_tensor * pos;
  10762. struct ggml_tensor * inpL;
  10763. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10764. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10765. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10766. if (model.pos_embd) {
  10767. // inp_pos - contains the positions
  10768. struct ggml_tensor * inp_pos = build_inp_pos();
  10769. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  10770. cb(pos, "pos_embd", -1);
  10771. inpL = ggml_add(ctx0, inpL, pos);
  10772. cb(inpL, "inpL", -1);
  10773. }
  10774. for (int il = 0; il < n_layer; ++il) {
  10775. struct ggml_tensor * attn_norm;
  10776. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  10777. model.layers[il].attn_norm,
  10778. model.layers[il].attn_norm_b,
  10779. LLM_NORM, cb, il);
  10780. cb(attn_norm, "attn_norm", il);
  10781. // self-attention
  10782. {
  10783. cur = attn_norm;
  10784. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10785. cb(cur, "wqkv", il);
  10786. if (model.layers[il].bqkv){
  10787. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10788. cb(cur, "bqkv", il);
  10789. }
  10790. if (hparams.f_clamp_kqv > 0.0f) {
  10791. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  10792. cb(cur, "wqkv_clamped", il);
  10793. }
  10794. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10795. 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)));
  10796. 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)));
  10797. cb(Qcur, "Qcur", il);
  10798. cb(Kcur, "Kcur", il);
  10799. cb(Vcur, "Vcur", il);
  10800. // Q/K Layernorm
  10801. if (model.layers[il].attn_q_norm) {
  10802. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  10803. model.layers[il].attn_q_norm,
  10804. model.layers[il].attn_q_norm_b,
  10805. LLM_NORM, cb, il);
  10806. cb(Qcur, "Qcur", il);
  10807. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  10808. model.layers[il].attn_k_norm,
  10809. model.layers[il].attn_k_norm_b,
  10810. LLM_NORM, cb, il);
  10811. cb(Kcur, "Kcur", il);
  10812. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10813. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10814. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10815. model.layers[il].wo, model.layers[il].bo,
  10816. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10817. } else {
  10818. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10819. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10820. model.layers[il].wo, model.layers[il].bo,
  10821. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10822. }
  10823. }
  10824. if (il == n_layer - 1) {
  10825. // skip computing output for unused tokens
  10826. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10827. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10828. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10829. }
  10830. // Add the input
  10831. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10832. cb(ffn_inp, "ffn_inp", il);
  10833. // feed forward
  10834. {
  10835. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10836. model.layers[il].ffn_norm,
  10837. model.layers[il].ffn_norm_b,
  10838. LLM_NORM, cb, il);
  10839. cb(cur, "ffn_norm", il);
  10840. cur = llm_build_ffn(ctx0, lctx, cur,
  10841. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10842. NULL, NULL, NULL,
  10843. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10844. model.layers[il].ffn_act,
  10845. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10846. cb(cur, "ffn_out", il);
  10847. }
  10848. cur = ggml_add(ctx0, cur, ffn_inp);
  10849. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10850. cb(cur, "l_out", il);
  10851. // input for next layer
  10852. inpL = cur;
  10853. }
  10854. cur = inpL;
  10855. cur = llm_build_norm(ctx0, cur, hparams,
  10856. model.output_norm,
  10857. model.output_norm_b,
  10858. LLM_NORM, cb, -1);
  10859. cb(cur, "result_norm", -1);
  10860. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10861. cb(cur, "result_output", -1);
  10862. ggml_build_forward_expand(gf, cur);
  10863. return gf;
  10864. }
  10865. struct ggml_cgraph * build_stablelm() {
  10866. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  10867. const int64_t n_embd_head = hparams.n_embd_head_v;
  10868. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10869. struct ggml_tensor * cur;
  10870. struct ggml_tensor * inpL;
  10871. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10872. // inp_pos - contains the positions
  10873. struct ggml_tensor * inp_pos = build_inp_pos();
  10874. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10875. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10876. for (int il = 0; il < n_layer; ++il) {
  10877. // norm
  10878. cur = llm_build_norm(ctx0, inpL, hparams,
  10879. model.layers[il].attn_norm,
  10880. model.layers[il].attn_norm_b,
  10881. LLM_NORM, cb, il);
  10882. cb(cur, "attn_norm", il);
  10883. struct ggml_tensor * inpSA = cur;
  10884. // self-attention
  10885. {
  10886. // compute Q and K and RoPE them
  10887. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10888. cb(Qcur, "Qcur", il);
  10889. if (model.layers[il].bq) {
  10890. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10891. cb(Qcur, "Qcur", il);
  10892. }
  10893. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10894. cb(Kcur, "Kcur", il);
  10895. if (model.layers[il].bk) {
  10896. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10897. cb(Kcur, "Kcur", il);
  10898. }
  10899. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10900. cb(Vcur, "Vcur", il);
  10901. if (model.layers[il].bv) {
  10902. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  10903. cb(Vcur, "Vcur", il);
  10904. }
  10905. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10906. cb(Qcur, "Qcur", il);
  10907. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10908. cb(Kcur, "Kcur", il);
  10909. if (model.layers[il].attn_q_norm) {
  10910. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  10911. model.layers[il].attn_q_norm,
  10912. NULL,
  10913. LLM_NORM, cb, il);
  10914. cb(Qcur, "Qcur", il);
  10915. }
  10916. if (model.layers[il].attn_k_norm) {
  10917. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  10918. model.layers[il].attn_k_norm,
  10919. NULL,
  10920. LLM_NORM, cb, il);
  10921. cb(Kcur, "Kcur", il);
  10922. }
  10923. Qcur = ggml_rope_ext(
  10924. ctx0, Qcur, inp_pos, nullptr,
  10925. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10926. ext_factor, attn_factor, beta_fast, beta_slow
  10927. );
  10928. cb(Qcur, "Qcur", il);
  10929. Kcur = ggml_rope_ext(
  10930. ctx0, Kcur, inp_pos, nullptr,
  10931. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10932. ext_factor, attn_factor, beta_fast, beta_slow
  10933. );
  10934. cb(Kcur, "Kcur", il);
  10935. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10936. model.layers[il].wo, NULL,
  10937. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10938. }
  10939. if (il == n_layer - 1) {
  10940. // skip computing output for unused tokens
  10941. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10942. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10943. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10944. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10945. }
  10946. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10947. cb(ffn_inp, "ffn_inp", il);
  10948. // feed-forward network
  10949. {
  10950. if (model.layers[il].ffn_norm) {
  10951. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10952. model.layers[il].ffn_norm,
  10953. model.layers[il].ffn_norm_b,
  10954. LLM_NORM, cb, il);
  10955. cb(cur, "ffn_norm", il);
  10956. } else {
  10957. // parallel residual
  10958. cur = inpSA;
  10959. }
  10960. cur = llm_build_ffn(ctx0, lctx, cur,
  10961. model.layers[il].ffn_up, NULL, NULL,
  10962. model.layers[il].ffn_gate, NULL, NULL,
  10963. model.layers[il].ffn_down, NULL, NULL,
  10964. NULL,
  10965. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10966. cb(cur, "ffn_out", il);
  10967. }
  10968. cur = ggml_add(ctx0, cur, ffn_inp);
  10969. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10970. cb(cur, "l_out", il);
  10971. // input for next layer
  10972. inpL = cur;
  10973. }
  10974. cur = inpL;
  10975. cur = llm_build_norm(ctx0, cur, hparams,
  10976. model.output_norm,
  10977. model.output_norm_b,
  10978. LLM_NORM, cb, -1);
  10979. cb(cur, "result_norm", -1);
  10980. // lm_head
  10981. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10982. cb(cur, "result_output", -1);
  10983. ggml_build_forward_expand(gf, cur);
  10984. return gf;
  10985. }
  10986. struct ggml_cgraph * build_qwen() {
  10987. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10988. const int64_t n_embd_head = hparams.n_embd_head_v;
  10989. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10990. struct ggml_tensor * cur;
  10991. struct ggml_tensor * inpL;
  10992. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10993. // inp_pos - contains the positions
  10994. struct ggml_tensor * inp_pos = build_inp_pos();
  10995. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10996. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10997. for (int il = 0; il < n_layer; ++il) {
  10998. struct ggml_tensor * inpSA = inpL;
  10999. cur = llm_build_norm(ctx0, inpL, hparams,
  11000. model.layers[il].attn_norm, NULL,
  11001. LLM_NORM_RMS, cb, il);
  11002. cb(cur, "attn_norm", il);
  11003. // self-attention
  11004. {
  11005. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  11006. cb(cur, "wqkv", il);
  11007. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  11008. cb(cur, "bqkv", il);
  11009. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  11010. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  11011. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  11012. cb(Qcur, "Qcur", il);
  11013. cb(Kcur, "Kcur", il);
  11014. cb(Vcur, "Vcur", il);
  11015. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11016. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  11017. // using mode = 2 for neox mode
  11018. Qcur = ggml_rope_ext(
  11019. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  11020. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  11021. );
  11022. cb(Qcur, "Qcur", il);
  11023. Kcur = ggml_rope_ext(
  11024. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  11025. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  11026. );
  11027. cb(Kcur, "Kcur", il);
  11028. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11029. model.layers[il].wo, NULL,
  11030. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11031. }
  11032. if (il == n_layer - 1) {
  11033. // skip computing output for unused tokens
  11034. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11035. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11036. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11037. }
  11038. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11039. cb(ffn_inp, "ffn_inp", il);
  11040. // feed-forward forward
  11041. {
  11042. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11043. model.layers[il].ffn_norm, NULL,
  11044. LLM_NORM_RMS, cb, il);
  11045. cb(cur, "ffn_norm", il);
  11046. cur = llm_build_ffn(ctx0, lctx, cur,
  11047. model.layers[il].ffn_up, NULL, NULL,
  11048. model.layers[il].ffn_gate, NULL, NULL,
  11049. model.layers[il].ffn_down, NULL, NULL,
  11050. NULL,
  11051. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11052. cb(cur, "ffn_out", il);
  11053. }
  11054. cur = ggml_add(ctx0, cur, ffn_inp);
  11055. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11056. cb(cur, "l_out", il);
  11057. // input for next layer
  11058. inpL = cur;
  11059. }
  11060. cur = inpL;
  11061. cur = llm_build_norm(ctx0, cur, hparams,
  11062. model.output_norm, NULL,
  11063. LLM_NORM_RMS, cb, -1);
  11064. cb(cur, "result_norm", -1);
  11065. // lm_head
  11066. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11067. cb(cur, "result_output", -1);
  11068. ggml_build_forward_expand(gf, cur);
  11069. return gf;
  11070. }
  11071. struct ggml_cgraph * build_qwen2() {
  11072. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11073. const int64_t n_embd_head = hparams.n_embd_head_v;
  11074. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11075. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11076. struct ggml_tensor * cur;
  11077. struct ggml_tensor * inpL;
  11078. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11079. // inp_pos - contains the positions
  11080. struct ggml_tensor * inp_pos = build_inp_pos();
  11081. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11082. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11083. for (int il = 0; il < n_layer; ++il) {
  11084. struct ggml_tensor * inpSA = inpL;
  11085. // norm
  11086. cur = llm_build_norm(ctx0, inpL, hparams,
  11087. model.layers[il].attn_norm, NULL,
  11088. LLM_NORM_RMS, cb, il);
  11089. cb(cur, "attn_norm", il);
  11090. // self-attention
  11091. {
  11092. // compute Q and K and RoPE them
  11093. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11094. cb(Qcur, "Qcur", il);
  11095. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  11096. cb(Qcur, "Qcur", il);
  11097. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11098. cb(Kcur, "Kcur", il);
  11099. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  11100. cb(Kcur, "Kcur", il);
  11101. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11102. cb(Vcur, "Vcur", il);
  11103. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11104. cb(Vcur, "Vcur", il);
  11105. Qcur = ggml_rope_ext(
  11106. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11107. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11108. ext_factor, attn_factor, beta_fast, beta_slow
  11109. );
  11110. cb(Qcur, "Qcur", il);
  11111. Kcur = ggml_rope_ext(
  11112. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11113. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11114. ext_factor, attn_factor, beta_fast, beta_slow
  11115. );
  11116. cb(Kcur, "Kcur", il);
  11117. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11118. model.layers[il].wo, model.layers[il].bo,
  11119. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11120. }
  11121. if (il == n_layer - 1) {
  11122. // skip computing output for unused tokens
  11123. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11124. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11125. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11126. }
  11127. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11128. cb(ffn_inp, "ffn_inp", il);
  11129. // feed-forward network
  11130. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11131. model.layers[il].ffn_norm, NULL,
  11132. LLM_NORM_RMS, cb, il);
  11133. cb(cur, "ffn_norm", il);
  11134. cur = llm_build_ffn(ctx0, lctx, cur,
  11135. model.layers[il].ffn_up, NULL, NULL,
  11136. model.layers[il].ffn_gate, NULL, NULL,
  11137. model.layers[il].ffn_down, NULL, NULL,
  11138. NULL,
  11139. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11140. cb(cur, "ffn_out", il);
  11141. cur = ggml_add(ctx0, cur, ffn_inp);
  11142. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11143. cb(cur, "l_out", il);
  11144. // input for next layer
  11145. inpL = cur;
  11146. }
  11147. cur = inpL;
  11148. cur = llm_build_norm(ctx0, cur, hparams,
  11149. model.output_norm, NULL,
  11150. LLM_NORM_RMS, cb, -1);
  11151. cb(cur, "result_norm", -1);
  11152. // lm_head
  11153. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11154. cb(cur, "result_output", -1);
  11155. ggml_build_forward_expand(gf, cur);
  11156. return gf;
  11157. }
  11158. struct ggml_cgraph * build_qwen2moe() {
  11159. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11160. // mutable variable, needed during the last layer of the computation to skip unused tokens
  11161. int32_t n_tokens = this->n_tokens;
  11162. const int64_t n_embd_head = hparams.n_embd_head_v;
  11163. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11164. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11165. struct ggml_tensor * cur;
  11166. struct ggml_tensor * inpL;
  11167. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11168. // inp_pos - contains the positions
  11169. struct ggml_tensor * inp_pos = build_inp_pos();
  11170. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11171. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11172. for (int il = 0; il < n_layer; ++il) {
  11173. struct ggml_tensor * inpSA = inpL;
  11174. // norm
  11175. cur = llm_build_norm(ctx0, inpL, hparams,
  11176. model.layers[il].attn_norm, NULL,
  11177. LLM_NORM_RMS, cb, il);
  11178. cb(cur, "attn_norm", il);
  11179. // self_attention
  11180. {
  11181. // compute Q and K and RoPE them
  11182. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11183. cb(Qcur, "Qcur", il);
  11184. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  11185. cb(Qcur, "Qcur", il);
  11186. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11187. cb(Kcur, "Kcur", il);
  11188. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  11189. cb(Kcur, "Kcur", il);
  11190. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11191. cb(Vcur, "Vcur", il);
  11192. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11193. cb(Vcur, "Vcur", il);
  11194. Qcur = ggml_rope_ext(
  11195. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11196. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11197. ext_factor, attn_factor, beta_fast, beta_slow
  11198. );
  11199. cb(Qcur, "Qcur", il);
  11200. Kcur = ggml_rope_ext(
  11201. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11202. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11203. ext_factor, attn_factor, beta_fast, beta_slow
  11204. );
  11205. cb(Kcur, "Kcur", il);
  11206. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11207. model.layers[il].wo, model.layers[il].bo,
  11208. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11209. }
  11210. if (il == n_layer - 1) {
  11211. // skip computing output for unused tokens
  11212. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11213. n_tokens = n_outputs;
  11214. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11215. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11216. }
  11217. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11218. cb(ffn_inp, "ffn_inp", il);
  11219. // MoE branch
  11220. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11221. model.layers[il].ffn_norm, NULL,
  11222. LLM_NORM_RMS, cb, il);
  11223. cb(cur, "ffn_norm", il);
  11224. ggml_tensor * moe_out =
  11225. llm_build_moe_ffn(ctx0, lctx, cur,
  11226. model.layers[il].ffn_gate_inp,
  11227. model.layers[il].ffn_up_exps,
  11228. model.layers[il].ffn_gate_exps,
  11229. model.layers[il].ffn_down_exps,
  11230. n_expert, n_expert_used,
  11231. LLM_FFN_SILU, false,
  11232. false, 0.0,
  11233. cb, il);
  11234. cb(cur, "ffn_moe_out", il);
  11235. // FFN shared expert
  11236. {
  11237. ggml_tensor * cur_gate_inp = llm_build_lora_mm(lctx, ctx0, model.layers[il].ffn_gate_inp_shexp, cur);
  11238. cb(cur_gate_inp, "ffn_shexp_gate_inp", il);
  11239. // sigmoid
  11240. ggml_tensor * cur_gate = ggml_div(ctx0, ggml_silu(ctx0, cur_gate_inp), cur_gate_inp);
  11241. cb(cur_gate, "ffn_shexp_gate", il);
  11242. ggml_tensor * cur_ffn = llm_build_ffn(ctx0, lctx, cur,
  11243. model.layers[il].ffn_up_shexp, NULL, NULL,
  11244. model.layers[il].ffn_gate_shexp, NULL, NULL,
  11245. model.layers[il].ffn_down_shexp, NULL, NULL,
  11246. NULL,
  11247. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11248. cb(cur_ffn, "ffn_shexp", il);
  11249. ggml_tensor * ffn_shexp_out = ggml_mul(ctx0, cur_ffn, cur_gate);
  11250. cb(ffn_shexp_out, "ffn_shexp_out", il);
  11251. moe_out = ggml_add(ctx0, moe_out, ffn_shexp_out);
  11252. cb(moe_out, "ffn_out", il);
  11253. cur = moe_out;
  11254. }
  11255. cur = ggml_add(ctx0, cur, ffn_inp);
  11256. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11257. cb(cur, "l_out", il);
  11258. // input for next layer
  11259. inpL = cur;
  11260. }
  11261. cur = inpL;
  11262. cur = llm_build_norm(ctx0, cur, hparams,
  11263. model.output_norm, NULL,
  11264. LLM_NORM_RMS, cb, -1);
  11265. cb(cur, "result_norm", -1);
  11266. // lm_head
  11267. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11268. cb(cur, "result_output", -1);
  11269. ggml_build_forward_expand(gf, cur);
  11270. return gf;
  11271. }
  11272. struct ggml_cgraph * build_phi2() {
  11273. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11274. const int64_t n_embd_head = hparams.n_embd_head_v;
  11275. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11276. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11277. struct ggml_tensor * cur;
  11278. struct ggml_tensor * attn_norm_output;
  11279. struct ggml_tensor * ffn_output;
  11280. struct ggml_tensor * inpL;
  11281. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11282. // inp_pos - contains the positions
  11283. struct ggml_tensor * inp_pos = build_inp_pos();
  11284. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11285. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11286. for (int il = 0; il < n_layer; ++il) {
  11287. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  11288. model.layers[il].attn_norm,
  11289. model.layers[il].attn_norm_b,
  11290. LLM_NORM, cb, il);
  11291. cb(attn_norm_output, "attn_norm", il);
  11292. // self-attention
  11293. {
  11294. struct ggml_tensor * Qcur = nullptr;
  11295. struct ggml_tensor * Kcur = nullptr;
  11296. struct ggml_tensor * Vcur = nullptr;
  11297. if (model.layers[il].wqkv) {
  11298. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, attn_norm_output);
  11299. cb(cur, "wqkv", il);
  11300. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  11301. cb(cur, "bqkv", il);
  11302. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  11303. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  11304. 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)));
  11305. } else {
  11306. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  11307. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  11308. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  11309. }
  11310. cb(Qcur, "Qcur", il);
  11311. cb(Kcur, "Kcur", il);
  11312. cb(Vcur, "Vcur", il);
  11313. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11314. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  11315. Qcur = ggml_rope_ext(
  11316. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  11317. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  11318. );
  11319. cb(Qcur, "Qcur", il);
  11320. // with phi2, we scale the Q to avoid precision issues
  11321. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  11322. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  11323. cb(Qcur, "Qcur", il);
  11324. Kcur = ggml_rope_ext(
  11325. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  11326. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  11327. );
  11328. cb(Kcur, "Kcur", il);
  11329. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11330. model.layers[il].wo, model.layers[il].bo,
  11331. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  11332. }
  11333. if (il == n_layer - 1) {
  11334. // skip computing output for unused tokens
  11335. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11336. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11337. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11338. attn_norm_output = ggml_get_rows(ctx0, attn_norm_output, inp_out_ids);
  11339. }
  11340. // FF
  11341. {
  11342. ffn_output = llm_build_ffn(ctx0, lctx, attn_norm_output,
  11343. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  11344. NULL, NULL, NULL,
  11345. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  11346. NULL,
  11347. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  11348. cb(ffn_output, "ffn_out", il);
  11349. }
  11350. cur = ggml_add(ctx0, cur, ffn_output);
  11351. cur = ggml_add(ctx0, cur, inpL);
  11352. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11353. cb(cur, "l_out", il);
  11354. // input for next layer
  11355. inpL = cur;
  11356. }
  11357. cur = llm_build_norm(ctx0, inpL, hparams,
  11358. model.output_norm,
  11359. model.output_norm_b,
  11360. LLM_NORM, cb, -1);
  11361. cb(cur, "result_norm", -1);
  11362. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11363. cb(cur, "result_output_no_bias", -1);
  11364. cur = ggml_add(ctx0, cur, model.output_b);
  11365. cb(cur, "result_output", -1);
  11366. ggml_build_forward_expand(gf, cur);
  11367. return gf;
  11368. }
  11369. struct ggml_cgraph * build_phi3() {
  11370. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11371. const int64_t n_embd_head = hparams.n_embd_head_v;
  11372. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11373. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11374. struct ggml_tensor * cur;
  11375. struct ggml_tensor * inpL;
  11376. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11377. // inp_pos - contains the positions
  11378. struct ggml_tensor * inp_pos = build_inp_pos();
  11379. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11380. struct ggml_tensor * KQ_mask_swa = build_inp_KQ_mask_swa();
  11381. for (int il = 0; il < n_layer; ++il) {
  11382. auto residual = inpL;
  11383. // self-attention
  11384. {
  11385. // rope freq factors for 128k context
  11386. struct ggml_tensor * rope_factors = build_rope_factors(il);
  11387. struct ggml_tensor* attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  11388. model.layers[il].attn_norm,
  11389. NULL,
  11390. LLM_NORM_RMS, cb, il);
  11391. cb(attn_norm_output, "attn_norm", il);
  11392. struct ggml_tensor * Qcur = nullptr;
  11393. struct ggml_tensor * Kcur = nullptr;
  11394. struct ggml_tensor * Vcur = nullptr;
  11395. if (model.layers[il].wqkv) {
  11396. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, attn_norm_output);
  11397. cb(cur, "wqkv", il);
  11398. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0 * sizeof(float) * (n_embd)));
  11399. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1 * sizeof(float) * (n_embd)));
  11400. 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)));
  11401. }
  11402. else {
  11403. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  11404. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  11405. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  11406. }
  11407. cb(Qcur, "Qcur", il);
  11408. cb(Kcur, "Kcur", il);
  11409. cb(Vcur, "Vcur", il);
  11410. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11411. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  11412. Qcur = ggml_rope_ext(
  11413. ctx0, Qcur, inp_pos, rope_factors, n_rot, rope_type, n_ctx_orig,
  11414. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  11415. );
  11416. cb(Qcur, "Qcur", il);
  11417. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head)));
  11418. cb(Qcur, "Qcur", il);
  11419. Kcur = ggml_rope_ext(
  11420. ctx0, Kcur, inp_pos, rope_factors, n_rot, rope_type, n_ctx_orig,
  11421. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  11422. );
  11423. cb(Kcur, "Kcur", il);
  11424. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11425. model.layers[il].wo, model.layers[il].bo,
  11426. Kcur, Vcur, Qcur, KQ_mask_swa, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  11427. }
  11428. if (il == n_layer - 1) {
  11429. // skip computing output for unused tokens
  11430. struct ggml_tensor* inp_out_ids = build_inp_out_ids();
  11431. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11432. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  11433. }
  11434. cur = ggml_add(ctx0, cur, residual);
  11435. residual = cur;
  11436. cur = llm_build_norm(ctx0, cur, hparams,
  11437. model.layers[il].ffn_norm, NULL,
  11438. LLM_NORM_RMS, cb, il);
  11439. cb(cur, "ffn_norm", il);
  11440. // FF
  11441. // special-case: the up and gate tensors are merged into a single tensor
  11442. // TOOD: support into llm_build_ffn
  11443. {
  11444. cur = llm_build_ffn(ctx0, lctx, cur,
  11445. model.layers[il].ffn_up, NULL, NULL,
  11446. NULL, NULL, NULL,
  11447. model.layers[il].ffn_down, NULL, NULL,
  11448. NULL,
  11449. LLM_FFN_SWIGLU, LLM_FFN_SEQ, cb, il);
  11450. cb(cur, "ffn_out", il);
  11451. }
  11452. cur = ggml_add(ctx0, residual, cur);
  11453. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11454. cb(cur, "l_out", il);
  11455. // input for next layer
  11456. inpL = cur;
  11457. }
  11458. cur = llm_build_norm(ctx0, inpL, hparams,
  11459. model.output_norm,
  11460. NULL,
  11461. LLM_NORM_RMS, cb, -1);
  11462. cb(cur, "result_norm", -1);
  11463. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11464. cb(cur, "result_output", -1);
  11465. ggml_build_forward_expand(gf, cur);
  11466. return gf;
  11467. }
  11468. struct ggml_cgraph * build_plamo() {
  11469. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  11470. const int64_t n_embd_head = hparams.n_embd_head_v;
  11471. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11472. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11473. struct ggml_tensor * cur;
  11474. struct ggml_tensor * inpL;
  11475. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11476. // inp_pos - contains the positions
  11477. struct ggml_tensor * inp_pos = build_inp_pos();
  11478. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11479. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11480. for (int il = 0; il < n_layer; ++il) {
  11481. // norm
  11482. cur = llm_build_norm(ctx0, inpL, hparams,
  11483. model.layers[il].attn_norm, NULL,
  11484. LLM_NORM_RMS, cb, il);
  11485. cb(cur, "attn_norm", il);
  11486. struct ggml_tensor * attention_norm = cur;
  11487. // self-attention
  11488. {
  11489. // compute Q and K and RoPE them
  11490. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11491. cb(Qcur, "Qcur", il);
  11492. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11493. cb(Kcur, "Kcur", il);
  11494. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11495. cb(Vcur, "Vcur", il);
  11496. Qcur = ggml_rope_ext(
  11497. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos, nullptr,
  11498. n_embd_head, rope_type, n_ctx_orig, freq_base, freq_scale,
  11499. ext_factor, attn_factor, beta_fast, beta_slow);
  11500. cb(Qcur, "Qcur", il);
  11501. Kcur = ggml_rope_ext(
  11502. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos, nullptr,
  11503. n_embd_head, rope_type, n_ctx_orig, freq_base, freq_scale,
  11504. ext_factor, attn_factor, beta_fast, beta_slow);
  11505. cb(Kcur, "Kcur", il);
  11506. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11507. model.layers[il].wo, NULL,
  11508. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11509. }
  11510. struct ggml_tensor * sa_out = cur;
  11511. cur = attention_norm;
  11512. if (il == n_layer - 1) {
  11513. // skip computing output for unused tokens
  11514. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11515. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11516. sa_out = ggml_get_rows(ctx0, sa_out, inp_out_ids);
  11517. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11518. }
  11519. // feed-forward network
  11520. {
  11521. cur = llm_build_ffn(ctx0, lctx, cur,
  11522. model.layers[il].ffn_up, NULL, NULL,
  11523. model.layers[il].ffn_gate, NULL, NULL,
  11524. model.layers[il].ffn_down, NULL, NULL,
  11525. NULL,
  11526. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11527. cb(cur, "ffn_out", il);
  11528. }
  11529. cur = ggml_add(ctx0, cur, sa_out);
  11530. cur = ggml_add(ctx0, cur, inpL);
  11531. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11532. cb(cur, "l_out", il);
  11533. // input for next layer
  11534. inpL = cur;
  11535. }
  11536. cur = inpL;
  11537. cur = llm_build_norm(ctx0, cur, hparams,
  11538. model.output_norm, NULL,
  11539. LLM_NORM_RMS, cb, -1);
  11540. cb(cur, "result_norm", -1);
  11541. // lm_head
  11542. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11543. cb(cur, "result_output", -1);
  11544. ggml_build_forward_expand(gf, cur);
  11545. return gf;
  11546. }
  11547. struct ggml_cgraph * build_gpt2() {
  11548. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11549. const int64_t n_embd_head = hparams.n_embd_head_v;
  11550. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11551. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11552. struct ggml_tensor * cur;
  11553. struct ggml_tensor * pos;
  11554. struct ggml_tensor * inpL;
  11555. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11556. // inp_pos - contains the positions
  11557. struct ggml_tensor * inp_pos = build_inp_pos();
  11558. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11559. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11560. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  11561. cb(pos, "pos_embd", -1);
  11562. inpL = ggml_add(ctx0, inpL, pos);
  11563. cb(inpL, "inpL", -1);
  11564. for (int il = 0; il < n_layer; ++il) {
  11565. cur = llm_build_norm(ctx0, inpL, hparams,
  11566. model.layers[il].attn_norm,
  11567. model.layers[il].attn_norm_b,
  11568. LLM_NORM, cb, il);
  11569. cb(cur, "attn_norm", il);
  11570. // self-attention
  11571. {
  11572. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  11573. cb(cur, "wqkv", il);
  11574. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  11575. cb(cur, "bqkv", il);
  11576. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  11577. 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)));
  11578. 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)));
  11579. cb(Qcur, "Qcur", il);
  11580. cb(Kcur, "Kcur", il);
  11581. cb(Vcur, "Vcur", il);
  11582. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11583. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11584. model.layers[il].wo, model.layers[il].bo,
  11585. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11586. }
  11587. if (il == n_layer - 1) {
  11588. // skip computing output for unused tokens
  11589. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11590. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11591. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11592. }
  11593. // add the input
  11594. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  11595. cb(ffn_inp, "ffn_inp", il);
  11596. // FF
  11597. {
  11598. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11599. model.layers[il].ffn_norm,
  11600. model.layers[il].ffn_norm_b,
  11601. LLM_NORM, cb, il);
  11602. cb(cur, "ffn_norm", il);
  11603. cur = llm_build_ffn(ctx0, lctx, cur,
  11604. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  11605. NULL, NULL, NULL,
  11606. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  11607. NULL,
  11608. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  11609. cb(cur, "ffn_out", il);
  11610. }
  11611. cur = ggml_add(ctx0, cur, ffn_inp);
  11612. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11613. cb(cur, "l_out", il);
  11614. // input for next layer
  11615. inpL = cur;
  11616. }
  11617. cur = llm_build_norm(ctx0, inpL, hparams,
  11618. model.output_norm,
  11619. model.output_norm_b,
  11620. LLM_NORM, cb, -1);
  11621. cb(cur, "result_norm", -1);
  11622. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11623. cb(cur, "result_output", -1);
  11624. ggml_build_forward_expand(gf, cur);
  11625. return gf;
  11626. }
  11627. struct ggml_cgraph * build_codeshell() {
  11628. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11629. const int64_t n_embd_head = hparams.n_embd_head_v;
  11630. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11631. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11632. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11633. struct ggml_tensor * cur;
  11634. struct ggml_tensor * inpL;
  11635. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11636. // inp_pos - contains the positions
  11637. struct ggml_tensor * inp_pos = build_inp_pos();
  11638. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11639. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11640. for (int il = 0; il < n_layer; ++il) {
  11641. cur = llm_build_norm(ctx0, inpL, hparams,
  11642. model.layers[il].attn_norm,
  11643. model.layers[il].attn_norm_b,
  11644. LLM_NORM, cb, il);
  11645. cb(cur, "attn_norm", il);
  11646. // self-attention
  11647. {
  11648. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  11649. cb(cur, "wqkv", il);
  11650. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  11651. cb(cur, "bqkv", il);
  11652. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  11653. 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)));
  11654. 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)));
  11655. cb(tmpq, "tmpq", il);
  11656. cb(tmpk, "tmpk", il);
  11657. cb(Vcur, "Vcur", il);
  11658. struct ggml_tensor * Qcur = ggml_rope_ext(
  11659. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11660. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11661. ext_factor, attn_factor, beta_fast, beta_slow
  11662. );
  11663. cb(Qcur, "Qcur", il);
  11664. struct ggml_tensor * Kcur = ggml_rope_ext(
  11665. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11666. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11667. ext_factor, attn_factor, beta_fast, beta_slow
  11668. );
  11669. cb(Kcur, "Kcur", il);
  11670. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11671. model.layers[il].wo, model.layers[il].bo,
  11672. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11673. }
  11674. if (il == n_layer - 1) {
  11675. // skip computing output for unused tokens
  11676. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11677. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11678. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11679. }
  11680. // add the input
  11681. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  11682. cb(ffn_inp, "ffn_inp", il);
  11683. // FF
  11684. {
  11685. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11686. model.layers[il].ffn_norm,
  11687. model.layers[il].ffn_norm_b,
  11688. LLM_NORM, cb, il);
  11689. cb(cur, "ffn_norm", il);
  11690. cur = llm_build_ffn(ctx0, lctx, cur,
  11691. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  11692. NULL, NULL, NULL,
  11693. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  11694. NULL,
  11695. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  11696. cb(cur, "ffn_out", il);
  11697. }
  11698. cur = ggml_add(ctx0, cur, ffn_inp);
  11699. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11700. cb(cur, "l_out", il);
  11701. // input for next layer
  11702. inpL = cur;
  11703. }
  11704. cur = llm_build_norm(ctx0, inpL, hparams,
  11705. model.output_norm,
  11706. model.output_norm_b,
  11707. LLM_NORM, cb, -1);
  11708. cb(cur, "result_norm", -1);
  11709. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11710. cb(cur, "result_output", -1);
  11711. ggml_build_forward_expand(gf, cur);
  11712. return gf;
  11713. }
  11714. struct ggml_cgraph * build_orion() {
  11715. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11716. const int64_t n_embd_head = hparams.n_embd_head_v;
  11717. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11718. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11719. struct ggml_tensor * cur;
  11720. struct ggml_tensor * inpL;
  11721. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11722. // inp_pos - contains the positions
  11723. struct ggml_tensor * inp_pos = build_inp_pos();
  11724. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11725. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11726. for (int il = 0; il < n_layer; ++il) {
  11727. struct ggml_tensor * inpSA = inpL;
  11728. // norm
  11729. cur = llm_build_norm(ctx0, inpL, hparams,
  11730. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  11731. LLM_NORM, cb, il);
  11732. cb(cur, "attn_norm", il);
  11733. // self-attention
  11734. {
  11735. // compute Q and K and RoPE them
  11736. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11737. cb(Qcur, "Qcur", il);
  11738. // if (model.layers[il].bq) {
  11739. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  11740. // cb(Qcur, "Qcur", il);
  11741. // }
  11742. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11743. cb(Kcur, "Kcur", il);
  11744. // if (model.layers[il].bk) {
  11745. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  11746. // cb(Kcur, "Kcur", il);
  11747. // }
  11748. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11749. cb(Vcur, "Vcur", il);
  11750. // if (model.layers[il].bv) {
  11751. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11752. // cb(Vcur, "Vcur", il);
  11753. // }
  11754. Qcur = ggml_rope_ext(
  11755. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11756. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11757. ext_factor, attn_factor, beta_fast, beta_slow
  11758. );
  11759. cb(Qcur, "Qcur", il);
  11760. Kcur = ggml_rope_ext(
  11761. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11762. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11763. ext_factor, attn_factor, beta_fast, beta_slow
  11764. );
  11765. cb(Kcur, "Kcur", il);
  11766. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11767. model.layers[il].wo, NULL,
  11768. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11769. }
  11770. if (il == n_layer - 1) {
  11771. // skip computing output for unused tokens
  11772. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11773. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11774. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11775. }
  11776. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11777. cb(ffn_inp, "ffn_inp", il);
  11778. // feed-forward network
  11779. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11780. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  11781. LLM_NORM, cb, il);
  11782. cb(cur, "ffn_norm", il);
  11783. cur = llm_build_ffn(ctx0, lctx, cur,
  11784. model.layers[il].ffn_up, NULL, NULL,
  11785. model.layers[il].ffn_gate, NULL, NULL,
  11786. model.layers[il].ffn_down, NULL, NULL,
  11787. NULL,
  11788. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11789. cb(cur, "ffn_out", il);
  11790. cur = ggml_add(ctx0, cur, ffn_inp);
  11791. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11792. cb(cur, "l_out", il);
  11793. // input for next layer
  11794. inpL = cur;
  11795. }
  11796. cur = inpL;
  11797. cur = llm_build_norm(ctx0, cur, hparams,
  11798. model.output_norm, model.output_norm_b,
  11799. LLM_NORM, cb, -1);
  11800. cb(cur, "result_norm", -1);
  11801. // lm_head
  11802. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11803. cb(cur, "result_output", -1);
  11804. ggml_build_forward_expand(gf, cur);
  11805. return gf;
  11806. }
  11807. struct ggml_cgraph * build_internlm2() {
  11808. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11809. const int64_t n_embd_head = hparams.n_embd_head_v;
  11810. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11811. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11812. struct ggml_tensor * cur;
  11813. struct ggml_tensor * inpL;
  11814. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11815. // inp_pos - contains the positions
  11816. struct ggml_tensor * inp_pos = build_inp_pos();
  11817. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11818. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11819. for (int il = 0; il < n_layer; ++il) {
  11820. struct ggml_tensor * inpSA = inpL;
  11821. // norm
  11822. cur = llm_build_norm(ctx0, inpL, hparams,
  11823. model.layers[il].attn_norm, NULL,
  11824. LLM_NORM_RMS, cb, il);
  11825. cb(cur, "attn_norm", il);
  11826. // self-attention
  11827. {
  11828. // compute Q and K and RoPE them
  11829. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11830. cb(Qcur, "Qcur", il);
  11831. if (model.layers[il].bq) {
  11832. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  11833. cb(Qcur, "Qcur", il);
  11834. }
  11835. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11836. cb(Kcur, "Kcur", il);
  11837. if (model.layers[il].bk) {
  11838. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  11839. cb(Kcur, "Kcur", il);
  11840. }
  11841. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11842. cb(Vcur, "Vcur", il);
  11843. if (model.layers[il].bv) {
  11844. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11845. cb(Vcur, "Vcur", il);
  11846. }
  11847. Qcur = ggml_rope_ext(
  11848. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11849. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11850. ext_factor, attn_factor, beta_fast, beta_slow
  11851. );
  11852. cb(Qcur, "Qcur", il);
  11853. Kcur = ggml_rope_ext(
  11854. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11855. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11856. ext_factor, attn_factor, beta_fast, beta_slow
  11857. );
  11858. cb(Kcur, "Kcur", il);
  11859. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11860. model.layers[il].wo, model.layers[il].bo,
  11861. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11862. }
  11863. if (il == n_layer - 1) {
  11864. // skip computing output for unused tokens
  11865. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11866. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11867. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11868. }
  11869. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11870. cb(ffn_inp, "ffn_inp", il);
  11871. // feed-forward network
  11872. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11873. model.layers[il].ffn_norm, NULL,
  11874. LLM_NORM_RMS, cb, il);
  11875. cb(cur, "ffn_norm", il);
  11876. cur = llm_build_ffn(ctx0, lctx, cur,
  11877. model.layers[il].ffn_up, NULL, NULL,
  11878. model.layers[il].ffn_gate, NULL, NULL,
  11879. model.layers[il].ffn_down, NULL, NULL,
  11880. NULL,
  11881. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11882. cb(cur, "ffn_out", il);
  11883. cur = ggml_add(ctx0, cur, ffn_inp);
  11884. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11885. cb(cur, "l_out", il);
  11886. // input for next layer
  11887. inpL = cur;
  11888. }
  11889. cur = inpL;
  11890. cur = llm_build_norm(ctx0, cur, hparams,
  11891. model.output_norm, NULL,
  11892. LLM_NORM_RMS, cb, -1);
  11893. cb(cur, "result_norm", -1);
  11894. // lm_head
  11895. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11896. cb(cur, "result_output", -1);
  11897. ggml_build_forward_expand(gf, cur);
  11898. return gf;
  11899. }
  11900. // ref: https://arxiv.org/abs/2203.03466
  11901. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  11902. // based on the original build_llama() function
  11903. struct ggml_cgraph * build_minicpm() {
  11904. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11905. const int64_t n_embd_head = hparams.n_embd_head_v;
  11906. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11907. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11908. const int64_t n_embd = hparams.n_embd;
  11909. //TODO: if the model varies, these parameters need to be read from the model
  11910. const int64_t n_embd_base = 256;
  11911. const float scale_embd = 12.0f;
  11912. const float scale_depth = 1.4f;
  11913. struct ggml_tensor * cur;
  11914. struct ggml_tensor * inpL;
  11915. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11916. // scale the input embeddings
  11917. inpL = ggml_scale(ctx0, inpL, scale_embd);
  11918. cb(inpL, "inp_scaled", -1);
  11919. // inp_pos - contains the positions
  11920. struct ggml_tensor * inp_pos = build_inp_pos();
  11921. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11922. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11923. for (int il = 0; il < n_layer; ++il) {
  11924. struct ggml_tensor * inpSA = inpL;
  11925. // norm
  11926. cur = llm_build_norm(ctx0, inpL, hparams,
  11927. model.layers[il].attn_norm, NULL,
  11928. LLM_NORM_RMS, cb, il);
  11929. cb(cur, "attn_norm", il);
  11930. // self-attention
  11931. {
  11932. // compute Q and K and RoPE them
  11933. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11934. cb(Qcur, "Qcur", il);
  11935. if (model.layers[il].bq) {
  11936. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  11937. cb(Qcur, "Qcur", il);
  11938. }
  11939. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11940. cb(Kcur, "Kcur", il);
  11941. if (model.layers[il].bk) {
  11942. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  11943. cb(Kcur, "Kcur", il);
  11944. }
  11945. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11946. cb(Vcur, "Vcur", il);
  11947. if (model.layers[il].bv) {
  11948. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11949. cb(Vcur, "Vcur", il);
  11950. }
  11951. Qcur = ggml_rope_ext(
  11952. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11953. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11954. ext_factor, attn_factor, beta_fast, beta_slow
  11955. );
  11956. cb(Qcur, "Qcur", il);
  11957. Kcur = ggml_rope_ext(
  11958. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11959. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11960. ext_factor, attn_factor, beta_fast, beta_slow
  11961. );
  11962. cb(Kcur, "Kcur", il);
  11963. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11964. model.layers[il].wo, model.layers[il].bo,
  11965. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11966. }
  11967. if (il == n_layer - 1) {
  11968. // skip computing output for unused tokens
  11969. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11970. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11971. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11972. }
  11973. // scale_res - scale the hidden states for residual connection
  11974. const float scale_res = scale_depth/sqrtf(float(n_layer));
  11975. cur = ggml_scale(ctx0, cur, scale_res);
  11976. cb(cur, "hidden_scaled", -1);
  11977. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11978. cb(ffn_inp, "ffn_inp", il);
  11979. // feed-forward network
  11980. {
  11981. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11982. model.layers[il].ffn_norm, NULL,
  11983. LLM_NORM_RMS, cb, il);
  11984. cb(cur, "ffn_norm", il);
  11985. cur = llm_build_ffn(ctx0, lctx, cur,
  11986. model.layers[il].ffn_up, NULL, NULL,
  11987. model.layers[il].ffn_gate, NULL, NULL,
  11988. model.layers[il].ffn_down, NULL, NULL,
  11989. NULL,
  11990. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11991. cb(cur, "ffn_out", il);
  11992. }
  11993. // scale the hidden states for residual connection
  11994. cur = ggml_scale(ctx0, cur, scale_res);
  11995. cb(cur, "hidden_scaled_ffn", -1);
  11996. cur = ggml_add(ctx0, cur, ffn_inp);
  11997. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11998. cb(cur, "l_out", il);
  11999. // input for next layer
  12000. inpL = cur;
  12001. }
  12002. cur = inpL;
  12003. cur = llm_build_norm(ctx0, cur, hparams,
  12004. model.output_norm, NULL,
  12005. LLM_NORM_RMS, cb, -1);
  12006. cb(cur, "result_norm", -1);
  12007. // lm_head scaling
  12008. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  12009. cur = ggml_scale(ctx0, cur, scale_lmhead);
  12010. cb(cur, "lmhead_scaling", -1);
  12011. // lm_head
  12012. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12013. cb(cur, "result_output", -1);
  12014. ggml_build_forward_expand(gf, cur);
  12015. return gf;
  12016. }
  12017. struct ggml_cgraph * build_minicpm3() {
  12018. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12019. //TODO: if the model varies, these parameters need to be read from the model
  12020. const int64_t n_embd_base = 256;
  12021. const float scale_embd = 12.0f;
  12022. const float scale_depth = 1.4f;
  12023. const float kq_scale = 1.0f / sqrtf(float(hparams.n_embd_head_k));
  12024. const uint32_t n_embd_head_qk_rope = hparams.n_rot;
  12025. const uint32_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  12026. const uint32_t kv_lora_rank = hparams.n_lora_kv;
  12027. struct ggml_tensor * cur;
  12028. struct ggml_tensor * inpL;
  12029. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12030. // scale the input embeddings
  12031. inpL = ggml_scale(ctx0, inpL, scale_embd);
  12032. cb(inpL, "inp_scaled", -1);
  12033. // inp_pos - contains the positions
  12034. struct ggml_tensor * inp_pos = build_inp_pos();
  12035. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12036. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12037. for (int il = 0; il < n_layer; ++il) {
  12038. struct ggml_tensor * inpSA = inpL;
  12039. struct ggml_tensor * rope_factors = build_rope_factors(il);
  12040. // norm
  12041. cur = llm_build_norm(ctx0, inpL, hparams,
  12042. model.layers[il].attn_norm, NULL,
  12043. LLM_NORM_RMS, cb, il);
  12044. cb(cur, "attn_norm", il);
  12045. // self_attention
  12046. {
  12047. struct ggml_tensor * q = NULL;
  12048. // {n_embd, q_lora_rank} * {n_embd, n_tokens} -> {q_lora_rank, n_tokens}
  12049. q = ggml_mul_mat(ctx0, model.layers[il].wq_a, cur);
  12050. cb(q, "q", il);
  12051. q = llm_build_norm(ctx0, q, hparams,
  12052. model.layers[il].attn_q_a_norm, NULL,
  12053. LLM_NORM_RMS, cb, il);
  12054. cb(q, "q", il);
  12055. // {q_lora_rank, n_head * hparams.n_embd_head_k} * {q_lora_rank, n_tokens} -> {n_head * hparams.n_embd_head_k, n_tokens}
  12056. q = ggml_mul_mat(ctx0, model.layers[il].wq_b, q);
  12057. cb(q, "q", il);
  12058. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  12059. struct ggml_tensor * q_nope = ggml_view_3d(ctx0, q, n_embd_head_qk_nope, n_head, n_tokens,
  12060. ggml_row_size(q->type, hparams.n_embd_head_k),
  12061. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  12062. 0);
  12063. cb(q_nope, "q_nope", il);
  12064. // and {n_head * n_embd_head_qk_rope, n_tokens}
  12065. struct ggml_tensor * q_pe = ggml_view_3d(ctx0, q, n_embd_head_qk_rope, n_head, n_tokens,
  12066. ggml_row_size(q->type, hparams.n_embd_head_k),
  12067. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  12068. ggml_row_size(q->type, n_embd_head_qk_nope));
  12069. cb(q_pe, "q_pe", il);
  12070. // {n_embd, kv_lora_rank + n_embd_head_qk_rope} * {n_embd, n_tokens} -> {kv_lora_rank + n_embd_head_qk_rope, n_tokens}
  12071. struct ggml_tensor * kv_pe_compresseed = ggml_mul_mat(ctx0, model.layers[il].wkv_a_mqa, cur);
  12072. cb(kv_pe_compresseed, "kv_pe_compresseed", il);
  12073. // split into {kv_lora_rank, n_tokens}
  12074. struct ggml_tensor * kv_compressed = ggml_view_2d(ctx0, kv_pe_compresseed, kv_lora_rank, n_tokens,
  12075. kv_pe_compresseed->nb[1],
  12076. 0);
  12077. cb(kv_compressed, "kv_compressed", il);
  12078. // and {n_embd_head_qk_rope, n_tokens}
  12079. struct ggml_tensor * k_pe = ggml_view_3d(ctx0, kv_pe_compresseed, n_embd_head_qk_rope, 1, n_tokens,
  12080. kv_pe_compresseed->nb[1],
  12081. kv_pe_compresseed->nb[1],
  12082. ggml_row_size(kv_pe_compresseed->type, kv_lora_rank));
  12083. cb(k_pe, "k_pe", il);
  12084. kv_compressed = ggml_cont(ctx0, kv_compressed); // TODO: the CUDA backend does not support non-contiguous norm
  12085. kv_compressed = llm_build_norm(ctx0, kv_compressed, hparams,
  12086. model.layers[il].attn_kv_a_norm, NULL,
  12087. LLM_NORM_RMS, cb, il);
  12088. cb(kv_compressed, "kv_compressed", il);
  12089. // {kv_lora_rank, n_head * (n_embd_head_qk_nope + n_embd_head_v)} * {kv_lora_rank, n_tokens} -> {n_head * (n_embd_head_qk_nope + n_embd_head_v), n_tokens}
  12090. struct ggml_tensor * kv = ggml_mul_mat(ctx0, model.layers[il].wkv_b, kv_compressed);
  12091. cb(kv, "kv", il);
  12092. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  12093. struct ggml_tensor * k_nope = ggml_view_3d(ctx0, kv, n_embd_head_qk_nope, n_head, n_tokens,
  12094. ggml_row_size(kv->type, n_embd_head_qk_nope + hparams.n_embd_head_v),
  12095. ggml_row_size(kv->type, n_head * (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  12096. 0);
  12097. cb(k_nope, "k_nope", il);
  12098. // and {n_head * n_embd_head_v, n_tokens}
  12099. struct ggml_tensor * v_states = ggml_view_3d(ctx0, kv, hparams.n_embd_head_v, n_head, n_tokens,
  12100. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  12101. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)*n_head),
  12102. ggml_row_size(kv->type, (n_embd_head_qk_nope)));
  12103. cb(v_states, "v_states", il);
  12104. v_states = ggml_cont(ctx0, v_states);
  12105. cb(v_states, "v_states", il);
  12106. v_states = ggml_view_2d(ctx0, v_states, hparams.n_embd_head_v * n_head, n_tokens,
  12107. ggml_row_size(kv->type, hparams.n_embd_head_v * n_head),
  12108. 0);
  12109. cb(v_states, "v_states", il);
  12110. q_pe = ggml_cont(ctx0, q_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  12111. q_pe = ggml_rope_ext(
  12112. ctx0, q_pe, inp_pos, rope_factors,
  12113. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12114. ext_factor, attn_factor, beta_fast, beta_slow
  12115. );
  12116. cb(q_pe, "q_pe", il);
  12117. // shared RoPE key
  12118. k_pe = ggml_cont(ctx0, k_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  12119. k_pe = ggml_rope_ext(
  12120. ctx0, k_pe, inp_pos, rope_factors,
  12121. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12122. ext_factor, attn_factor, beta_fast, beta_slow
  12123. );
  12124. cb(k_pe, "k_pe", il);
  12125. struct ggml_tensor * q_states = ggml_concat(ctx0, q_nope, q_pe, 0);
  12126. cb(q_states, "q_states", il);
  12127. struct ggml_tensor * k_states = ggml_concat(ctx0, k_nope, ggml_repeat(ctx0, k_pe, q_pe), 0);
  12128. cb(k_states, "k_states", il);
  12129. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12130. model.layers[il].wo, NULL,
  12131. k_states, v_states, q_states, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  12132. }
  12133. if (il == n_layer - 1) {
  12134. // skip computing output for unused tokens
  12135. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12136. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12137. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12138. }
  12139. // scale_res - scale the hidden states for residual connection
  12140. const float scale_res = scale_depth/sqrtf(float(n_layer));
  12141. cur = ggml_scale(ctx0, cur, scale_res);
  12142. cb(cur, "hidden_scaled", il);
  12143. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12144. cb(ffn_inp, "ffn_inp", il);
  12145. // feed-forward network
  12146. {
  12147. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12148. model.layers[il].ffn_norm, NULL,
  12149. LLM_NORM_RMS, cb, il);
  12150. cb(cur, "ffn_norm", il);
  12151. cur = llm_build_ffn(ctx0, lctx, cur,
  12152. model.layers[il].ffn_up, NULL, NULL,
  12153. model.layers[il].ffn_gate, NULL, NULL,
  12154. model.layers[il].ffn_down, NULL, NULL,
  12155. NULL,
  12156. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12157. cb(cur, "ffn_out", il);
  12158. }
  12159. // scale the hidden states for residual connection
  12160. cur = ggml_scale(ctx0, cur, scale_res);
  12161. cb(cur, "hidden_scaled_ffn", il);
  12162. cur = ggml_add(ctx0, cur, ffn_inp);
  12163. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12164. cb(cur, "l_out", il);
  12165. // input for next layer
  12166. inpL = cur;
  12167. }
  12168. cur = inpL;
  12169. cur = llm_build_norm(ctx0, cur, hparams,
  12170. model.output_norm, NULL,
  12171. LLM_NORM_RMS, cb, -1);
  12172. cb(cur, "result_norm", -1);
  12173. // lm_head scaling
  12174. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  12175. cur = ggml_scale(ctx0, cur, scale_lmhead);
  12176. cb(cur, "lmhead_scaling", -1);
  12177. // lm_head
  12178. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12179. cb(cur, "result_output", -1);
  12180. ggml_build_forward_expand(gf, cur);
  12181. return gf;
  12182. }
  12183. struct ggml_cgraph * build_gemma() {
  12184. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12185. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  12186. struct ggml_tensor * cur;
  12187. struct ggml_tensor * inpL;
  12188. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12189. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  12190. cb(inpL, "inp_scaled", -1);
  12191. // inp_pos - contains the positions
  12192. struct ggml_tensor * inp_pos = build_inp_pos();
  12193. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12194. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12195. for (int il = 0; il < n_layer; ++il) {
  12196. // norm
  12197. cur = llm_build_norm(ctx0, inpL, hparams,
  12198. model.layers[il].attn_norm, NULL,
  12199. LLM_NORM_RMS, cb, il);
  12200. cb(cur, "attn_norm", il);
  12201. // self-attention
  12202. {
  12203. // compute Q and K and RoPE them
  12204. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12205. cb(Qcur, "Qcur", il);
  12206. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12207. cb(Kcur, "Kcur", il);
  12208. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12209. cb(Vcur, "Vcur", il);
  12210. Qcur = ggml_rope_ext(
  12211. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos, nullptr,
  12212. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12213. ext_factor, attn_factor, beta_fast, beta_slow);
  12214. cb(Qcur, "Qcur", il);
  12215. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  12216. cb(Qcur, "Qcur_scaled", il);
  12217. Kcur = ggml_rope_ext(
  12218. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos, nullptr,
  12219. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12220. ext_factor, attn_factor, beta_fast, beta_slow);
  12221. cb(Kcur, "Kcur", il);
  12222. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12223. model.layers[il].wo, NULL,
  12224. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  12225. }
  12226. if (il == n_layer - 1) {
  12227. // skip computing output for unused tokens
  12228. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12229. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12230. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  12231. }
  12232. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  12233. cb(sa_out, "sa_out", il);
  12234. cur = llm_build_norm(ctx0, sa_out, hparams,
  12235. model.layers[il].ffn_norm, NULL,
  12236. LLM_NORM_RMS, cb, il);
  12237. cb(cur, "ffn_norm", il);
  12238. // feed-forward network
  12239. {
  12240. cur = llm_build_ffn(ctx0, lctx, cur,
  12241. model.layers[il].ffn_up, NULL, NULL,
  12242. model.layers[il].ffn_gate, NULL, NULL,
  12243. model.layers[il].ffn_down, NULL, NULL,
  12244. NULL,
  12245. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  12246. cb(cur, "ffn_out", il);
  12247. }
  12248. cur = ggml_add(ctx0, cur, sa_out);
  12249. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12250. cb(cur, "l_out", il);
  12251. // input for next layer
  12252. inpL = cur;
  12253. }
  12254. cur = inpL;
  12255. cur = llm_build_norm(ctx0, cur, hparams,
  12256. model.output_norm, NULL,
  12257. LLM_NORM_RMS, cb, -1);
  12258. cb(cur, "result_norm", -1);
  12259. // lm_head
  12260. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12261. cb(cur, "result_output", -1);
  12262. ggml_build_forward_expand(gf, cur);
  12263. return gf;
  12264. }
  12265. struct ggml_cgraph * build_gemma2() {
  12266. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12267. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  12268. struct ggml_tensor * cur;
  12269. struct ggml_tensor * inpL;
  12270. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12271. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  12272. cb(inpL, "inp_scaled", -1);
  12273. // inp_pos - contains the positions
  12274. struct ggml_tensor * inp_pos = build_inp_pos();
  12275. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12276. // gemma 2 requires different mask for layers using sliding window (SWA)
  12277. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(true);
  12278. struct ggml_tensor * KQ_mask_swa = build_inp_KQ_mask_swa(true);
  12279. for (int il = 0; il < n_layer; ++il) {
  12280. // (il % 2) layers use SWA
  12281. struct ggml_tensor * KQ_mask_l = (il % 2 == 0) ? KQ_mask_swa : KQ_mask;
  12282. // norm
  12283. cur = llm_build_norm(ctx0, inpL, hparams,
  12284. model.layers[il].attn_norm, NULL,
  12285. LLM_NORM_RMS, cb, il);
  12286. cb(cur, "attn_norm", il);
  12287. // self-attention
  12288. {
  12289. // compute Q and K and RoPE them
  12290. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12291. cb(Qcur, "Qcur", il);
  12292. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12293. cb(Kcur, "Kcur", il);
  12294. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12295. cb(Vcur, "Vcur", il);
  12296. Qcur = ggml_rope_ext(
  12297. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos, nullptr,
  12298. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12299. ext_factor, attn_factor, beta_fast, beta_slow);
  12300. cb(Qcur, "Qcur", il);
  12301. // ref: https://github.com/google/gemma_pytorch/commit/03e657582d17cb5a8617ebf333c1c16f3694670e
  12302. switch (model.type) {
  12303. case e_model::MODEL_2B:
  12304. case e_model::MODEL_9B: Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k))); break;
  12305. case e_model::MODEL_27B: Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd / n_head))); break;
  12306. default: GGML_ABORT("fatal error");
  12307. };
  12308. cb(Qcur, "Qcur_scaled", il);
  12309. Kcur = ggml_rope_ext(
  12310. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos, nullptr,
  12311. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12312. ext_factor, attn_factor, beta_fast, beta_slow);
  12313. cb(Kcur, "Kcur", il);
  12314. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12315. model.layers[il].wo, NULL,
  12316. Kcur, Vcur, Qcur, KQ_mask_l, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  12317. }
  12318. cur = llm_build_norm(ctx0, cur, hparams,
  12319. model.layers[il].attn_post_norm, NULL,
  12320. LLM_NORM_RMS, cb, il);
  12321. cb(cur, "attn_post_norm", il);
  12322. if (il == n_layer - 1) {
  12323. // skip computing output for unused tokens
  12324. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12325. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12326. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  12327. }
  12328. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  12329. cb(sa_out, "sa_out", il);
  12330. cur = llm_build_norm(ctx0, sa_out, hparams,
  12331. model.layers[il].ffn_norm, NULL,
  12332. LLM_NORM_RMS, cb, il);
  12333. cb(cur, "ffn_norm", il);
  12334. // feed-forward network
  12335. {
  12336. cur = llm_build_ffn(ctx0, lctx, cur,
  12337. model.layers[il].ffn_up, NULL, NULL,
  12338. model.layers[il].ffn_gate, NULL, NULL,
  12339. model.layers[il].ffn_down, NULL, NULL,
  12340. NULL,
  12341. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  12342. cb(cur, "ffn_out", il);
  12343. }
  12344. cur = llm_build_norm(ctx0, cur, hparams,
  12345. model.layers[il].ffn_post_norm, NULL,
  12346. LLM_NORM_RMS, cb, -1);
  12347. cb(cur, "ffn_post_norm", -1);
  12348. cur = ggml_add(ctx0, cur, sa_out);
  12349. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12350. cb(cur, "l_out", il);
  12351. // input for next layer
  12352. inpL = cur;
  12353. }
  12354. cur = inpL;
  12355. cur = llm_build_norm(ctx0, cur, hparams,
  12356. model.output_norm, NULL,
  12357. LLM_NORM_RMS, cb, -1);
  12358. cb(cur, "result_norm", -1);
  12359. // lm_head
  12360. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12361. // final logit soft-capping
  12362. cur = ggml_scale(ctx0, cur, 1.0f / hparams.f_final_logit_softcapping);
  12363. cur = ggml_tanh(ctx0, cur);
  12364. cur = ggml_scale(ctx0, cur, hparams.f_final_logit_softcapping);
  12365. cb(cur, "result_output", -1);
  12366. ggml_build_forward_expand(gf, cur);
  12367. return gf;
  12368. }
  12369. struct ggml_cgraph * build_starcoder2() {
  12370. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12371. const int64_t n_embd_head = hparams.n_embd_head_v;
  12372. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12373. GGML_ASSERT(n_embd_head == hparams.n_rot);
  12374. struct ggml_tensor * cur;
  12375. struct ggml_tensor * inpL;
  12376. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12377. // inp_pos - contains the positions
  12378. struct ggml_tensor * inp_pos = build_inp_pos();
  12379. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12380. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12381. for (int il = 0; il < n_layer; ++il) {
  12382. struct ggml_tensor * inpSA = inpL;
  12383. // norm
  12384. cur = llm_build_norm(ctx0, inpL, hparams,
  12385. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  12386. LLM_NORM, cb, il);
  12387. cb(cur, "attn_norm", il);
  12388. // self-attention
  12389. {
  12390. // compute Q and K and RoPE them
  12391. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12392. cb(Qcur, "Qcur", il);
  12393. if (model.layers[il].bq) {
  12394. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  12395. cb(Qcur, "Qcur", il);
  12396. }
  12397. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12398. cb(Kcur, "Kcur", il);
  12399. if (model.layers[il].bk) {
  12400. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  12401. cb(Kcur, "Kcur", il);
  12402. }
  12403. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12404. cb(Vcur, "Vcur", il);
  12405. if (model.layers[il].bv) {
  12406. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  12407. cb(Vcur, "Vcur", il);
  12408. }
  12409. Qcur = ggml_rope_ext(
  12410. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  12411. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12412. ext_factor, attn_factor, beta_fast, beta_slow
  12413. );
  12414. cb(Qcur, "Qcur", il);
  12415. Kcur = ggml_rope_ext(
  12416. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  12417. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12418. ext_factor, attn_factor, beta_fast, beta_slow
  12419. );
  12420. cb(Kcur, "Kcur", il);
  12421. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12422. model.layers[il].wo, model.layers[il].bo,
  12423. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12424. }
  12425. if (il == n_layer - 1) {
  12426. // skip computing output for unused tokens
  12427. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12428. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12429. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12430. }
  12431. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12432. cb(ffn_inp, "ffn_inp", il);
  12433. // feed-forward network
  12434. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12435. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  12436. LLM_NORM, cb, il);
  12437. cb(cur, "ffn_norm", il);
  12438. cur = llm_build_ffn(ctx0, lctx, cur,
  12439. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  12440. NULL, NULL, NULL,
  12441. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  12442. NULL,
  12443. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  12444. cb(cur, "ffn_out", il);
  12445. cur = ggml_add(ctx0, cur, ffn_inp);
  12446. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12447. cb(cur, "l_out", il);
  12448. // input for next layer
  12449. inpL = cur;
  12450. }
  12451. cur = inpL;
  12452. cur = llm_build_norm(ctx0, cur, hparams,
  12453. model.output_norm, model.output_norm_b,
  12454. LLM_NORM, cb, -1);
  12455. cb(cur, "result_norm", -1);
  12456. // lm_head
  12457. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12458. cb(cur, "result_output", -1);
  12459. ggml_build_forward_expand(gf, cur);
  12460. return gf;
  12461. }
  12462. struct ggml_cgraph * build_mamba() {
  12463. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12464. struct ggml_tensor * cur;
  12465. struct ggml_tensor * inpL;
  12466. // {n_embd, n_tokens}
  12467. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12468. struct ggml_tensor * state_copy = build_inp_s_copy();
  12469. struct ggml_tensor * state_mask = build_inp_s_mask();
  12470. for (int il = 0; il < n_layer; ++il) {
  12471. // norm
  12472. cur = llm_build_norm(ctx0, inpL, hparams,
  12473. model.layers[il].attn_norm, NULL,
  12474. LLM_NORM_RMS, cb, il);
  12475. cb(cur, "attn_norm", il);
  12476. cur = llm_build_mamba(ctx0, lctx, ubatch, gf, cur,
  12477. state_copy, state_mask,
  12478. kv_head, n_kv, cb, il);
  12479. if (il == n_layer - 1) {
  12480. // skip computing output for unused tokens
  12481. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12482. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12483. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  12484. }
  12485. // residual
  12486. cur = ggml_add(ctx0, cur, inpL);
  12487. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12488. cb(cur, "l_out", il);
  12489. // input for next layer
  12490. inpL = cur;
  12491. }
  12492. // final rmsnorm
  12493. cur = llm_build_norm(ctx0, inpL, hparams,
  12494. model.output_norm, NULL,
  12495. LLM_NORM_RMS, cb, -1);
  12496. cb(cur, "result_norm", -1);
  12497. // lm_head
  12498. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12499. cb(cur, "result_output", -1);
  12500. ggml_build_forward_expand(gf, cur);
  12501. return gf;
  12502. }
  12503. struct ggml_cgraph * build_command_r() {
  12504. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12505. const int64_t n_embd_head = hparams.n_embd_head_v;
  12506. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12507. const float f_logit_scale = hparams.f_logit_scale;
  12508. struct ggml_tensor * cur;
  12509. struct ggml_tensor * inpL;
  12510. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12511. // inp_pos - contains the positions
  12512. struct ggml_tensor * inp_pos = build_inp_pos();
  12513. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12514. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12515. for (int il = 0; il < n_layer; ++il) {
  12516. // norm
  12517. cur = llm_build_norm(ctx0, inpL, hparams,
  12518. model.layers[il].attn_norm, NULL,
  12519. LLM_NORM, cb, il);
  12520. cb(cur, "attn_norm", il);
  12521. struct ggml_tensor * ffn_inp = cur;
  12522. // self-attention
  12523. {
  12524. // compute Q and K and RoPE them
  12525. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12526. cb(Qcur, "Qcur", il);
  12527. if (model.layers[il].bq) {
  12528. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  12529. cb(Qcur, "Qcur", il);
  12530. }
  12531. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12532. cb(Kcur, "Kcur", il);
  12533. if (model.layers[il].bk) {
  12534. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  12535. cb(Kcur, "Kcur", il);
  12536. }
  12537. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12538. cb(Vcur, "Vcur", il);
  12539. if (model.layers[il].bv) {
  12540. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  12541. cb(Vcur, "Vcur", il);
  12542. }
  12543. if (model.layers[il].attn_q_norm) {
  12544. Qcur = ggml_view_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens,
  12545. ggml_element_size(Qcur) * n_embd_head,
  12546. ggml_element_size(Qcur) * n_embd_head * n_head,
  12547. 0);
  12548. cb(Qcur, "Qcur", il);
  12549. Kcur = ggml_view_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens,
  12550. ggml_element_size(Kcur) * n_embd_head,
  12551. ggml_element_size(Kcur) * n_embd_head * n_head_kv,
  12552. 0);
  12553. cb(Kcur, "Kcur", il);
  12554. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  12555. model.layers[il].attn_q_norm,
  12556. NULL,
  12557. LLM_NORM, cb, il);
  12558. cb(Qcur, "Qcur", il);
  12559. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  12560. model.layers[il].attn_k_norm,
  12561. NULL,
  12562. LLM_NORM, cb, il);
  12563. cb(Kcur, "Kcur", il);
  12564. }
  12565. Qcur = ggml_rope_ext(
  12566. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  12567. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12568. ext_factor, attn_factor, beta_fast, beta_slow
  12569. );
  12570. cb(Qcur, "Qcur", il);
  12571. Kcur = ggml_rope_ext(
  12572. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  12573. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12574. ext_factor, attn_factor, beta_fast, beta_slow
  12575. );
  12576. cb(Kcur, "Kcur", il);
  12577. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12578. model.layers[il].wo, model.layers[il].bo,
  12579. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12580. }
  12581. if (il == n_layer - 1) {
  12582. // skip computing output for unused tokens
  12583. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12584. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12585. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  12586. ffn_inp = ggml_get_rows(ctx0, ffn_inp, inp_out_ids);
  12587. }
  12588. struct ggml_tensor * attn_out = cur;
  12589. // feed-forward network
  12590. {
  12591. cur = llm_build_ffn(ctx0, lctx, ffn_inp,
  12592. model.layers[il].ffn_up, NULL, NULL,
  12593. model.layers[il].ffn_gate, NULL, NULL,
  12594. model.layers[il].ffn_down, NULL, NULL,
  12595. NULL,
  12596. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12597. cb(cur, "ffn_out", il);
  12598. }
  12599. // add together residual + FFN + self-attention
  12600. cur = ggml_add(ctx0, cur, inpL);
  12601. cur = ggml_add(ctx0, cur, attn_out);
  12602. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12603. cb(cur, "l_out", il);
  12604. // input for next layer
  12605. inpL = cur;
  12606. }
  12607. cur = inpL;
  12608. cur = llm_build_norm(ctx0, cur, hparams,
  12609. model.output_norm, NULL,
  12610. LLM_NORM, cb, -1);
  12611. cb(cur, "result_norm", -1);
  12612. // lm_head
  12613. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12614. if (f_logit_scale) {
  12615. cur = ggml_scale(ctx0, cur, f_logit_scale);
  12616. }
  12617. cb(cur, "result_output", -1);
  12618. ggml_build_forward_expand(gf, cur);
  12619. return gf;
  12620. }
  12621. // ref: https://allenai.org/olmo
  12622. // based on the original build_llama() function, changes:
  12623. // * non-parametric layer norm
  12624. // * clamp qkv
  12625. // * removed bias
  12626. // * removed MoE
  12627. struct ggml_cgraph * build_olmo() {
  12628. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12629. // mutable variable, needed during the last layer of the computation to skip unused tokens
  12630. int32_t n_tokens = this->n_tokens;
  12631. const int64_t n_embd_head = hparams.n_embd_head_v;
  12632. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12633. GGML_ASSERT(n_embd_head == hparams.n_rot);
  12634. struct ggml_tensor * cur;
  12635. struct ggml_tensor * inpL;
  12636. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12637. // inp_pos - contains the positions
  12638. struct ggml_tensor * inp_pos = build_inp_pos();
  12639. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12640. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12641. for (int il = 0; il < n_layer; ++il) {
  12642. struct ggml_tensor * inpSA = inpL;
  12643. // norm
  12644. cur = llm_build_norm(ctx0, inpL, hparams,
  12645. NULL, NULL,
  12646. LLM_NORM, cb, il);
  12647. cb(cur, "attn_norm", il);
  12648. // self-attention
  12649. {
  12650. // compute Q and K and RoPE them
  12651. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12652. cb(Qcur, "Qcur", il);
  12653. if (hparams.f_clamp_kqv > 0.0f) {
  12654. Qcur = ggml_clamp(ctx0, Qcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  12655. cb(Qcur, "Qcur", il);
  12656. }
  12657. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12658. cb(Kcur, "Kcur", il);
  12659. if (hparams.f_clamp_kqv > 0.0f) {
  12660. Kcur = ggml_clamp(ctx0, Kcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  12661. cb(Kcur, "Kcur", il);
  12662. }
  12663. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12664. cb(Vcur, "Vcur", il);
  12665. if (hparams.f_clamp_kqv > 0.0f) {
  12666. Vcur = ggml_clamp(ctx0, Vcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  12667. cb(Vcur, "Vcur", il);
  12668. }
  12669. Qcur = ggml_rope_ext(
  12670. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  12671. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12672. ext_factor, attn_factor, beta_fast, beta_slow
  12673. );
  12674. cb(Qcur, "Qcur", il);
  12675. Kcur = ggml_rope_ext(
  12676. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  12677. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12678. ext_factor, attn_factor, beta_fast, beta_slow
  12679. );
  12680. cb(Kcur, "Kcur", il);
  12681. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12682. model.layers[il].wo, nullptr,
  12683. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12684. }
  12685. if (il == n_layer - 1) {
  12686. // skip computing output for unused tokens
  12687. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12688. n_tokens = n_outputs;
  12689. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12690. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12691. }
  12692. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12693. cb(ffn_inp, "ffn_inp", il);
  12694. // feed-forward network
  12695. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12696. NULL, NULL,
  12697. LLM_NORM, cb, il);
  12698. cb(cur, "ffn_norm", il);
  12699. cur = llm_build_ffn(ctx0, lctx, cur,
  12700. model.layers[il].ffn_up, NULL, NULL,
  12701. model.layers[il].ffn_gate, NULL, NULL,
  12702. model.layers[il].ffn_down, NULL, NULL,
  12703. NULL,
  12704. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12705. cb(cur, "ffn_out", il);
  12706. cur = ggml_add(ctx0, cur, ffn_inp);
  12707. cb(cur, "ffn_out", il);
  12708. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12709. cb(cur, "l_out", il);
  12710. // input for next layer
  12711. inpL = cur;
  12712. }
  12713. cur = inpL;
  12714. cur = llm_build_norm(ctx0, cur, hparams,
  12715. NULL, NULL,
  12716. LLM_NORM, cb, -1);
  12717. cb(cur, "result_norm", -1);
  12718. // lm_head
  12719. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12720. cb(cur, "result_output", -1);
  12721. ggml_build_forward_expand(gf, cur);
  12722. return gf;
  12723. }
  12724. struct ggml_cgraph * build_olmo2() {
  12725. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12726. // mutable variable, needed during the last layer of the computation to skip unused tokens
  12727. int32_t n_tokens = this->n_tokens;
  12728. const int64_t n_embd_head = hparams.n_embd_head_v;
  12729. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12730. GGML_ASSERT(n_embd_head == hparams.n_rot);
  12731. struct ggml_tensor * cur;
  12732. struct ggml_tensor * inpL;
  12733. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12734. // inp_pos - contains the positions
  12735. struct ggml_tensor * inp_pos = build_inp_pos();
  12736. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12737. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12738. for (int il = 0; il < n_layer; ++il) {
  12739. struct ggml_tensor * inpSA = inpL;
  12740. cur = inpL;
  12741. // self_attention
  12742. {
  12743. // compute Q and K and RoPE them
  12744. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12745. cb(Qcur, "Qcur", il);
  12746. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12747. cb(Kcur, "Kcur", il);
  12748. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12749. cb(Vcur, "Vcur", il);
  12750. Qcur = llm_build_norm(ctx0, Qcur, hparams, model.layers[il].attn_q_norm, NULL,
  12751. LLM_NORM_RMS, cb, il);
  12752. cb(Qcur, "Qcur_normed", il);
  12753. Kcur = llm_build_norm(ctx0, Kcur, hparams, model.layers[il].attn_k_norm, NULL,
  12754. LLM_NORM_RMS, cb, il);
  12755. cb(Kcur, "Kcur_normed", il);
  12756. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  12757. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  12758. Qcur = ggml_rope_ext(
  12759. ctx0, Qcur, inp_pos, nullptr,
  12760. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12761. ext_factor, attn_factor, beta_fast, beta_slow
  12762. );
  12763. cb(Qcur, "Qcur_rope", il);
  12764. Kcur = ggml_rope_ext(
  12765. ctx0, Kcur, inp_pos, nullptr,
  12766. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12767. ext_factor, attn_factor, beta_fast, beta_slow
  12768. );
  12769. cb(Kcur, "Kcur_rope", il);
  12770. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12771. model.layers[il].wo, NULL,
  12772. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12773. }
  12774. cur = llm_build_norm(ctx0, cur, hparams,
  12775. model.layers[il].attn_post_norm, NULL,
  12776. LLM_NORM_RMS, cb, il);
  12777. cb(cur, "attn_post_norm", il);
  12778. if (il == n_layer - 1) {
  12779. // skip computing output for unused tokens
  12780. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12781. n_tokens = n_outputs;
  12782. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12783. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12784. }
  12785. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12786. cb(ffn_inp, "ffn_inp", il);
  12787. // feed-forward network
  12788. cur = llm_build_ffn(ctx0, lctx, ffn_inp,
  12789. model.layers[il].ffn_up, NULL, NULL,
  12790. model.layers[il].ffn_gate, NULL, NULL,
  12791. model.layers[il].ffn_down, NULL, NULL,
  12792. NULL,
  12793. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12794. cb(cur, "ffn_out", il);
  12795. cur = llm_build_norm(ctx0, cur, hparams,
  12796. model.layers[il].ffn_post_norm, NULL,
  12797. LLM_NORM_RMS, cb, -1);
  12798. cb(cur, "ffn_post_norm", -1);
  12799. cur = ggml_add(ctx0, cur, ffn_inp);
  12800. cb(cur, "ffn_out", il);
  12801. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12802. cb(cur, "l_out", il);
  12803. // input for next layer
  12804. inpL = cur;
  12805. }
  12806. cur = inpL;
  12807. cur = llm_build_norm(ctx0, cur, hparams,
  12808. model.output_norm, NULL,
  12809. LLM_NORM_RMS, cb, -1);
  12810. cb(cur, "result_norm", -1);
  12811. // lm_head
  12812. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12813. cb(cur, "result_output", -1);
  12814. ggml_build_forward_expand(gf, cur);
  12815. return gf;
  12816. }
  12817. // based on the build_qwen2moe() function, changes:
  12818. // * removed shared experts
  12819. // * removed bias
  12820. // * added q, k norm
  12821. struct ggml_cgraph * build_olmoe() {
  12822. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12823. // mutable variable, needed during the last layer of the computation to skip unused tokens
  12824. int32_t n_tokens = this->n_tokens;
  12825. const int64_t n_embd_head = hparams.n_embd_head_v;
  12826. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12827. GGML_ASSERT(n_embd_head == hparams.n_rot);
  12828. struct ggml_tensor * cur;
  12829. struct ggml_tensor * inpL;
  12830. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12831. // inp_pos - contains the positions
  12832. struct ggml_tensor * inp_pos = build_inp_pos();
  12833. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12834. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12835. for (int il = 0; il < n_layer; ++il) {
  12836. struct ggml_tensor * inpSA = inpL;
  12837. // norm
  12838. cur = llm_build_norm(ctx0, inpL, hparams,
  12839. model.layers[il].attn_norm, NULL,
  12840. LLM_NORM_RMS, cb, il);
  12841. cb(cur, "attn_norm", il);
  12842. // self_attention
  12843. {
  12844. // compute Q and K and RoPE them
  12845. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12846. cb(Qcur, "Qcur", il);
  12847. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12848. cb(Kcur, "Kcur", il);
  12849. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12850. cb(Vcur, "Vcur", il);
  12851. Qcur = llm_build_norm(ctx0, Qcur, hparams, model.layers[il].attn_q_norm, NULL,
  12852. LLM_NORM_RMS, cb, il);
  12853. cb(Qcur, "Qcur_normed", il);
  12854. Kcur = llm_build_norm(ctx0, Kcur, hparams, model.layers[il].attn_k_norm, NULL,
  12855. LLM_NORM_RMS, cb, il);
  12856. cb(Kcur, "Kcur_normed", il);
  12857. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  12858. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  12859. Qcur = ggml_rope_ext(
  12860. ctx0, Qcur, inp_pos, nullptr,
  12861. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12862. ext_factor, attn_factor, beta_fast, beta_slow
  12863. );
  12864. cb(Qcur, "Qcur_rope", il);
  12865. Kcur = ggml_rope_ext(
  12866. ctx0, Kcur, inp_pos, nullptr,
  12867. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12868. ext_factor, attn_factor, beta_fast, beta_slow
  12869. );
  12870. cb(Kcur, "Kcur_rope", il);
  12871. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12872. model.layers[il].wo, NULL,
  12873. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12874. }
  12875. if (il == n_layer - 1) {
  12876. // skip computing output for unused tokens
  12877. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12878. n_tokens = n_outputs;
  12879. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12880. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12881. }
  12882. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12883. cb(ffn_inp, "ffn_inp", il);
  12884. // MoE branch
  12885. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12886. model.layers[il].ffn_norm, NULL,
  12887. LLM_NORM_RMS, cb, il);
  12888. cb(cur, "ffn_norm", il);
  12889. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  12890. model.layers[il].ffn_gate_inp,
  12891. model.layers[il].ffn_up_exps,
  12892. model.layers[il].ffn_gate_exps,
  12893. model.layers[il].ffn_down_exps,
  12894. n_expert, n_expert_used,
  12895. LLM_FFN_SILU, false,
  12896. false, 0.0,
  12897. cb, il);
  12898. cb(cur, "ffn_moe_out", il);
  12899. cur = ggml_add(ctx0, cur, ffn_inp);
  12900. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12901. cb(cur, "l_out", il);
  12902. // input for next layer
  12903. inpL = cur;
  12904. }
  12905. cur = inpL;
  12906. cur = llm_build_norm(ctx0, cur, hparams,
  12907. model.output_norm, NULL,
  12908. LLM_NORM_RMS, cb, -1);
  12909. cb(cur, "result_norm", -1);
  12910. // lm_head
  12911. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12912. cb(cur, "result_output", -1);
  12913. ggml_build_forward_expand(gf, cur);
  12914. return gf;
  12915. }
  12916. struct ggml_cgraph * build_openelm() {
  12917. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12918. const int64_t n_embd_head = hparams.n_embd_head_v;
  12919. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12920. struct ggml_tensor * cur;
  12921. struct ggml_tensor * inpL;
  12922. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12923. // inp_pos - contains the positions
  12924. struct ggml_tensor * inp_pos = build_inp_pos();
  12925. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12926. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12927. for (int il = 0; il < n_layer; ++il) {
  12928. const int64_t n_head = hparams.n_head(il);
  12929. const int64_t n_head_kv = hparams.n_head_kv(il);
  12930. const int64_t n_head_qkv = 2*n_head_kv + n_head;
  12931. cur = inpL;
  12932. struct ggml_tensor * residual = cur;
  12933. // norm
  12934. cur = llm_build_norm(ctx0, inpL, hparams,
  12935. model.layers[il].attn_norm, NULL,
  12936. LLM_NORM_RMS, cb, il);
  12937. cb(cur, "attn_norm", il);
  12938. // self-attention
  12939. {
  12940. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  12941. cb(cur, "wqkv", il);
  12942. cur = ggml_reshape_3d(ctx0, cur, n_embd_head_k, n_head_qkv, n_tokens);
  12943. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_3d(ctx0, cur, n_embd_head, n_head, n_tokens, cur->nb[1], cur->nb[2], 0));
  12944. cb(Qcur, "Qcur", il);
  12945. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_3d(ctx0, cur, n_embd_head, n_head_kv, n_tokens, cur->nb[1], cur->nb[2], cur->nb[1]*n_head));
  12946. cb(Kcur, "Kcur", il);
  12947. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_3d(ctx0, cur, n_embd_head, n_head_kv, n_tokens, cur->nb[1], cur->nb[2], cur->nb[1]*(n_head+n_head_kv)));
  12948. cb(Vcur, "Vcur", il);
  12949. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  12950. model.layers[il].attn_q_norm, NULL,
  12951. LLM_NORM_RMS, cb, il);
  12952. cb(Qcur, "Qcur", il);
  12953. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  12954. model.layers[il].attn_k_norm, NULL,
  12955. LLM_NORM_RMS, cb, il);
  12956. cb(Kcur, "Kcur", il);
  12957. Qcur = ggml_rope_ext(
  12958. ctx0, Qcur, inp_pos, NULL, n_rot, rope_type, n_ctx_orig,
  12959. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  12960. );
  12961. cb(Qcur, "Qcur", il);
  12962. Kcur = ggml_rope_ext(
  12963. ctx0, Kcur, inp_pos, NULL, n_rot, rope_type, n_ctx_orig,
  12964. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  12965. );
  12966. cb(Kcur, "Kcur", il);
  12967. Vcur = ggml_reshape_2d(ctx0, Vcur, n_embd_head * n_head_kv, n_tokens);
  12968. cb(Qcur, "Vcur", il);
  12969. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12970. model.layers[il].wo, NULL,
  12971. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12972. }
  12973. if (il == n_layer - 1) {
  12974. // skip computing output for unused tokens
  12975. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12976. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  12977. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12978. }
  12979. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  12980. cb(ffn_inp, "ffn_inp", il);
  12981. // feed-forward network
  12982. {
  12983. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12984. model.layers[il].ffn_norm, NULL,
  12985. LLM_NORM_RMS, cb, il);
  12986. cb(cur, "ffn_norm", il);
  12987. cur = llm_build_ffn(ctx0, lctx, cur,
  12988. model.layers[il].ffn_up, NULL, NULL,
  12989. model.layers[il].ffn_gate, NULL, NULL,
  12990. model.layers[il].ffn_down, NULL, NULL,
  12991. NULL,
  12992. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12993. cb(cur, "ffn_out", il);
  12994. }
  12995. cur = ggml_add(ctx0, cur, ffn_inp);
  12996. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12997. cb(cur, "l_out", il);
  12998. inpL = cur;
  12999. }
  13000. cur = inpL;
  13001. // norm
  13002. cur = llm_build_norm(ctx0, cur, hparams,
  13003. model.output_norm, NULL,
  13004. LLM_NORM_RMS, cb, -1);
  13005. cb(cur, "result_norm", -1);
  13006. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13007. cb(cur, "result_output", -1);
  13008. ggml_build_forward_expand(gf, cur);
  13009. return gf;
  13010. }
  13011. struct ggml_cgraph * build_gptneox() {
  13012. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13013. const int64_t n_embd_head = hparams.n_embd_head_v;
  13014. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  13015. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13016. struct ggml_tensor * cur;
  13017. struct ggml_tensor * inpL;
  13018. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13019. // inp_pos - contains the positions
  13020. struct ggml_tensor * inp_pos = build_inp_pos();
  13021. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13022. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13023. for (int il = 0; il < n_layer; ++il) {
  13024. cur = llm_build_norm(ctx0, inpL, hparams,
  13025. model.layers[il].attn_norm,
  13026. model.layers[il].attn_norm_b,
  13027. LLM_NORM, cb, il);
  13028. cb(cur, "attn_norm", il);
  13029. // self-attention
  13030. {
  13031. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  13032. cb(cur, "wqkv", il);
  13033. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  13034. cb(cur, "bqkv", il);
  13035. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  13036. 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)));
  13037. 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)));
  13038. cb(Qcur, "Qcur", il);
  13039. cb(Kcur, "Kcur", il);
  13040. cb(Vcur, "Vcur", il);
  13041. Qcur = ggml_rope_ext(
  13042. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  13043. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13044. ext_factor, attn_factor, beta_fast, beta_slow
  13045. );
  13046. cb(Qcur, "Qcur", il);
  13047. Kcur = ggml_rope_ext(
  13048. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  13049. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13050. ext_factor, attn_factor, beta_fast, beta_slow
  13051. );
  13052. cb(Kcur, "Kcur", il);
  13053. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13054. model.layers[il].wo, model.layers[il].bo,
  13055. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13056. }
  13057. if (il == n_layer - 1) {
  13058. // skip computing output for unused tokens
  13059. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13060. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13061. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  13062. }
  13063. // ffn
  13064. if (hparams.use_par_res) {
  13065. // attention and ffn are computed in parallel
  13066. // x = x + attn(ln1(x)) + ffn(ln2(x))
  13067. struct ggml_tensor * attn_out = cur;
  13068. cur = llm_build_norm(ctx0, inpL, hparams,
  13069. model.layers[il].ffn_norm,
  13070. model.layers[il].ffn_norm_b,
  13071. LLM_NORM, cb, il);
  13072. cb(cur, "ffn_norm", il);
  13073. cur = llm_build_ffn(ctx0, lctx, cur,
  13074. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  13075. NULL, NULL, NULL,
  13076. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  13077. NULL,
  13078. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  13079. cb(cur, "ffn_out", il);
  13080. cur = ggml_add(ctx0, cur, inpL);
  13081. cb(cur, "ffn_out", il);
  13082. cur = ggml_add(ctx0, cur, attn_out);
  13083. cur = lctx.cvec.apply_to(ctx0, cur, il);
  13084. cb(cur, "l_out", il);
  13085. // input for next layer
  13086. inpL = cur;
  13087. } else {
  13088. // attention and ffn are computed sequentially
  13089. // x = x + attn(ln1(x))
  13090. // x = x + ffn(ln2(x))
  13091. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  13092. cb(ffn_inp, "ffn_inp", il);
  13093. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13094. model.layers[il].ffn_norm,
  13095. model.layers[il].ffn_norm_b,
  13096. LLM_NORM, cb, il);
  13097. cb(cur, "ffn_norm", il);
  13098. cur = llm_build_ffn(ctx0, lctx, cur,
  13099. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  13100. NULL, NULL, NULL,
  13101. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  13102. NULL,
  13103. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  13104. cb(cur, "ffn_out", il);
  13105. cur = ggml_add(ctx0, cur, ffn_inp);
  13106. cur = lctx.cvec.apply_to(ctx0, cur, il);
  13107. cb(cur, "l_out", il);
  13108. // input for next layer
  13109. inpL = cur;
  13110. }
  13111. }
  13112. cur = llm_build_norm(ctx0, inpL, hparams,
  13113. model.output_norm,
  13114. model.output_norm_b,
  13115. LLM_NORM, cb, -1);
  13116. cb(cur, "result_norm", -1);
  13117. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13118. cb(cur, "result_output", -1);
  13119. ggml_build_forward_expand(gf, cur);
  13120. return gf;
  13121. }
  13122. struct ggml_cgraph * build_arctic() {
  13123. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13124. // mutable variable, needed during the last layer of the computation to skip unused tokens
  13125. int32_t n_tokens = this->n_tokens;
  13126. const int64_t n_embd_head = hparams.n_embd_head_v;
  13127. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13128. GGML_ASSERT(n_embd_head == hparams.n_rot);
  13129. struct ggml_tensor * cur;
  13130. struct ggml_tensor * inpL;
  13131. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13132. // inp_pos - contains the positions
  13133. struct ggml_tensor * inp_pos = build_inp_pos();
  13134. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13135. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13136. for (int il = 0; il < n_layer; ++il) {
  13137. struct ggml_tensor * inpSA = inpL;
  13138. // norm
  13139. cur = llm_build_norm(ctx0, inpL, hparams,
  13140. model.layers[il].attn_norm, NULL,
  13141. LLM_NORM_RMS, cb, il);
  13142. cb(cur, "attn_norm", il);
  13143. // self-attention
  13144. {
  13145. // compute Q and K and RoPE them
  13146. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  13147. cb(Qcur, "Qcur", il);
  13148. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  13149. cb(Kcur, "Kcur", il);
  13150. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  13151. cb(Vcur, "Vcur", il);
  13152. Qcur = ggml_rope_ext(
  13153. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  13154. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13155. ext_factor, attn_factor, beta_fast, beta_slow
  13156. );
  13157. cb(Qcur, "Qcur", il);
  13158. Kcur = ggml_rope_ext(
  13159. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  13160. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13161. ext_factor, attn_factor, beta_fast, beta_slow
  13162. );
  13163. cb(Kcur, "Kcur", il);
  13164. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13165. model.layers[il].wo, NULL,
  13166. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13167. }
  13168. if (il == n_layer - 1) {
  13169. // skip computing output for unused tokens
  13170. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13171. n_tokens = n_outputs;
  13172. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13173. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13174. }
  13175. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13176. cb(ffn_inp, "ffn_inp", il);
  13177. // feed-forward network
  13178. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13179. model.layers[il].ffn_norm, NULL,
  13180. LLM_NORM_RMS, cb, il);
  13181. cb(cur, "ffn_norm", il);
  13182. cur = llm_build_ffn(ctx0, lctx, cur,
  13183. model.layers[il].ffn_up, NULL, NULL,
  13184. model.layers[il].ffn_gate, NULL, NULL,
  13185. model.layers[il].ffn_down, NULL, NULL,
  13186. NULL,
  13187. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13188. cb(cur, "ffn_out", il);
  13189. struct ggml_tensor * ffn_out = ggml_add(ctx0, cur, ffn_inp);
  13190. cb(ffn_out, "ffn_out", il);
  13191. // MoE
  13192. cur = llm_build_norm(ctx0, inpSA, hparams,
  13193. model.layers[il].ffn_norm_exps, NULL,
  13194. LLM_NORM_RMS, cb, il);
  13195. cb(cur, "ffn_norm_exps", il);
  13196. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  13197. model.layers[il].ffn_gate_inp,
  13198. model.layers[il].ffn_up_exps,
  13199. model.layers[il].ffn_gate_exps,
  13200. model.layers[il].ffn_down_exps,
  13201. n_expert, n_expert_used,
  13202. LLM_FFN_SILU, true,
  13203. false, 0.0,
  13204. cb, il);
  13205. cb(cur, "ffn_moe_out", il);
  13206. cur = ggml_add(ctx0, cur, ffn_out);
  13207. cb(cur, "ffn_out", il);
  13208. cur = lctx.cvec.apply_to(ctx0, cur, il);
  13209. cb(cur, "l_out", il);
  13210. // input for next layer
  13211. inpL = cur;
  13212. }
  13213. cur = inpL;
  13214. cur = llm_build_norm(ctx0, cur, hparams,
  13215. model.output_norm, NULL,
  13216. LLM_NORM_RMS, cb, -1);
  13217. cb(cur, "result_norm", -1);
  13218. // lm_head
  13219. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13220. cb(cur, "result_output", -1);
  13221. ggml_build_forward_expand(gf, cur);
  13222. return gf;
  13223. }
  13224. struct ggml_cgraph * build_deepseek2() {
  13225. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13226. // mutable variable, needed during the last layer of the computation to skip unused tokens
  13227. int32_t n_tokens = this->n_tokens;
  13228. bool is_lite = (hparams.n_layer == 27);
  13229. // We have to pre-scale kq_scale and attn_factor to make the YaRN RoPE work correctly.
  13230. // See https://github.com/ggerganov/llama.cpp/discussions/7416 for detailed explanation.
  13231. const float mscale = attn_factor * (1.0f + hparams.rope_yarn_log_mul * logf(1.0f / freq_scale));
  13232. const float kq_scale = 1.0f*mscale*mscale/sqrtf(float(hparams.n_embd_head_k));
  13233. const float attn_factor_scaled = 1.0f / (1.0f + 0.1f * logf(1.0f / freq_scale));
  13234. const uint32_t n_embd_head_qk_rope = hparams.n_rot;
  13235. const uint32_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  13236. const uint32_t kv_lora_rank = hparams.n_lora_kv;
  13237. struct ggml_tensor * cur;
  13238. struct ggml_tensor * inpL;
  13239. // {n_embd, n_tokens}
  13240. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13241. // inp_pos - contains the positions
  13242. struct ggml_tensor * inp_pos = build_inp_pos();
  13243. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13244. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13245. for (int il = 0; il < n_layer; ++il) {
  13246. struct ggml_tensor * inpSA = inpL;
  13247. // norm
  13248. cur = llm_build_norm(ctx0, inpL, hparams,
  13249. model.layers[il].attn_norm, NULL,
  13250. LLM_NORM_RMS, cb, il);
  13251. cb(cur, "attn_norm", il);
  13252. // self_attention
  13253. {
  13254. struct ggml_tensor * q = NULL;
  13255. if (!is_lite) {
  13256. // {n_embd, q_lora_rank} * {n_embd, n_tokens} -> {q_lora_rank, n_tokens}
  13257. q = ggml_mul_mat(ctx0, model.layers[il].wq_a, cur);
  13258. cb(q, "q", il);
  13259. q = llm_build_norm(ctx0, q, hparams,
  13260. model.layers[il].attn_q_a_norm, NULL,
  13261. LLM_NORM_RMS, cb, il);
  13262. cb(q, "q", il);
  13263. // {q_lora_rank, n_head * hparams.n_embd_head_k} * {q_lora_rank, n_tokens} -> {n_head * hparams.n_embd_head_k, n_tokens}
  13264. q = ggml_mul_mat(ctx0, model.layers[il].wq_b, q);
  13265. cb(q, "q", il);
  13266. } else {
  13267. q = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  13268. cb(q, "q", il);
  13269. }
  13270. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  13271. struct ggml_tensor * q_nope = ggml_view_3d(ctx0, q, n_embd_head_qk_nope, n_head, n_tokens,
  13272. ggml_row_size(q->type, hparams.n_embd_head_k),
  13273. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  13274. 0);
  13275. cb(q_nope, "q_nope", il);
  13276. // and {n_head * n_embd_head_qk_rope, n_tokens}
  13277. struct ggml_tensor * q_pe = ggml_view_3d(ctx0, q, n_embd_head_qk_rope, n_head, n_tokens,
  13278. ggml_row_size(q->type, hparams.n_embd_head_k),
  13279. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  13280. ggml_row_size(q->type, n_embd_head_qk_nope));
  13281. cb(q_pe, "q_pe", il);
  13282. // {n_embd, kv_lora_rank + n_embd_head_qk_rope} * {n_embd, n_tokens} -> {kv_lora_rank + n_embd_head_qk_rope, n_tokens}
  13283. struct ggml_tensor * kv_pe_compresseed = ggml_mul_mat(ctx0, model.layers[il].wkv_a_mqa, cur);
  13284. cb(kv_pe_compresseed, "kv_pe_compresseed", il);
  13285. // split into {kv_lora_rank, n_tokens}
  13286. struct ggml_tensor * kv_compressed = ggml_view_2d(ctx0, kv_pe_compresseed, kv_lora_rank, n_tokens,
  13287. kv_pe_compresseed->nb[1],
  13288. 0);
  13289. cb(kv_compressed, "kv_compressed", il);
  13290. // and {n_embd_head_qk_rope, n_tokens}
  13291. struct ggml_tensor * k_pe = ggml_view_3d(ctx0, kv_pe_compresseed, n_embd_head_qk_rope, 1, n_tokens,
  13292. kv_pe_compresseed->nb[1],
  13293. kv_pe_compresseed->nb[1],
  13294. ggml_row_size(kv_pe_compresseed->type, kv_lora_rank));
  13295. cb(k_pe, "k_pe", il);
  13296. kv_compressed = ggml_cont(ctx0, kv_compressed); // TODO: the CUDA backend does not support non-contiguous norm
  13297. kv_compressed = llm_build_norm(ctx0, kv_compressed, hparams,
  13298. model.layers[il].attn_kv_a_norm, NULL,
  13299. LLM_NORM_RMS, cb, il);
  13300. cb(kv_compressed, "kv_compressed", il);
  13301. // {kv_lora_rank, n_head * (n_embd_head_qk_nope + n_embd_head_v)} * {kv_lora_rank, n_tokens} -> {n_head * (n_embd_head_qk_nope + n_embd_head_v), n_tokens}
  13302. struct ggml_tensor * kv = ggml_mul_mat(ctx0, model.layers[il].wkv_b, kv_compressed);
  13303. cb(kv, "kv", il);
  13304. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  13305. struct ggml_tensor * k_nope = ggml_view_3d(ctx0, kv, n_embd_head_qk_nope, n_head, n_tokens,
  13306. ggml_row_size(kv->type, n_embd_head_qk_nope + hparams.n_embd_head_v),
  13307. ggml_row_size(kv->type, n_head * (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  13308. 0);
  13309. cb(k_nope, "k_nope", il);
  13310. // and {n_head * n_embd_head_v, n_tokens}
  13311. struct ggml_tensor * v_states = ggml_view_3d(ctx0, kv, hparams.n_embd_head_v, n_head, n_tokens,
  13312. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  13313. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)*n_head),
  13314. ggml_row_size(kv->type, (n_embd_head_qk_nope)));
  13315. cb(v_states, "v_states", il);
  13316. v_states = ggml_cont(ctx0, v_states);
  13317. cb(v_states, "v_states", il);
  13318. v_states = ggml_view_2d(ctx0, v_states, hparams.n_embd_head_v * n_head, n_tokens,
  13319. ggml_row_size(kv->type, hparams.n_embd_head_v * n_head),
  13320. 0);
  13321. cb(v_states, "v_states", il);
  13322. q_pe = ggml_cont(ctx0, q_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  13323. q_pe = ggml_rope_ext(
  13324. ctx0, q_pe, inp_pos, nullptr,
  13325. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13326. ext_factor, attn_factor_scaled, beta_fast, beta_slow
  13327. );
  13328. cb(q_pe, "q_pe", il);
  13329. // shared RoPE key
  13330. k_pe = ggml_cont(ctx0, k_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  13331. k_pe = ggml_rope_ext(
  13332. ctx0, k_pe, inp_pos, nullptr,
  13333. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13334. ext_factor, attn_factor_scaled, beta_fast, beta_slow
  13335. );
  13336. cb(k_pe, "k_pe", il);
  13337. struct ggml_tensor * q_states = ggml_concat(ctx0, q_nope, q_pe, 0);
  13338. cb(q_states, "q_states", il);
  13339. struct ggml_tensor * k_states = ggml_concat(ctx0, k_nope, ggml_repeat(ctx0, k_pe, q_pe), 0);
  13340. cb(k_states, "k_states", il);
  13341. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13342. model.layers[il].wo, NULL,
  13343. k_states, v_states, q_states, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  13344. }
  13345. if (il == n_layer - 1) {
  13346. // skip computing output for unused tokens
  13347. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13348. n_tokens = n_outputs;
  13349. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13350. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13351. }
  13352. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13353. cb(ffn_inp, "ffn_inp", il);
  13354. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13355. model.layers[il].ffn_norm, NULL,
  13356. LLM_NORM_RMS, cb, il);
  13357. cb(cur, "ffn_norm", il);
  13358. if ((uint32_t) il < hparams.n_layer_dense_lead) {
  13359. cur = llm_build_ffn(ctx0, lctx, cur,
  13360. model.layers[il].ffn_up, NULL, NULL,
  13361. model.layers[il].ffn_gate, NULL, NULL,
  13362. model.layers[il].ffn_down, NULL, NULL,
  13363. NULL,
  13364. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13365. cb(cur, "ffn_out", il);
  13366. } else {
  13367. // MoE branch
  13368. ggml_tensor * moe_out =
  13369. llm_build_moe_ffn(ctx0, lctx, cur,
  13370. model.layers[il].ffn_gate_inp,
  13371. model.layers[il].ffn_up_exps,
  13372. model.layers[il].ffn_gate_exps,
  13373. model.layers[il].ffn_down_exps,
  13374. n_expert, n_expert_used,
  13375. LLM_FFN_SILU, false,
  13376. true, hparams.expert_weights_scale,
  13377. cb, il);
  13378. cb(moe_out, "ffn_moe_out", il);
  13379. // FFN shared expert
  13380. {
  13381. ggml_tensor * ffn_shexp = llm_build_ffn(ctx0, lctx, cur,
  13382. model.layers[il].ffn_up_shexp, NULL, NULL,
  13383. model.layers[il].ffn_gate_shexp, NULL, NULL,
  13384. model.layers[il].ffn_down_shexp, NULL, NULL,
  13385. NULL,
  13386. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13387. cb(ffn_shexp, "ffn_shexp", il);
  13388. cur = ggml_add(ctx0, moe_out, ffn_shexp);
  13389. cb(cur, "ffn_out", il);
  13390. }
  13391. }
  13392. cur = ggml_add(ctx0, cur, ffn_inp);
  13393. cur = lctx.cvec.apply_to(ctx0, cur, il);
  13394. cb(cur, "l_out", il);
  13395. // input for next layer
  13396. inpL = cur;
  13397. }
  13398. cur = inpL;
  13399. cur = llm_build_norm(ctx0, cur, hparams,
  13400. model.output_norm, NULL,
  13401. LLM_NORM_RMS, cb, -1);
  13402. cb(cur, "result_norm", -1);
  13403. // lm_head
  13404. cur = ggml_mul_mat(ctx0, model.output, cur);
  13405. cb(cur, "result_output", -1);
  13406. ggml_build_forward_expand(gf, cur);
  13407. return gf;
  13408. }
  13409. struct ggml_cgraph * build_bitnet() {
  13410. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13411. const int64_t n_embd_head = hparams.n_embd_head_v;
  13412. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13413. struct ggml_tensor * cur;
  13414. struct ggml_tensor * inpL;
  13415. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13416. // inp_pos - contains the positions
  13417. struct ggml_tensor * inp_pos = build_inp_pos();
  13418. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13419. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13420. for (int il = 0; il < n_layer; ++il) {
  13421. struct ggml_tensor * inpSA = inpL;
  13422. cur = llm_build_norm(ctx0, inpL, hparams,
  13423. model.layers[il].attn_norm, NULL,
  13424. LLM_NORM_RMS, cb, il);
  13425. cb(cur, "attn_norm", il);
  13426. // self-attention
  13427. {
  13428. // compute Q and K and RoPE them
  13429. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  13430. if (model.layers[il].wq_scale) {
  13431. Qcur = ggml_mul(ctx0, Qcur, model.layers[il].wq_scale);
  13432. }
  13433. cb(Qcur, "Qcur", il);
  13434. if (model.layers[il].bq) {
  13435. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  13436. cb(Qcur, "Qcur", il);
  13437. }
  13438. // B1.K
  13439. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  13440. if (model.layers[il].wk_scale) {
  13441. Kcur = ggml_mul(ctx0, Kcur, model.layers[il].wk_scale);
  13442. }
  13443. cb(Kcur, "Kcur", il);
  13444. if (model.layers[il].bk) {
  13445. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  13446. cb(Kcur, "Kcur", il);
  13447. }
  13448. // B1.V
  13449. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  13450. if (model.layers[il].wv_scale) {
  13451. Vcur = ggml_mul(ctx0, Vcur, model.layers[il].wv_scale);
  13452. }
  13453. cb(Vcur, "Vcur", il);
  13454. if (model.layers[il].bv) {
  13455. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  13456. cb(Vcur, "Vcur", il);
  13457. }
  13458. Qcur = ggml_rope_ext(
  13459. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  13460. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13461. ext_factor, attn_factor, beta_fast, beta_slow
  13462. );
  13463. cb(Qcur, "Qcur", il);
  13464. Kcur = ggml_rope_ext(
  13465. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  13466. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13467. ext_factor, attn_factor, beta_fast, beta_slow
  13468. );
  13469. cb(Kcur, "Kcur", il);
  13470. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13471. NULL, NULL,
  13472. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13473. cur = llm_build_norm(ctx0, cur, hparams,
  13474. model.layers[il].attn_sub_norm, NULL,
  13475. LLM_NORM_RMS, cb, il);
  13476. cb(cur, "attn_sub_norm", il);
  13477. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  13478. if (model.layers[il].wo_scale) {
  13479. cur = ggml_mul(ctx0, cur, model.layers[il].wo_scale);
  13480. }
  13481. if (model.layers[il].bo) {
  13482. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  13483. }
  13484. cb(cur, "attn_o_out", il);
  13485. }
  13486. if (il == n_layer - 1) {
  13487. // skip computing output for unused tokens
  13488. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13489. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13490. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13491. }
  13492. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13493. cb(ffn_inp, "ffn_inp", il);
  13494. // feed-forward forward
  13495. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13496. model.layers[il].ffn_norm, NULL,
  13497. LLM_NORM_RMS, cb, il);
  13498. cb(cur, "ffn_norm", il);
  13499. cur = llm_build_ffn(ctx0, lctx, cur,
  13500. model.layers[il].ffn_up, NULL, model.layers[il].ffn_up_scale,
  13501. model.layers[il].ffn_gate, NULL, model.layers[il].ffn_gate_scale,
  13502. NULL, NULL, NULL,
  13503. NULL,
  13504. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13505. cb(cur, "ffn_sub_out", il);
  13506. cur = llm_build_norm(ctx0, cur, hparams,
  13507. model.layers[il].ffn_sub_norm, NULL,
  13508. LLM_NORM_RMS, cb, il);
  13509. cb(cur, "ffn_sub_norm", il);
  13510. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].ffn_down, cur);
  13511. if (model.layers[il].ffn_down_scale) {
  13512. cur = ggml_mul(ctx0, cur, model.layers[il].ffn_down_scale);
  13513. }
  13514. cb(cur, "ffn_down", il);
  13515. cur = ggml_add(ctx0, cur, ffn_inp);
  13516. cb(cur, "l_out", il);
  13517. // input for next layer
  13518. inpL = cur;
  13519. }
  13520. cur = inpL;
  13521. cur = llm_build_norm(ctx0, cur, hparams,
  13522. model.output_norm, NULL,
  13523. LLM_NORM_RMS, cb, -1);
  13524. cb(cur, "result_norm", -1);
  13525. // lm_head
  13526. // FIXME: do not use model.tok_embd directly, duplicate as model.output
  13527. cur = llm_build_lora_mm(lctx, ctx0, model.tok_embd, cur);
  13528. cb(cur, "result_output", -1);
  13529. ggml_build_forward_expand(gf, cur);
  13530. return gf;
  13531. }
  13532. struct ggml_cgraph * build_t5_encoder() {
  13533. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13534. // mutable variable, needed during the last layer of the computation to skip unused tokens
  13535. int32_t n_tokens = this->n_tokens;
  13536. const int64_t n_embd_head = hparams.n_embd_head_v;
  13537. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  13538. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13539. struct ggml_tensor * cur;
  13540. struct ggml_tensor * inpL;
  13541. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13542. GGML_ASSERT(lctx.is_encoding);
  13543. struct ggml_tensor * pos_bucket_enc = llm_build_pos_bucket(false);
  13544. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13545. struct ggml_tensor * KQ_mask_enc = build_inp_KQ_mask(false);
  13546. for (int il = 0; il < n_layer; ++il) {
  13547. struct ggml_tensor * inpSA = inpL;
  13548. // norm
  13549. cur = llm_build_norm(ctx0, inpL, hparams,
  13550. model.layers[il].attn_norm_enc, NULL,
  13551. LLM_NORM_RMS, cb, il);
  13552. cb(cur, "attn_norm", il);
  13553. // self-attention
  13554. {
  13555. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq_enc, cur);
  13556. cb(Qcur, "Qcur", il);
  13557. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk_enc, cur);
  13558. cb(Kcur, "Kcur", il);
  13559. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv_enc, cur);
  13560. cb(Vcur, "Vcur", il);
  13561. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  13562. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  13563. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  13564. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  13565. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  13566. cb(kq, "kq", il);
  13567. struct ggml_tensor * attn_rel_b = model.layers[il].attn_rel_b_enc ? model.layers[il].attn_rel_b_enc : model.layers[0].attn_rel_b_enc;
  13568. struct ggml_tensor * pos_bias = llm_build_pos_bias(pos_bucket_enc, attn_rel_b);
  13569. struct ggml_tensor * kq_b = ggml_add(ctx0, kq, pos_bias);
  13570. cb(kq_b, "kq_b", il);
  13571. kq = ggml_soft_max_ext(ctx0, kq_b, KQ_mask_enc, 1.0f, hparams.f_max_alibi_bias);
  13572. cb(kq, "kq_soft_max_ext", il);
  13573. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  13574. cb(v, "v", il);
  13575. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  13576. cb(kqv, "kqv", il);
  13577. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  13578. cb(kqv_merged, "kqv_merged", il);
  13579. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  13580. cb(cur, "kqv_merged_cont", il);
  13581. ggml_build_forward_expand(gf, cur);
  13582. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo_enc, cur);
  13583. cb(cur, "kqv_out", il);
  13584. }
  13585. if (il == n_layer - 1) {
  13586. // skip computing output for unused tokens
  13587. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13588. n_tokens = n_outputs;
  13589. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13590. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13591. }
  13592. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13593. cb(ffn_inp, "ffn_inp", il);
  13594. // feed-forward network
  13595. {
  13596. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13597. model.layers[il].ffn_norm_enc, NULL,
  13598. LLM_NORM_RMS, cb, il);
  13599. cb(cur, "ffn_norm", il);
  13600. // T5 uses relu, flan-T5 uses gelu-gated
  13601. cur = llm_build_ffn(ctx0, lctx, cur,
  13602. model.layers[il].ffn_up_enc, NULL, NULL,
  13603. model.layers[il].ffn_gate_enc, NULL, NULL,
  13604. model.layers[il].ffn_down_enc, NULL, NULL,
  13605. NULL,
  13606. model.layers[il].ffn_gate_enc ? LLM_FFN_GELU : LLM_FFN_RELU,
  13607. model.layers[il].ffn_gate_enc ? LLM_FFN_PAR : LLM_FFN_SEQ,
  13608. cb, il);
  13609. cb(cur, "ffn_out", il);
  13610. }
  13611. cur = ggml_add(ctx0, cur, ffn_inp);
  13612. cb(cur, "ffn_out", il);
  13613. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  13614. if (layer_dir != nullptr) {
  13615. cur = ggml_add(ctx0, cur, layer_dir);
  13616. }
  13617. cb(cur, "l_out", il);
  13618. // input for next layer
  13619. inpL = cur;
  13620. }
  13621. cur = inpL;
  13622. cb(cur, "result_embd", -1);
  13623. cur = llm_build_norm(ctx0, cur, hparams,
  13624. model.output_norm_enc, NULL,
  13625. LLM_NORM_RMS, cb, -1);
  13626. cb(cur, "result_norm", -1);
  13627. ggml_build_forward_expand(gf, cur);
  13628. return gf;
  13629. }
  13630. struct ggml_cgraph * build_t5_decoder() {
  13631. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13632. // mutable variable, needed during the last layer of the computation to skip unused tokens
  13633. int32_t n_tokens = this->n_tokens;
  13634. const int64_t n_embd_head = hparams.n_embd_head_v;
  13635. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  13636. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13637. struct ggml_tensor * cur;
  13638. struct ggml_tensor * inpL;
  13639. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13640. GGML_ASSERT(!lctx.is_encoding);
  13641. GGML_ASSERT(n_outputs_enc > 0 && "call llama_encode() first");
  13642. struct ggml_tensor * embd_enc = llm_build_inp_embd_enc();
  13643. struct ggml_tensor * pos_bucket_dec = llm_build_pos_bucket(true);
  13644. struct ggml_tensor * KQ_mask_dec = build_inp_KQ_mask();
  13645. struct ggml_tensor * KQ_mask_cross = llm_build_inp_KQ_mask_cross();
  13646. for (int il = 0; il < n_layer; ++il) {
  13647. struct ggml_tensor * inpSA = inpL;
  13648. // norm
  13649. cur = llm_build_norm(ctx0, inpL, hparams,
  13650. model.layers[il].attn_norm, NULL,
  13651. LLM_NORM_RMS, cb, il);
  13652. cb(cur, "attn_norm", il);
  13653. // self-attention
  13654. {
  13655. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  13656. cb(Qcur, "Qcur", il);
  13657. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  13658. cb(Kcur, "Kcur", il);
  13659. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  13660. cb(Vcur, "Vcur", il);
  13661. llm_build_kv_store(ctx0, hparams, cparams, kv_self, gf, Kcur, Vcur, n_tokens, kv_head, cb, il);
  13662. struct ggml_tensor * k =
  13663. ggml_view_3d(ctx0, kv_self.k_l[il],
  13664. n_embd_head_k, n_kv, n_head_kv,
  13665. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  13666. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  13667. 0);
  13668. cb(k, "k", il);
  13669. struct ggml_tensor * v =
  13670. ggml_view_3d(ctx0, kv_self.v_l[il],
  13671. n_kv, n_embd_head_v, n_head_kv,
  13672. ggml_element_size(kv_self.v_l[il])*n_ctx,
  13673. ggml_element_size(kv_self.v_l[il])*n_ctx*n_embd_head_v,
  13674. 0);
  13675. cb(v, "v", il);
  13676. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  13677. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  13678. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  13679. cb(kq, "kq", il);
  13680. struct ggml_tensor * attn_rel_b = model.layers[il].attn_rel_b ? model.layers[il].attn_rel_b : model.layers[0].attn_rel_b;
  13681. struct ggml_tensor * pos_bias = llm_build_pos_bias(pos_bucket_dec, attn_rel_b);
  13682. struct ggml_tensor * kq_b = ggml_add(ctx0, kq, pos_bias);
  13683. cb(kq_b, "kq_b", il);
  13684. kq = ggml_soft_max_ext(ctx0, kq_b, KQ_mask_dec, 1.0f, hparams.f_max_alibi_bias);
  13685. cb(kq, "kq_soft_max_ext", il);
  13686. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, v, kq);
  13687. cb(kqv, "kqv", il);
  13688. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  13689. cb(kqv_merged, "kqv_merged", il);
  13690. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  13691. cb(cur, "kqv_merged_cont", il);
  13692. ggml_build_forward_expand(gf, cur);
  13693. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  13694. cb(cur, "kqv_out", il);
  13695. }
  13696. cur = ggml_add(ctx0, cur, inpSA);
  13697. cb(cur, "cross_inp", il);
  13698. struct ggml_tensor * inpCA = cur;
  13699. // norm
  13700. cur = llm_build_norm(ctx0, cur, hparams,
  13701. model.layers[il].attn_norm_cross, NULL,
  13702. LLM_NORM_RMS, cb, il);
  13703. cb(cur, "attn_norm_cross", il);
  13704. // cross-attention
  13705. {
  13706. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq_cross, cur);
  13707. cb(Qcur, "Qcur", il);
  13708. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk_cross, embd_enc);
  13709. cb(Kcur, "Kcur", il);
  13710. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv_cross, embd_enc);
  13711. cb(Vcur, "Vcur", il);
  13712. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  13713. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_outputs_enc);
  13714. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  13715. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  13716. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  13717. cb(kq, "kq", il);
  13718. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask_cross, 1.0f, hparams.f_max_alibi_bias);
  13719. cb(kq, "kq_soft_max_ext", il);
  13720. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_outputs_enc)));
  13721. cb(v, "v", il);
  13722. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_outputs_enc, n_embd_head, n_head_kv), kq);
  13723. cb(kqv, "kqv", il);
  13724. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  13725. cb(kqv_merged, "kqv_merged", il);
  13726. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  13727. cb(cur, "kqv_merged_cont", il);
  13728. ggml_build_forward_expand(gf, cur);
  13729. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo_cross, cur);
  13730. cb(cur, "kqv_out", il);
  13731. }
  13732. if (il == n_layer - 1) {
  13733. // skip computing output for unused tokens
  13734. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13735. n_tokens = n_outputs;
  13736. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13737. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13738. inpCA = ggml_get_rows(ctx0, inpCA, inp_out_ids);
  13739. }
  13740. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpCA);
  13741. cb(ffn_inp, "ffn_inp", il);
  13742. // feed-forward network
  13743. {
  13744. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13745. model.layers[il].ffn_norm, NULL,
  13746. LLM_NORM_RMS, cb, il);
  13747. cb(cur, "ffn_norm", il);
  13748. // T5 uses relu, flan-T5 uses gelu-gated
  13749. cur = llm_build_ffn(ctx0, lctx, cur,
  13750. model.layers[il].ffn_up, NULL, NULL,
  13751. model.layers[il].ffn_gate, NULL, NULL,
  13752. model.layers[il].ffn_down, NULL, NULL,
  13753. NULL,
  13754. model.layers[il].ffn_gate_enc ? LLM_FFN_GELU : LLM_FFN_RELU,
  13755. model.layers[il].ffn_gate_enc ? LLM_FFN_PAR : LLM_FFN_SEQ,
  13756. cb, il);
  13757. cb(cur, "ffn_out", il);
  13758. }
  13759. cur = ggml_add(ctx0, cur, ffn_inp);
  13760. cb(cur, "ffn_out", il);
  13761. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  13762. if (layer_dir != nullptr) {
  13763. cur = ggml_add(ctx0, cur, layer_dir);
  13764. }
  13765. cb(cur, "l_out", il);
  13766. // input for next layer
  13767. inpL = cur;
  13768. }
  13769. cur = inpL;
  13770. cb(cur, "result_embd", -1);
  13771. cur = llm_build_norm(ctx0, cur, hparams,
  13772. model.output_norm, NULL,
  13773. LLM_NORM_RMS, cb, -1);
  13774. cb(cur, "result_norm", -1);
  13775. // lm_head
  13776. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13777. cb(cur, "result_output", -1);
  13778. ggml_build_forward_expand(gf, cur);
  13779. return gf;
  13780. }
  13781. struct ggml_cgraph * build_jais() {
  13782. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13783. const int64_t n_embd_head = hparams.n_embd_head_v;
  13784. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  13785. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13786. struct ggml_tensor * cur;
  13787. struct ggml_tensor * inpL;
  13788. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13789. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13790. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13791. for (int il = 0; il < n_layer; ++il) {
  13792. cur = llm_build_norm(ctx0, inpL, hparams,
  13793. model.layers[il].attn_norm,
  13794. model.layers[il].attn_norm_b,
  13795. LLM_NORM, cb, il);
  13796. cb(cur, "attn_norm", il);
  13797. // self-attention
  13798. {
  13799. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  13800. cb(cur, "wqkv", il);
  13801. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  13802. cb(cur, "bqkv", il);
  13803. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*cur->nb[0]*(n_embd)));
  13804. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*cur->nb[0]*(n_embd)));
  13805. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*cur->nb[0]*(n_embd + n_embd_gqa)));
  13806. cb(Qcur, "Qcur", il);
  13807. cb(Kcur, "Kcur", il);
  13808. cb(Vcur, "Vcur", il);
  13809. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  13810. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13811. model.layers[il].wo, model.layers[il].bo,
  13812. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/float(n_embd_head), cb, il);
  13813. }
  13814. if (il == n_layer - 1) {
  13815. // skip computing output for unused tokens
  13816. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13817. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13818. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  13819. }
  13820. // add the input
  13821. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  13822. cb(ffn_inp, "ffn_inp", il);
  13823. // FF
  13824. {
  13825. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13826. model.layers[il].ffn_norm,
  13827. model.layers[il].ffn_norm_b,
  13828. LLM_NORM, cb, il);
  13829. cb(cur, "ffn_norm", il);
  13830. cur = llm_build_ffn(ctx0, lctx, cur,
  13831. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  13832. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  13833. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  13834. NULL,
  13835. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13836. cb(cur, "ffn_out", il);
  13837. }
  13838. inpL = ggml_add(ctx0, cur, ffn_inp);
  13839. cb(inpL, "l_out", il);
  13840. }
  13841. cur = llm_build_norm(ctx0, inpL, hparams,
  13842. model.output_norm,
  13843. model.output_norm_b,
  13844. LLM_NORM, cb, -1);
  13845. cb(cur, "result_norm", -1);
  13846. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13847. cb(cur, "result_output", -1);
  13848. ggml_build_forward_expand(gf, cur);
  13849. return gf;
  13850. }
  13851. struct ggml_cgraph * build_chatglm() {
  13852. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13853. const int64_t n_embd_head = hparams.n_embd_head_v;
  13854. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  13855. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13856. struct ggml_tensor * cur;
  13857. struct ggml_tensor * inpL;
  13858. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13859. // inp_pos - contains the positions
  13860. struct ggml_tensor * inp_pos = build_inp_pos();
  13861. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13862. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13863. for (int il = 0; il < n_layer; ++il) {
  13864. struct ggml_tensor * inpSA = inpL;
  13865. cur = llm_build_norm(ctx0, inpL, hparams,
  13866. model.layers[il].attn_norm,
  13867. NULL,
  13868. LLM_NORM_RMS, cb, il);
  13869. cb(cur, "attn_norm", il);
  13870. // self-attention
  13871. {
  13872. struct ggml_tensor * Qcur = nullptr;
  13873. struct ggml_tensor * Kcur = nullptr;
  13874. struct ggml_tensor * Vcur = nullptr;
  13875. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  13876. cb(cur, "wqkv", il);
  13877. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  13878. cb(cur, "bqkv", il);
  13879. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  13880. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  13881. 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)));
  13882. cb(Qcur, "Qcur", il);
  13883. cb(Kcur, "Kcur", il);
  13884. cb(Vcur, "Vcur", il);
  13885. //printf("freq_base: %f freq_scale: %f ext_factor: %f attn_factor: %f\n", freq_base, freq_scale, ext_factor, attn_factor);
  13886. Qcur = ggml_rope_ext(
  13887. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  13888. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13889. ext_factor, attn_factor, beta_fast, beta_slow
  13890. );
  13891. cb(Qcur, "Qcur_rope", il);
  13892. Kcur = ggml_rope_ext(
  13893. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  13894. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13895. ext_factor, attn_factor, beta_fast, beta_slow
  13896. );
  13897. cb(Kcur, "Kcur_rope", il);
  13898. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13899. model.layers[il].wo, NULL,
  13900. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13901. }
  13902. if (il == n_layer - 1) {
  13903. // skip computing output for unused tokens
  13904. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13905. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13906. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13907. }
  13908. // Add the input
  13909. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13910. cb(ffn_inp, "ffn_inp", il);
  13911. // FF
  13912. {
  13913. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13914. model.layers[il].ffn_norm,
  13915. NULL,
  13916. LLM_NORM_RMS, cb, il);
  13917. cb(cur, "ffn_norm", il);
  13918. cur = llm_build_ffn(ctx0, lctx, cur,
  13919. model.layers[il].ffn_up, NULL, NULL,
  13920. NULL, NULL, NULL,
  13921. model.layers[il].ffn_down, NULL, NULL,
  13922. NULL,
  13923. LLM_FFN_SWIGLU, LLM_FFN_SEQ, cb, il);
  13924. cb(cur, "ffn_out", il);
  13925. }
  13926. inpL = ggml_add(ctx0, cur, ffn_inp);
  13927. cb(inpL, "l_out", il);
  13928. }
  13929. cur = llm_build_norm(ctx0, inpL, hparams,
  13930. model.output_norm,
  13931. NULL,
  13932. LLM_NORM_RMS, cb, -1);
  13933. cb(cur, "result_norm", -1);
  13934. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13935. cb(cur, "result_output", -1);
  13936. ggml_build_forward_expand(gf, cur);
  13937. return gf;
  13938. }
  13939. struct ggml_cgraph * build_nemotron() {
  13940. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13941. const int64_t n_embd_head = hparams.n_embd_head_v;
  13942. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13943. //GGML_ASSERT(n_embd_head == hparams.n_rot);
  13944. struct ggml_tensor * cur;
  13945. struct ggml_tensor * inpL;
  13946. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13947. // inp_pos - contains the positions
  13948. struct ggml_tensor * inp_pos = build_inp_pos();
  13949. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13950. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13951. for (int il = 0; il < n_layer; ++il) {
  13952. struct ggml_tensor * inpSA = inpL;
  13953. // norm
  13954. cur = llm_build_norm(ctx0, inpL, hparams,
  13955. model.layers[il].attn_norm,
  13956. model.layers[il].attn_norm_b,
  13957. LLM_NORM, cb, il);
  13958. cb(cur, "attn_norm", il);
  13959. // self-attention
  13960. {
  13961. // compute Q and K and RoPE them
  13962. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  13963. cb(Qcur, "Qcur", il);
  13964. if (model.layers[il].bq) {
  13965. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  13966. cb(Qcur, "Qcur", il);
  13967. }
  13968. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  13969. cb(Kcur, "Kcur", il);
  13970. if (model.layers[il].bk) {
  13971. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  13972. cb(Kcur, "Kcur", il);
  13973. }
  13974. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  13975. cb(Vcur, "Vcur", il);
  13976. if (model.layers[il].bv) {
  13977. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  13978. cb(Vcur, "Vcur", il);
  13979. }
  13980. Qcur = ggml_rope_ext(
  13981. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  13982. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13983. ext_factor, attn_factor, beta_fast, beta_slow
  13984. );
  13985. cb(Qcur, "Qcur", il);
  13986. Kcur = ggml_rope_ext(
  13987. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  13988. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13989. ext_factor, attn_factor, beta_fast, beta_slow
  13990. );
  13991. cb(Kcur, "Kcur", il);
  13992. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13993. model.layers[il].wo, model.layers[il].bo,
  13994. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13995. }
  13996. if (il == n_layer - 1) {
  13997. // skip computing output for unused tokens
  13998. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13999. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  14000. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  14001. }
  14002. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  14003. cb(ffn_inp, "ffn_inp", il);
  14004. // feed-forward network
  14005. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  14006. model.layers[il].ffn_norm,
  14007. model.layers[il].ffn_norm_b,
  14008. LLM_NORM, cb, il);
  14009. cb(cur, "ffn_norm", il);
  14010. cur = llm_build_ffn(ctx0, lctx, cur,
  14011. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  14012. NULL, NULL, NULL,
  14013. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  14014. NULL,
  14015. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  14016. cur = ggml_add(ctx0, cur, ffn_inp);
  14017. cb(cur, "ffn_out", il);
  14018. cur = lctx.cvec.apply_to(ctx0, cur, il);
  14019. cb(cur, "l_out", il);
  14020. // input for next layer
  14021. inpL = cur;
  14022. }
  14023. cur = inpL;
  14024. cur = llm_build_norm(ctx0, cur, hparams,
  14025. model.output_norm, model.output_norm_b,
  14026. LLM_NORM, cb, -1);
  14027. cb(cur, "result_norm", -1);
  14028. // lm_head
  14029. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  14030. cb(cur, "result_output", -1);
  14031. ggml_build_forward_expand(gf, cur);
  14032. return gf;
  14033. }
  14034. struct ggml_cgraph * build_exaone() {
  14035. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  14036. // mutable variable, needed during the last layer of the computation to skip unused tokens
  14037. int32_t n_tokens = this->n_tokens;
  14038. const int64_t n_embd_head = hparams.n_embd_head_v;
  14039. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  14040. GGML_ASSERT(n_embd_head == hparams.n_rot);
  14041. struct ggml_tensor * cur;
  14042. struct ggml_tensor * inpL;
  14043. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  14044. // inp_pos - contains the positions
  14045. struct ggml_tensor * inp_pos = build_inp_pos();
  14046. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  14047. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  14048. for (int il = 0; il < n_layer; ++il) {
  14049. struct ggml_tensor * inpSA = inpL;
  14050. // norm
  14051. cur = llm_build_norm(ctx0, inpL, hparams,
  14052. model.layers[il].attn_norm, NULL,
  14053. LLM_NORM_RMS, cb, il);
  14054. cb(cur, "attn_norm", il);
  14055. // self-attention
  14056. {
  14057. // rope freq factors for llama3; may return nullptr for llama2 and other models
  14058. struct ggml_tensor * rope_factors = build_rope_factors(il);
  14059. // compute Q and K and RoPE them
  14060. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  14061. cb(Qcur, "Qcur", il);
  14062. if (model.layers[il].bq) {
  14063. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  14064. cb(Qcur, "Qcur", il);
  14065. }
  14066. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  14067. cb(Kcur, "Kcur", il);
  14068. if (model.layers[il].bk) {
  14069. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  14070. cb(Kcur, "Kcur", il);
  14071. }
  14072. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  14073. cb(Vcur, "Vcur", il);
  14074. if (model.layers[il].bv) {
  14075. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  14076. cb(Vcur, "Vcur", il);
  14077. }
  14078. Qcur = ggml_rope_ext(
  14079. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  14080. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  14081. ext_factor, attn_factor, beta_fast, beta_slow
  14082. );
  14083. cb(Qcur, "Qcur", il);
  14084. Kcur = ggml_rope_ext(
  14085. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  14086. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  14087. ext_factor, attn_factor, beta_fast, beta_slow
  14088. );
  14089. cb(Kcur, "Kcur", il);
  14090. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  14091. model.layers[il].wo, model.layers[il].bo,
  14092. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  14093. }
  14094. if (il == n_layer - 1) {
  14095. // skip computing output for unused tokens
  14096. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  14097. n_tokens = n_outputs;
  14098. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  14099. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  14100. }
  14101. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  14102. cb(ffn_inp, "ffn_inp", il);
  14103. // feed-forward network
  14104. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  14105. model.layers[il].ffn_norm, NULL,
  14106. LLM_NORM_RMS, cb, il);
  14107. cb(cur, "ffn_norm", il);
  14108. cur = llm_build_ffn(ctx0, lctx, cur,
  14109. model.layers[il].ffn_up, NULL, NULL,
  14110. model.layers[il].ffn_gate, NULL, NULL,
  14111. model.layers[il].ffn_down, NULL, NULL,
  14112. NULL,
  14113. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  14114. cb(cur, "ffn_out", il);
  14115. cur = ggml_add(ctx0, cur, ffn_inp);
  14116. cb(cur, "ffn_out", il);
  14117. cur = lctx.cvec.apply_to(ctx0, cur, il);
  14118. cb(cur, "l_out", il);
  14119. // input for next layer
  14120. inpL = cur;
  14121. }
  14122. cur = inpL;
  14123. cur = llm_build_norm(ctx0, cur, hparams,
  14124. model.output_norm, NULL,
  14125. LLM_NORM_RMS, cb, -1);
  14126. cb(cur, "result_norm", -1);
  14127. // lm_head
  14128. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  14129. cb(cur, "result_output", -1);
  14130. ggml_build_forward_expand(gf, cur);
  14131. return gf;
  14132. }
  14133. ggml_cgraph * build_rwkv6() {
  14134. ggml_cgraph *gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  14135. // Token shift state dimensions should be 2 * n_emb
  14136. GGML_ASSERT(n_embd == hparams.n_embd_k_s() / 2);
  14137. const int64_t n_seqs = ubatch.n_seqs;
  14138. const int64_t n_seq_tokens = ubatch.n_seq_tokens;
  14139. const int64_t n_tokens = ubatch.n_tokens;
  14140. GGML_ASSERT(n_seqs != 0);
  14141. GGML_ASSERT(ubatch.equal_seqs);
  14142. GGML_ASSERT(n_tokens == n_seq_tokens * n_seqs);
  14143. struct ggml_tensor * cur;
  14144. struct ggml_tensor * inpL;
  14145. struct ggml_tensor * state_copy = build_inp_s_copy();
  14146. struct ggml_tensor * state_mask = build_inp_s_mask();
  14147. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  14148. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  14149. for (int il = 0; il < n_layer; ++il) {
  14150. const llama_layer * layer = &model.layers[il];
  14151. // (ab)using the KV cache to store the states
  14152. struct ggml_tensor * token_shift = llm_build_copy_mask_state(ctx0,
  14153. gf, kv_self.k_l[il], state_copy, state_mask,
  14154. hparams.n_embd_k_s(), kv_self.size, kv_head, n_kv, n_seqs);
  14155. struct ggml_tensor * wkv_states = llm_build_copy_mask_state(ctx0,
  14156. gf, kv_self.v_l[il], state_copy, state_mask,
  14157. hparams.n_embd_v_s(), kv_self.size, kv_head, n_kv, n_seqs);
  14158. cur = ggml_reshape_3d(ctx0, inpL, n_embd, n_seq_tokens, n_seqs);
  14159. token_shift = ggml_reshape_3d(ctx0, token_shift, n_embd, 2, n_seqs);
  14160. struct ggml_tensor * att_shift = ggml_view_3d(ctx0, token_shift, n_embd, 1, n_seqs, token_shift->nb[1], token_shift->nb[2], 0);
  14161. struct ggml_tensor * ffn_shift = ggml_view_3d(ctx0, token_shift, n_embd, 1, n_seqs, token_shift->nb[1], token_shift->nb[2], n_embd * ggml_element_size(token_shift));
  14162. struct ggml_tensor * x_norm_att = llm_build_norm(ctx0, cur, hparams, layer->attn_norm, layer->attn_norm_b, LLM_NORM, cb, il);
  14163. struct ggml_tensor * x_prev = ggml_concat(
  14164. ctx0,
  14165. att_shift,
  14166. ggml_view_3d(ctx0, x_norm_att, n_embd, n_seq_tokens - 1, n_seqs, x_norm_att->nb[1], x_norm_att->nb[2], 0),
  14167. 1
  14168. );
  14169. cur = ggml_add(ctx0, cur, llm_build_rwkv6_time_mix(lctx, ctx0, layer, x_norm_att, x_prev, &wkv_states));
  14170. ggml_build_forward_expand(gf, cur);
  14171. ggml_build_forward_expand(
  14172. gf,
  14173. ggml_cpy(
  14174. ctx0,
  14175. wkv_states,
  14176. ggml_view_1d(
  14177. ctx0,
  14178. kv_self.v_l[il],
  14179. hparams.n_embd_v_s() * n_seqs,
  14180. hparams.n_embd_v_s() * kv_head * ggml_element_size(kv_self.v_l[il])
  14181. )
  14182. )
  14183. );
  14184. struct ggml_tensor * x_norm_ffn = llm_build_norm(ctx0, cur, hparams, layer->attn_norm_2, layer->attn_norm_2_b, LLM_NORM, cb, il);
  14185. x_prev = ggml_concat(
  14186. ctx0,
  14187. ffn_shift,
  14188. ggml_view_3d(ctx0, x_norm_ffn, n_embd, n_seq_tokens - 1, n_seqs, x_norm_ffn->nb[1], x_norm_ffn->nb[2], 0),
  14189. 1
  14190. );
  14191. cur = ggml_add(ctx0, cur, llm_build_rwkv6_channel_mix(lctx, ctx0, layer, x_norm_ffn, x_prev));
  14192. ggml_build_forward_expand(gf, cur);
  14193. struct ggml_tensor * last_norm_att = ggml_view_3d(ctx0, x_norm_att, n_embd, 1, n_seqs, x_norm_att->nb[1], x_norm_att->nb[2], (n_seq_tokens-1)*n_embd*ggml_element_size(x_norm_att));
  14194. struct ggml_tensor * last_norm_ffn = ggml_view_3d(ctx0, x_norm_ffn, n_embd, 1, n_seqs, x_norm_ffn->nb[1], x_norm_ffn->nb[2], (n_seq_tokens-1)*n_embd*ggml_element_size(x_norm_ffn));
  14195. token_shift = ggml_concat(ctx0, last_norm_att, last_norm_ffn, 1);
  14196. ggml_build_forward_expand(
  14197. gf,
  14198. ggml_cpy(
  14199. ctx0,
  14200. ggml_view_1d(ctx0, token_shift, n_embd * n_seqs * 2, 0),
  14201. ggml_view_1d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s() * n_seqs, hparams.n_embd_k_s() * kv_head * ggml_element_size(kv_self.k_l[il]))
  14202. )
  14203. );
  14204. if (hparams.rescale_every_n_layers != 0 && (il + 1) % hparams.rescale_every_n_layers == 0) {
  14205. cur = ggml_scale(ctx0, cur, 0.5F);
  14206. }
  14207. cur = lctx.cvec.apply_to(ctx0, cur, il);
  14208. cb(cur, "l_out", il);
  14209. // input for next layer
  14210. inpL = cur;
  14211. }
  14212. cur = inpL;
  14213. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  14214. cur = ggml_reshape_2d(ctx0, cur, n_embd, n_tokens);
  14215. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  14216. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, model.output_norm_b, LLM_NORM, cb, -1);
  14217. cb(cur, "result_norm", -1);
  14218. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  14219. cb(cur, "result_output", -1);
  14220. ggml_build_forward_expand(gf, cur);
  14221. return gf;
  14222. }
  14223. // ref: https://github.com/facebookresearch/chameleon
  14224. // based on the original build_llama() function, changes:
  14225. // * qk-norm
  14226. // * swin-norm
  14227. // * removed bias
  14228. // * removed MoE
  14229. struct ggml_cgraph * build_chameleon() {
  14230. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  14231. // mutable variable, needed during the last layer of the computation to skip unused tokens
  14232. int32_t n_tokens = this->n_tokens;
  14233. const int64_t n_embd_head = hparams.n_embd_head_v;
  14234. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  14235. GGML_ASSERT(n_embd_head == hparams.n_rot);
  14236. struct ggml_tensor * cur;
  14237. struct ggml_tensor * inpL;
  14238. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  14239. // inp_pos - contains the positions
  14240. struct ggml_tensor * inp_pos = build_inp_pos();
  14241. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  14242. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  14243. for (int il = 0; il < n_layer; ++il) {
  14244. struct ggml_tensor * inpSA = inpL;
  14245. // norm
  14246. if (hparams.swin_norm) {
  14247. cur = inpL;
  14248. } else {
  14249. cur = llm_build_norm(ctx0, inpL, hparams,
  14250. model.layers[il].attn_norm, NULL,
  14251. LLM_NORM_RMS, cb, il);
  14252. cb(cur, "attn_norm", il);
  14253. }
  14254. // self-attention
  14255. {
  14256. // compute Q and K and RoPE them
  14257. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  14258. cb(Qcur, "Qcur", il);
  14259. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  14260. cb(Kcur, "Kcur", il);
  14261. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  14262. cb(Vcur, "Vcur", il);
  14263. if (model.layers[il].attn_q_norm) {
  14264. Qcur = ggml_view_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens,
  14265. ggml_element_size(Qcur) * n_embd_head,
  14266. ggml_element_size(Qcur) * n_embd_head * n_head,
  14267. 0);
  14268. cb(Qcur, "Qcur", il);
  14269. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  14270. model.layers[il].attn_q_norm,
  14271. model.layers[il].attn_q_norm_b,
  14272. LLM_NORM, cb, il);
  14273. cb(Qcur, "Qcur", il);
  14274. }
  14275. if (model.layers[il].attn_k_norm) {
  14276. Kcur = ggml_view_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens,
  14277. ggml_element_size(Kcur) * n_embd_head,
  14278. ggml_element_size(Kcur) * n_embd_head * n_head_kv,
  14279. 0);
  14280. cb(Kcur, "Kcur", il);
  14281. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  14282. model.layers[il].attn_k_norm,
  14283. model.layers[il].attn_k_norm_b,
  14284. LLM_NORM, cb, il);
  14285. cb(Kcur, "Kcur", il);
  14286. }
  14287. Qcur = ggml_rope_ext(
  14288. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  14289. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  14290. ext_factor, attn_factor, beta_fast, beta_slow
  14291. );
  14292. cb(Qcur, "Qcur", il);
  14293. Kcur = ggml_rope_ext(
  14294. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  14295. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  14296. ext_factor, attn_factor, beta_fast, beta_slow
  14297. );
  14298. cb(Kcur, "Kcur", il);
  14299. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  14300. model.layers[il].wo, nullptr,
  14301. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  14302. if (hparams.swin_norm) {
  14303. cur = llm_build_norm(ctx0, cur, hparams,
  14304. model.layers[il].attn_norm, NULL,
  14305. LLM_NORM_RMS, cb, il);
  14306. }
  14307. }
  14308. if (il == n_layer - 1) {
  14309. // skip computing output for unused tokens
  14310. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  14311. n_tokens = n_outputs;
  14312. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  14313. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  14314. }
  14315. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  14316. cb(ffn_inp, "ffn_inp", il);
  14317. // feed-forward network
  14318. if (!hparams.swin_norm) {
  14319. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  14320. model.layers[il].ffn_norm, NULL,
  14321. LLM_NORM_RMS, cb, il);
  14322. cb(cur, "ffn_norm", il);
  14323. }
  14324. cur = llm_build_ffn(ctx0, lctx, cur,
  14325. model.layers[il].ffn_up, NULL, NULL,
  14326. model.layers[il].ffn_gate, NULL, NULL,
  14327. model.layers[il].ffn_down, NULL, NULL,
  14328. NULL,
  14329. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  14330. cb(cur, "ffn_out", il);
  14331. if (hparams.swin_norm) {
  14332. cur = llm_build_norm(ctx0, cur, hparams,
  14333. model.layers[il].ffn_norm, NULL,
  14334. LLM_NORM_RMS, cb, il);
  14335. cb(cur, "ffn_norm", il);
  14336. }
  14337. cur = ggml_add(ctx0, cur, ffn_inp);
  14338. cb(cur, "ffn_out", il);
  14339. cur = lctx.cvec.apply_to(ctx0, cur, il);
  14340. cb(cur, "l_out", il);
  14341. // input for next layer
  14342. inpL = cur;
  14343. }
  14344. cur = inpL;
  14345. cur = llm_build_norm(ctx0, cur, hparams,
  14346. model.output_norm, NULL,
  14347. LLM_NORM_RMS, cb, -1);
  14348. cb(cur, "result_norm", -1);
  14349. // lm_head
  14350. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  14351. cb(cur, "result_output_with_img_logits", -1);
  14352. // TODO: this suppresses the output of image tokens, which is required to enable text-only outputs.
  14353. // Needs to be removed once image outputs are supported.
  14354. int img_token_end_idx = 8196;
  14355. int img_token_start_idx = 4;
  14356. int num_img_tokens = img_token_end_idx - img_token_start_idx;
  14357. // creates 1d tensor of size num_img_tokens and values -FLT_MAX,
  14358. // which ensures that text token values are always at least larger than image token values
  14359. struct ggml_tensor * img_logits = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, num_img_tokens);
  14360. img_logits = ggml_clamp(ctx0, img_logits, -FLT_MAX, -FLT_MAX);
  14361. cb(img_logits, "img_logits", -1);
  14362. cur = ggml_set_1d(ctx0, cur, img_logits, ggml_element_size(cur) * img_token_start_idx);
  14363. cb(cur, "result_output", -1);
  14364. ggml_build_forward_expand(gf, cur);
  14365. return gf;
  14366. }
  14367. ggml_cgraph * build_solar() {
  14368. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  14369. // mutable variable, needed during the last layer of the computation to skip unused tokens
  14370. int32_t n_tokens = this->n_tokens;
  14371. const int64_t n_embd_head = hparams.n_embd_head_v;
  14372. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  14373. GGML_ASSERT(n_embd_head == hparams.n_rot);
  14374. struct ggml_tensor * cur;
  14375. struct ggml_tensor * inpL;
  14376. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  14377. // inp_pos - contains the positions
  14378. struct ggml_tensor * inp_pos = build_inp_pos();
  14379. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  14380. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  14381. struct ggml_tensor * bskcn_1;
  14382. struct ggml_tensor * bskcn_2;
  14383. for (int il = 0; il < n_layer; ++il) {
  14384. struct ggml_tensor * inpSA = inpL;
  14385. if (hparams.n_bskcn(0, il)) {
  14386. bskcn_1 = inpSA;
  14387. }
  14388. if (hparams.n_bskcn(1, il)) {
  14389. bskcn_2 = inpSA;
  14390. }
  14391. if (hparams.n_bskcn(2, il)) {
  14392. inpSA = ggml_add(
  14393. ctx0,
  14394. ggml_mul(ctx0, bskcn_1, ggml_view_1d(ctx0, model.layers[il].bskcn_tv, 1, 0)),
  14395. ggml_mul(ctx0, inpSA, ggml_view_1d(ctx0, model.layers[il].bskcn_tv, 1, ggml_element_size(model.layers[il].bskcn_tv))));
  14396. }
  14397. if (hparams.n_bskcn(3, il)) {
  14398. inpSA = ggml_add(
  14399. ctx0,
  14400. ggml_mul(ctx0, bskcn_2, ggml_view_1d(ctx0, model.layers[il].bskcn_tv, 1, 0)),
  14401. ggml_mul(ctx0, inpSA, ggml_view_1d(ctx0, model.layers[il].bskcn_tv, 1, ggml_element_size(model.layers[il].bskcn_tv))));
  14402. }
  14403. // norm
  14404. cur = llm_build_norm(ctx0, inpL, hparams,
  14405. model.layers[il].attn_norm, NULL,
  14406. LLM_NORM_RMS, cb, il);
  14407. cb(cur, "attn_norm", il);
  14408. // self-attention
  14409. {
  14410. // rope freq factors for llama3; may return nullptr for llama2 and other models
  14411. struct ggml_tensor * rope_factors = build_rope_factors(il);
  14412. // compute Q and K and RoPE them
  14413. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  14414. cb(Qcur, "Qcur", il);
  14415. if (model.layers[il].bq) {
  14416. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  14417. cb(Qcur, "Qcur", il);
  14418. }
  14419. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  14420. cb(Kcur, "Kcur", il);
  14421. if (model.layers[il].bk) {
  14422. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  14423. cb(Kcur, "Kcur", il);
  14424. }
  14425. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  14426. cb(Vcur, "Vcur", il);
  14427. if (model.layers[il].bv) {
  14428. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  14429. cb(Vcur, "Vcur", il);
  14430. }
  14431. Qcur = ggml_rope_ext(
  14432. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  14433. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  14434. ext_factor, attn_factor, beta_fast, beta_slow
  14435. );
  14436. cb(Qcur, "Qcur", il);
  14437. Kcur = ggml_rope_ext(
  14438. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  14439. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  14440. ext_factor, attn_factor, beta_fast, beta_slow
  14441. );
  14442. cb(Kcur, "Kcur", il);
  14443. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  14444. model.layers[il].wo, model.layers[il].bo,
  14445. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  14446. }
  14447. if (il == n_layer - 1) {
  14448. // skip computing output for unused tokens
  14449. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  14450. n_tokens = n_outputs;
  14451. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  14452. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  14453. }
  14454. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  14455. cb(ffn_inp, "ffn_inp", il);
  14456. // feed-forward network
  14457. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  14458. model.layers[il].ffn_norm, NULL,
  14459. LLM_NORM_RMS, cb, il);
  14460. cb(cur, "ffn_norm", il);
  14461. cur = llm_build_ffn(ctx0, lctx, cur,
  14462. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  14463. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  14464. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  14465. NULL,
  14466. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  14467. cb(cur, "ffn_out", il);
  14468. cur = ggml_add(ctx0, cur, ffn_inp);
  14469. cb(cur, "ffn_out", il);
  14470. cur = lctx.cvec.apply_to(ctx0, cur, il);
  14471. cb(cur, "l_out", il);
  14472. // input for next layer
  14473. inpL = cur;
  14474. }
  14475. cur = inpL;
  14476. cur = llm_build_norm(ctx0, cur, hparams,
  14477. model.output_norm, NULL,
  14478. LLM_NORM_RMS, cb, -1);
  14479. cb(cur, "result_norm", -1);
  14480. // lm_head
  14481. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  14482. cb(cur, "result_output", -1);
  14483. ggml_build_forward_expand(gf, cur);
  14484. return gf;
  14485. }
  14486. };
  14487. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  14488. llama_ubatch dummy = {};
  14489. dummy.equal_seqs = true;
  14490. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  14491. struct llm_build_context llm(lctx, dummy, cb, false);
  14492. llm.init();
  14493. struct ggml_cgraph * result = llm.build_defrag(ids);
  14494. llm.free();
  14495. return result;
  14496. }
  14497. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  14498. llama_ubatch dummy = {};
  14499. dummy.equal_seqs = true;
  14500. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  14501. struct llm_build_context llm(lctx, dummy, cb, false);
  14502. llm.init();
  14503. struct ggml_cgraph * result = llm.build_k_shift();
  14504. llm.free();
  14505. return result;
  14506. }
  14507. static struct ggml_cgraph * llama_build_graph(
  14508. llama_context & lctx,
  14509. const llama_ubatch & ubatch,
  14510. bool worst_case) {
  14511. const auto & model = lctx.model;
  14512. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  14513. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  14514. if (il >= 0) {
  14515. ggml_format_name(cur, "%s-%d", name, il);
  14516. } else {
  14517. ggml_set_name(cur, name);
  14518. }
  14519. if (!lctx.cparams.offload_kqv) {
  14520. if (strcmp(name, "kqv_merged_cont") == 0) {
  14521. // all nodes between the KV store and the attention output are run on the CPU
  14522. ggml_backend_sched_set_tensor_backend(lctx.sched.get(), cur, lctx.backend_cpu);
  14523. }
  14524. }
  14525. // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
  14526. // FIXME: fix in ggml_backend_sched
  14527. const bool full_offload = lctx.model.n_gpu_layers > (int)lctx.model.hparams.n_layer;
  14528. if (ubatch.n_tokens < 32 || full_offload) {
  14529. if (il != -1 && strcmp(name, "norm") == 0) {
  14530. const auto & dev_layer = lctx.model.dev_layer.at(il);
  14531. for (auto & backend : lctx.backends) {
  14532. if (ggml_backend_get_device(backend.get()) == dev_layer.dev) {
  14533. if (ggml_backend_supports_op(backend.get(), cur)) {
  14534. ggml_backend_sched_set_tensor_backend(lctx.sched.get(), cur, backend.get());
  14535. }
  14536. }
  14537. }
  14538. }
  14539. }
  14540. };
  14541. struct ggml_cgraph * result = NULL;
  14542. struct llm_build_context llm(lctx, ubatch, cb, worst_case);
  14543. llm.init();
  14544. switch (model.arch) {
  14545. case LLM_ARCH_LLAMA:
  14546. case LLM_ARCH_GRANITE:
  14547. case LLM_ARCH_GRANITE_MOE:
  14548. {
  14549. result = llm.build_llama();
  14550. } break;
  14551. case LLM_ARCH_MLLAMA:
  14552. {
  14553. result = llm.build_mllama();
  14554. } break;
  14555. case LLM_ARCH_BAICHUAN:
  14556. {
  14557. result = llm.build_baichuan();
  14558. } break;
  14559. case LLM_ARCH_FALCON:
  14560. {
  14561. result = llm.build_falcon();
  14562. } break;
  14563. case LLM_ARCH_GROK:
  14564. {
  14565. result = llm.build_grok();
  14566. } break;
  14567. case LLM_ARCH_STARCODER:
  14568. {
  14569. result = llm.build_starcoder();
  14570. } break;
  14571. case LLM_ARCH_REFACT:
  14572. {
  14573. result = llm.build_refact();
  14574. } break;
  14575. case LLM_ARCH_BERT:
  14576. case LLM_ARCH_JINA_BERT_V2:
  14577. case LLM_ARCH_NOMIC_BERT:
  14578. {
  14579. result = llm.build_bert();
  14580. } break;
  14581. case LLM_ARCH_BLOOM:
  14582. {
  14583. result = llm.build_bloom();
  14584. } break;
  14585. case LLM_ARCH_MPT:
  14586. {
  14587. result = llm.build_mpt();
  14588. } break;
  14589. case LLM_ARCH_STABLELM:
  14590. {
  14591. result = llm.build_stablelm();
  14592. } break;
  14593. case LLM_ARCH_QWEN:
  14594. {
  14595. result = llm.build_qwen();
  14596. } break;
  14597. case LLM_ARCH_QWEN2:
  14598. {
  14599. result = llm.build_qwen2();
  14600. } break;
  14601. case LLM_ARCH_QWEN2MOE:
  14602. {
  14603. result = llm.build_qwen2moe();
  14604. } break;
  14605. case LLM_ARCH_PHI2:
  14606. {
  14607. result = llm.build_phi2();
  14608. } break;
  14609. case LLM_ARCH_PHI3:
  14610. {
  14611. result = llm.build_phi3();
  14612. } break;
  14613. case LLM_ARCH_PLAMO:
  14614. {
  14615. result = llm.build_plamo();
  14616. } break;
  14617. case LLM_ARCH_GPT2:
  14618. {
  14619. result = llm.build_gpt2();
  14620. } break;
  14621. case LLM_ARCH_CODESHELL:
  14622. {
  14623. result = llm.build_codeshell();
  14624. } break;
  14625. case LLM_ARCH_ORION:
  14626. {
  14627. result = llm.build_orion();
  14628. } break;
  14629. case LLM_ARCH_INTERNLM2:
  14630. {
  14631. result = llm.build_internlm2();
  14632. } break;
  14633. case LLM_ARCH_MINICPM:
  14634. {
  14635. result = llm.build_minicpm();
  14636. } break;
  14637. case LLM_ARCH_MINICPM3:
  14638. {
  14639. result = llm.build_minicpm3();
  14640. } break;
  14641. case LLM_ARCH_GEMMA:
  14642. {
  14643. result = llm.build_gemma();
  14644. } break;
  14645. case LLM_ARCH_GEMMA2:
  14646. {
  14647. result = llm.build_gemma2();
  14648. } break;
  14649. case LLM_ARCH_STARCODER2:
  14650. {
  14651. result = llm.build_starcoder2();
  14652. } break;
  14653. case LLM_ARCH_MAMBA:
  14654. {
  14655. result = llm.build_mamba();
  14656. } break;
  14657. case LLM_ARCH_XVERSE:
  14658. {
  14659. result = llm.build_xverse();
  14660. } break;
  14661. case LLM_ARCH_COMMAND_R:
  14662. {
  14663. result = llm.build_command_r();
  14664. } break;
  14665. case LLM_ARCH_DBRX:
  14666. {
  14667. result = llm.build_dbrx();
  14668. } break;
  14669. case LLM_ARCH_OLMO:
  14670. {
  14671. result = llm.build_olmo();
  14672. } break;
  14673. case LLM_ARCH_OLMO2:
  14674. {
  14675. result = llm.build_olmo2();
  14676. } break;
  14677. case LLM_ARCH_OLMOE:
  14678. {
  14679. result = llm.build_olmoe();
  14680. } break;
  14681. case LLM_ARCH_OPENELM:
  14682. {
  14683. result = llm.build_openelm();
  14684. } break;
  14685. case LLM_ARCH_GPTNEOX:
  14686. {
  14687. result = llm.build_gptneox();
  14688. } break;
  14689. case LLM_ARCH_ARCTIC:
  14690. {
  14691. result = llm.build_arctic();
  14692. } break;
  14693. case LLM_ARCH_DEEPSEEK2:
  14694. {
  14695. result = llm.build_deepseek2();
  14696. } break;
  14697. case LLM_ARCH_CHATGLM:
  14698. {
  14699. result = llm.build_chatglm();
  14700. } break;
  14701. case LLM_ARCH_BITNET:
  14702. {
  14703. result = llm.build_bitnet();
  14704. } break;
  14705. case LLM_ARCH_T5:
  14706. {
  14707. if (lctx.is_encoding) {
  14708. result = llm.build_t5_encoder();
  14709. } else {
  14710. result = llm.build_t5_decoder();
  14711. }
  14712. } break;
  14713. case LLM_ARCH_T5ENCODER:
  14714. {
  14715. result = llm.build_t5_encoder();
  14716. } break;
  14717. case LLM_ARCH_JAIS:
  14718. {
  14719. result = llm.build_jais();
  14720. } break;
  14721. case LLM_ARCH_NEMOTRON:
  14722. {
  14723. result = llm.build_nemotron();
  14724. } break;
  14725. case LLM_ARCH_EXAONE:
  14726. {
  14727. result = llm.build_exaone();
  14728. } break;
  14729. case LLM_ARCH_RWKV6:
  14730. {
  14731. result = llm.build_rwkv6();
  14732. } break;
  14733. case LLM_ARCH_CHAMELEON:
  14734. {
  14735. result = llm.build_chameleon();
  14736. } break;
  14737. case LLM_ARCH_SOLAR:
  14738. {
  14739. result = llm.build_solar();
  14740. } break;
  14741. default:
  14742. GGML_ABORT("fatal error");
  14743. }
  14744. // add on pooling layer
  14745. if (lctx.cparams.embeddings) {
  14746. result = llm.append_pooling(result);
  14747. }
  14748. llm.free();
  14749. return result;
  14750. }
  14751. static void llama_set_k_shift(llama_context & lctx) {
  14752. const int64_t kv_size = lctx.kv_self.size;
  14753. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  14754. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  14755. for (int i = 0; i < kv_size; ++i) {
  14756. data[i] = lctx.kv_self.cells[i].delta;
  14757. }
  14758. }
  14759. static void llama_set_s_copy(llama_context & lctx) {
  14760. const int64_t kv_size = lctx.kv_self.size;
  14761. assert(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  14762. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  14763. for (int i = 0; i < kv_size; ++i) {
  14764. data[i] = lctx.kv_self.cells[i].src;
  14765. }
  14766. }
  14767. static int32_t llama_relative_position_bucket(llama_pos x, llama_pos y, uint64_t n_buckets, bool bidirectional) {
  14768. // TODO move to hparams if a T5 variant appears that uses a different value
  14769. const int64_t max_distance = 128;
  14770. if (bidirectional) {
  14771. n_buckets >>= 1;
  14772. }
  14773. const int64_t max_exact = n_buckets >> 1;
  14774. int32_t relative_position = x - y;
  14775. int32_t relative_bucket = 0;
  14776. if (bidirectional) {
  14777. relative_bucket += (relative_position > 0) * n_buckets;
  14778. relative_position = abs(relative_position);
  14779. } else {
  14780. relative_position = -std::min<int32_t>(relative_position, 0);
  14781. }
  14782. int32_t relative_position_if_large = floorf(max_exact + logf(1.0 * relative_position / max_exact) * (n_buckets - max_exact) / log(1.0 * max_distance / max_exact));
  14783. relative_position_if_large = std::min<int32_t>(relative_position_if_large, n_buckets - 1);
  14784. relative_bucket += (relative_position < max_exact ? relative_position : relative_position_if_large);
  14785. return relative_bucket;
  14786. }
  14787. static void llama_set_inputs(llama_context & lctx, const llama_ubatch & ubatch) {
  14788. //
  14789. // set input data
  14790. //
  14791. const auto & hparams = lctx.model.hparams;
  14792. const auto & cparams = lctx.cparams;
  14793. const auto & kv_self = lctx.kv_self;
  14794. if (ubatch.token) {
  14795. const int64_t n_tokens = ubatch.n_tokens;
  14796. ggml_backend_tensor_set(lctx.inp_tokens, ubatch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  14797. }
  14798. if (ubatch.embd) {
  14799. if (lctx.inp_cross_attn_state && lctx.inp_cross_attn_state->buffer) {
  14800. ggml_backend_tensor_set(lctx.inp_cross_attn_state, ubatch.embd, 0, ggml_nbytes(lctx.inp_cross_attn_state));
  14801. // zero out inp_embd since it's not used
  14802. float * inp_embd_data = (float *)lctx.inp_embd->data;
  14803. for (int i = 0; i < ggml_nelements(lctx.inp_embd); ++i) {
  14804. inp_embd_data[i] = 0.0f;
  14805. }
  14806. } else {
  14807. const int64_t n_embd = hparams.n_embd;
  14808. const int64_t n_tokens = ubatch.n_tokens;
  14809. ggml_backend_tensor_set(lctx.inp_embd, ubatch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  14810. }
  14811. }
  14812. if (ubatch.pos && lctx.inp_pos) {
  14813. const int64_t n_tokens = ubatch.n_tokens;
  14814. ggml_backend_tensor_set(lctx.inp_pos, ubatch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  14815. }
  14816. if (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE) {
  14817. GGML_ASSERT(lctx.inp_out_ids && "every model that can must skip unused outputs");
  14818. const int64_t n_tokens = ubatch.n_tokens;
  14819. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_out_ids->buffer));
  14820. int32_t * data = (int32_t *) lctx.inp_out_ids->data;
  14821. if (lctx.n_outputs == n_tokens) {
  14822. for (int i = 0; i < n_tokens; ++i) {
  14823. data[i] = i;
  14824. }
  14825. } else if (ubatch.output) {
  14826. int32_t n_outputs = 0;
  14827. for (int i = 0; i < n_tokens; ++i) {
  14828. if (ubatch.output[i]) {
  14829. data[n_outputs++] = i;
  14830. }
  14831. }
  14832. // the graph needs to have been passed the correct number of outputs
  14833. GGML_ASSERT(lctx.n_outputs == n_outputs);
  14834. } else if (lctx.n_outputs == 1) {
  14835. // only keep last output
  14836. data[0] = n_tokens - 1;
  14837. } else {
  14838. GGML_ASSERT(lctx.n_outputs == 0);
  14839. }
  14840. }
  14841. GGML_ASSERT(
  14842. // (!a || b) is a logical implication (a -> b)
  14843. // !hparams.causal_attn -> !cparams.causal_attn
  14844. (hparams.causal_attn || !cparams.causal_attn) &&
  14845. "causal attention is not supported by this model"
  14846. );
  14847. if (lctx.inp_KQ_mask || lctx.inp_KQ_mask_swa) {
  14848. // NOTE: hparams.causal_attn indicates the model is capable of generation and uses the kv cache.
  14849. if (cparams.causal_attn && !lctx.is_encoding) {
  14850. const int64_t n_kv = kv_self.n;
  14851. const int64_t n_tokens = ubatch.n_tokens;
  14852. const int64_t n_seq_tokens = ubatch.n_seq_tokens;
  14853. const int64_t n_seqs = ubatch.n_seqs;
  14854. float * data = nullptr;
  14855. float * data_swa = nullptr;
  14856. if (lctx.inp_KQ_mask) {
  14857. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  14858. data = (float *) lctx.inp_KQ_mask->data;
  14859. }
  14860. if (lctx.inp_KQ_mask_swa) {
  14861. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask_swa->buffer));
  14862. data_swa = (float *) lctx.inp_KQ_mask_swa->data;
  14863. }
  14864. // For causal attention, use only the previous KV cells
  14865. // of the correct sequence for each token of the ubatch.
  14866. // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
  14867. for (int h = 0; h < 1; ++h) {
  14868. for (int s = 0; s < n_seqs; ++s) {
  14869. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  14870. for (int j = 0; j < n_seq_tokens; ++j) {
  14871. const llama_pos pos = ubatch.pos[s*n_seq_tokens + j];
  14872. for (int i = 0; i < n_kv; ++i) {
  14873. float f;
  14874. if (!kv_self.cells[i].has_seq_id(seq_id) || kv_self.cells[i].pos > pos) {
  14875. f = -INFINITY;
  14876. } else {
  14877. if (hparams.use_alibi) {
  14878. f = -std::abs(kv_self.cells[i].pos - pos);
  14879. } else {
  14880. f = 0.0f;
  14881. }
  14882. }
  14883. if (data) {
  14884. data[h*(n_kv*n_tokens) + s*(n_kv*n_seq_tokens) + j*n_kv + i] = f;
  14885. }
  14886. // may need to cut off old tokens for sliding window
  14887. if (data_swa) {
  14888. if (pos - kv_self.cells[i].pos >= (int32_t)hparams.n_swa) {
  14889. f = -INFINITY;
  14890. }
  14891. data_swa[h*(n_kv*n_tokens) + s*(n_kv*n_seq_tokens) + j*n_kv + i] = f;
  14892. }
  14893. }
  14894. }
  14895. }
  14896. if (data) {
  14897. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  14898. for (int j = 0; j < n_kv; ++j) {
  14899. data[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
  14900. }
  14901. }
  14902. }
  14903. if (data_swa) {
  14904. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  14905. for (int j = 0; j < n_kv; ++j) {
  14906. data_swa[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
  14907. }
  14908. }
  14909. }
  14910. }
  14911. } else {
  14912. const int64_t n_tokens = ubatch.n_tokens;
  14913. const int64_t n_seq_tokens = ubatch.n_seq_tokens;
  14914. const int64_t n_seqs = ubatch.n_seqs;
  14915. // when using kv cache, the mask needs to match the kv cache size
  14916. const int64_t n_stride = hparams.causal_attn && !lctx.is_encoding ? kv_self.n : n_tokens;
  14917. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  14918. float * data = (float *) lctx.inp_KQ_mask->data;
  14919. for (int h = 0; h < 1; ++h) {
  14920. for (int s1 = 0; s1 < n_seqs; ++s1) {
  14921. const llama_seq_id seq_id = ubatch.seq_id[s1][0];
  14922. for (int j = 0; j < n_seq_tokens; ++j) {
  14923. const int32_t tj = s1*n_seq_tokens + j;
  14924. for (int s0 = 0; s0 < n_seqs; ++s0) {
  14925. for (int i = 0; i < n_seq_tokens; ++i) {
  14926. const int32_t ti = s0*n_seq_tokens + i;
  14927. float f = -INFINITY;
  14928. for (int s = 0; s < ubatch.n_seq_id[s0]; ++s) {
  14929. if (ubatch.seq_id[s0][s] == seq_id) {
  14930. if (hparams.use_alibi) {
  14931. f = -std::abs(ubatch.pos[ti] - ubatch.pos[tj]);
  14932. } else {
  14933. f = 0.0f;
  14934. }
  14935. break;
  14936. }
  14937. }
  14938. data[h*(n_tokens*n_tokens) + tj*n_stride + ti] = f;
  14939. }
  14940. }
  14941. for (int i = n_tokens; i < n_stride; ++i) {
  14942. data[h*(n_tokens*n_tokens) + tj*n_stride + i] = -INFINITY;
  14943. }
  14944. }
  14945. }
  14946. }
  14947. }
  14948. }
  14949. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  14950. const int64_t n_tokens = ubatch.n_tokens;
  14951. const int64_t n_seq_tokens = ubatch.n_seq_tokens;
  14952. const int64_t n_seqs = ubatch.n_seqs;
  14953. GGML_ASSERT(lctx.inp_mean);
  14954. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  14955. float * data = (float *) lctx.inp_mean->data;
  14956. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  14957. std::vector<uint64_t> sum(n_tokens, 0);
  14958. for (int s = 0; s < n_seqs; ++s) {
  14959. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  14960. // TODO: adapt limits to n_seqs when ubatch.equal_seqs is true
  14961. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
  14962. sum[seq_id] += ubatch.n_seq_tokens;
  14963. }
  14964. std::vector<float> div(n_tokens, 0.0f);
  14965. for (int i = 0; i < n_tokens; ++i) {
  14966. const uint64_t s = sum[i];
  14967. if (s > 0) {
  14968. div[i] = 1.0f/float(s);
  14969. }
  14970. }
  14971. for (int s = 0; s < n_seqs; ++s) {
  14972. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  14973. for (int i = 0; i < n_seq_tokens; ++i) {
  14974. data[seq_id*n_tokens + s*n_seq_tokens + i] = div[seq_id];
  14975. }
  14976. }
  14977. }
  14978. if (cparams.embeddings && (
  14979. cparams.pooling_type == LLAMA_POOLING_TYPE_CLS ||
  14980. cparams.pooling_type == LLAMA_POOLING_TYPE_RANK)) {
  14981. const int64_t n_tokens = ubatch.n_tokens;
  14982. const int64_t n_seq_tokens = ubatch.n_seq_tokens;
  14983. const int64_t n_seqs = ubatch.n_seqs;
  14984. GGML_ASSERT(lctx.inp_cls);
  14985. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  14986. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  14987. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  14988. for (int s = 0; s < n_seqs; ++s) {
  14989. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  14990. // TODO: adapt limits to n_seqs when ubatch.equal_seqs is true
  14991. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS or RANK");
  14992. for (int i = 0; i < n_seq_tokens; ++i) {
  14993. const llama_pos pos = ubatch.pos[s*n_seq_tokens + i];
  14994. if (pos == 0) {
  14995. data[seq_id] = s*n_seq_tokens + i;
  14996. }
  14997. }
  14998. }
  14999. }
  15000. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_LAST) {
  15001. const int64_t n_tokens = ubatch.n_tokens;
  15002. const int64_t n_seq_tokens = ubatch.n_seq_tokens;
  15003. const int64_t n_seqs = ubatch.n_seqs;
  15004. GGML_ASSERT(lctx.inp_cls);
  15005. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  15006. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  15007. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  15008. std::vector<int> last_pos(n_tokens, -1);
  15009. std::vector<int> last_row(n_tokens, -1);
  15010. for (int s = 0; s < n_seqs; ++s) {
  15011. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  15012. // TODO: adapt limits to n_seqs when ubatch.equal_seqs is true
  15013. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == LAST");
  15014. for (int i = 0; i < n_seq_tokens; ++i) {
  15015. const llama_pos pos = ubatch.pos[s*n_seq_tokens + i];
  15016. if (pos >= last_pos[seq_id]) {
  15017. last_pos[seq_id] = pos;
  15018. last_row[seq_id] = s*n_seq_tokens + i;
  15019. }
  15020. }
  15021. }
  15022. for (int i = 0; i < n_tokens; ++i) {
  15023. if (last_row[i] >= 0) {
  15024. data[i] = last_row[i];
  15025. }
  15026. }
  15027. }
  15028. if (kv_self.recurrent) {
  15029. const int64_t n_kv = kv_self.n;
  15030. if (lctx.inp_s_mask) {
  15031. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_mask->buffer));
  15032. float * data = (float *) lctx.inp_s_mask->data;
  15033. // clear unused states
  15034. for (int i = 0; i < n_kv; ++i) {
  15035. const uint32_t cell_id = i + kv_self.head;
  15036. llama_kv_cell & kv_cell = lctx.kv_self.cells[cell_id];
  15037. data[i] = (float) (kv_cell.src >= 0);
  15038. // only clear once
  15039. if (kv_cell.src < 0) {
  15040. kv_cell.src = cell_id;
  15041. }
  15042. }
  15043. }
  15044. if (lctx.inp_s_copy) {
  15045. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  15046. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  15047. // assuming copy destinations ALWAYS happen ONLY on the cells between head and head+n
  15048. for (uint32_t i = 0; i < n_kv; ++i) {
  15049. const uint32_t cell_id = i + kv_self.head;
  15050. llama_kv_cell & kv_cell = lctx.kv_self.cells[cell_id];
  15051. // prevent out-of-bound sources
  15052. if (kv_cell.src < 0 || (uint32_t) kv_cell.src >= kv_self.size) {
  15053. kv_cell.src = cell_id;
  15054. }
  15055. data[i] = kv_cell.src;
  15056. // ensure copy only happens once
  15057. if (kv_cell.src != (int32_t) cell_id) {
  15058. kv_cell.src = cell_id;
  15059. }
  15060. }
  15061. }
  15062. }
  15063. if (lctx.inp_pos_bucket) {
  15064. const int64_t n_tokens = ubatch.n_tokens;
  15065. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_pos_bucket->buffer));
  15066. GGML_ASSERT(!ubatch.equal_seqs); // TODO: use ubatch.n_seqs instead of failing
  15067. int32_t * data = (int32_t *) lctx.inp_pos_bucket->data;
  15068. if (!lctx.is_encoding) {
  15069. const int64_t n_kv = kv_self.n;
  15070. for (int h = 0; h < 1; ++h) {
  15071. for (int j = 0; j < n_tokens; ++j) {
  15072. for (int i = 0; i < n_kv; ++i) {
  15073. data[h*(n_kv*n_tokens) + j*n_kv + i] = llama_relative_position_bucket(lctx.kv_self.cells[i].pos, ubatch.pos[j], hparams.n_rel_attn_bkts, lctx.is_encoding);
  15074. }
  15075. }
  15076. }
  15077. } else {
  15078. for (int h = 0; h < 1; ++h) {
  15079. for (int j = 0; j < n_tokens; ++j) {
  15080. for (int i = 0; i < n_tokens; ++i) {
  15081. data[h*(n_tokens*n_tokens) + j*n_tokens + i] = llama_relative_position_bucket(ubatch.pos[i], ubatch.pos[j], hparams.n_rel_attn_bkts, lctx.is_encoding);
  15082. }
  15083. }
  15084. }
  15085. }
  15086. }
  15087. if (!lctx.is_encoding && lctx.inp_embd_enc) {
  15088. assert(lctx.inp_embd_enc->type == GGML_TYPE_F32);
  15089. assert((size_t) ggml_nelements(lctx.inp_embd_enc) == lctx.embd_enc.size());
  15090. ggml_backend_tensor_set(lctx.inp_embd_enc, lctx.embd_enc.data(), 0, ggml_nbytes(lctx.inp_embd_enc));
  15091. }
  15092. if (!lctx.is_encoding && lctx.inp_KQ_mask_cross) {
  15093. const int64_t n_output_enc = lctx.embd_enc.size() / hparams.n_embd;
  15094. const int64_t n_tokens = ubatch.n_tokens;
  15095. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask_cross->buffer));
  15096. GGML_ASSERT(!ubatch.equal_seqs); // TODO: use ubatch.n_seqs instead of failing
  15097. float * data = (float *) lctx.inp_KQ_mask_cross->data;
  15098. for (int h = 0; h < 1; ++h) {
  15099. for (int j = 0; j < n_tokens; ++j) {
  15100. for (int i = 0; i < n_output_enc; ++i) {
  15101. float f = -INFINITY;
  15102. for (int s = 0; s < ubatch.n_seq_id[j]; ++s) {
  15103. const llama_seq_id seq_id = ubatch.seq_id[j][s];
  15104. if (lctx.seq_ids_enc[i].find(seq_id) != lctx.seq_ids_enc[i].end()) {
  15105. f = 0.0f;
  15106. }
  15107. }
  15108. data[h*(n_output_enc*n_tokens) + j*n_output_enc + i] = f;
  15109. }
  15110. }
  15111. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  15112. for (int j = 0; j < n_output_enc; ++j) {
  15113. data[h*(n_output_enc*n_tokens) + i*n_output_enc + j] = -INFINITY;
  15114. }
  15115. }
  15116. }
  15117. }
  15118. }
  15119. // Make sure enough space is available for outputs.
  15120. // Returns max number of outputs for which space was reserved.
  15121. static size_t llama_output_reserve(llama_context & lctx, size_t n_outputs) {
  15122. const auto & cparams = lctx.cparams;
  15123. const auto & hparams = lctx.model.hparams;
  15124. const size_t n_outputs_max = std::max(n_outputs, (size_t) cparams.n_seq_max);
  15125. const auto n_batch = cparams.n_batch;
  15126. const auto n_vocab = hparams.n_vocab;
  15127. const auto n_embd = hparams.n_embd;
  15128. // TODO: use a per-batch flag for logits presence instead
  15129. const bool has_logits = cparams.causal_attn;
  15130. const bool has_embd = cparams.embeddings && (cparams.pooling_type == LLAMA_POOLING_TYPE_NONE);
  15131. const size_t logits_size = has_logits ? n_vocab*n_outputs_max : 0;
  15132. const size_t embd_size = has_embd ? n_embd*n_outputs_max : 0;
  15133. if (lctx.output_ids.empty()) {
  15134. // init, never resized afterwards
  15135. lctx.output_ids.resize(n_batch);
  15136. }
  15137. const size_t prev_size = lctx.buf_output ? ggml_backend_buffer_get_size(lctx.buf_output.get()) : 0;
  15138. const size_t new_size = (logits_size + embd_size) * sizeof(float);
  15139. // alloc only when more than the current capacity is required
  15140. // TODO: also consider shrinking the buffer
  15141. if (!lctx.buf_output || prev_size < new_size) {
  15142. if (lctx.buf_output) {
  15143. #ifndef NDEBUG
  15144. // This doesn't happen often, but may be annoying in some cases (like the HellaSwag benchmark)
  15145. LLAMA_LOG_INFO("%s: reallocating output buffer from size %.02f MiB to %.02f MiB\n", __func__, prev_size / 1024.0 / 1024.0, new_size / 1024.0 / 1024.0);
  15146. #endif
  15147. lctx.buf_output = nullptr;
  15148. lctx.logits = nullptr;
  15149. lctx.embd = nullptr;
  15150. }
  15151. auto * buft = ggml_backend_cpu_buffer_type();
  15152. // try to use the host buffer of the device where the output tensor is allocated for faster transfer to system memory
  15153. auto * output_dev = lctx.model.dev_output.dev;
  15154. auto * output_dev_host_buft = output_dev ? ggml_backend_dev_host_buffer_type(output_dev) : nullptr;
  15155. if (output_dev_host_buft) {
  15156. buft = output_dev_host_buft;
  15157. }
  15158. lctx.buf_output.reset(ggml_backend_buft_alloc_buffer(buft, new_size));
  15159. if (lctx.buf_output == nullptr) {
  15160. LLAMA_LOG_ERROR("%s: failed to allocate output buffer of size %.2f MiB\n", __func__, new_size / (1024.0 * 1024.0));
  15161. return 0;
  15162. }
  15163. }
  15164. float * output_base = (float *) ggml_backend_buffer_get_base(lctx.buf_output.get());
  15165. lctx.logits = has_logits ? output_base : nullptr;
  15166. lctx.embd = has_embd ? output_base + logits_size : nullptr;
  15167. lctx.output_size = n_outputs_max;
  15168. lctx.logits_size = logits_size;
  15169. lctx.embd_size = embd_size;
  15170. // set all ids as invalid (negative)
  15171. std::fill(lctx.output_ids.begin(), lctx.output_ids.end(), -1);
  15172. ggml_backend_buffer_clear(lctx.buf_output.get(), 0);
  15173. lctx.n_outputs = 0;
  15174. return n_outputs_max;
  15175. }
  15176. // make the outputs have the same order they had in the user-provided batch
  15177. static void llama_output_reorder(struct llama_context * ctx) {
  15178. std::vector<size_t> & out_ids = ctx->sbatch.out_ids;
  15179. if (!out_ids.empty()) {
  15180. uint32_t n_vocab = ctx->model.hparams.n_vocab;
  15181. uint32_t n_embd = ctx->model.hparams.n_embd;
  15182. int32_t n_outputs = ctx->n_outputs;
  15183. GGML_ASSERT((size_t) n_outputs == out_ids.size());
  15184. // TODO: is there something more efficient which also minimizes swaps?
  15185. // selection sort, to minimize swaps (from https://en.wikipedia.org/wiki/Selection_sort)
  15186. for (int32_t i = 0; i < n_outputs - 1; ++i) {
  15187. int32_t j_min = i;
  15188. for (int32_t j = i + 1; j < n_outputs; ++j) {
  15189. if (out_ids[j] < out_ids[j_min]) {
  15190. j_min = j;
  15191. }
  15192. }
  15193. if (j_min == i) { continue; }
  15194. std::swap(out_ids[i], out_ids[j_min]);
  15195. if (ctx->logits_size > 0) {
  15196. for (uint32_t k = 0; k < n_vocab; k++) {
  15197. std::swap(ctx->logits[i*n_vocab + k], ctx->logits[j_min*n_vocab + k]);
  15198. }
  15199. }
  15200. if (ctx->embd_size > 0) {
  15201. for (uint32_t k = 0; k < n_embd; k++) {
  15202. std::swap(ctx->embd[i*n_embd + k], ctx->embd[j_min*n_embd + k]);
  15203. }
  15204. }
  15205. }
  15206. std::fill(ctx->output_ids.begin(), ctx->output_ids.end(), -1);
  15207. for (int32_t i = 0; i < n_outputs; ++i) {
  15208. ctx->output_ids[out_ids[i]] = i;
  15209. }
  15210. out_ids.clear();
  15211. }
  15212. }
  15213. // returns the result of ggml_backend_sched_graph_compute_async execution
  15214. static enum ggml_status llama_graph_compute(
  15215. llama_context & lctx,
  15216. ggml_cgraph * gf,
  15217. int n_threads,
  15218. ggml_threadpool * threadpool) {
  15219. if (lctx.backend_cpu != nullptr) {
  15220. auto * reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(lctx.backend_cpu));
  15221. auto * set_threadpool_fn = (decltype(ggml_backend_cpu_set_threadpool) *) ggml_backend_reg_get_proc_address(reg, "ggml_backend_cpu_set_threadpool");
  15222. set_threadpool_fn(lctx.backend_cpu, threadpool);
  15223. }
  15224. // set the number of threads for all the backends
  15225. for (const auto & set_n_threads_fn : lctx.set_n_threads_fns) {
  15226. set_n_threads_fn.second(set_n_threads_fn.first, n_threads);
  15227. }
  15228. auto status = ggml_backend_sched_graph_compute_async(lctx.sched.get(), gf);
  15229. if (status != GGML_STATUS_SUCCESS) {
  15230. LLAMA_LOG_ERROR("%s: ggml_backend_sched_graph_compute_async failed with error %d\n", __func__, status);
  15231. }
  15232. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  15233. return status;
  15234. }
  15235. // decode a batch of tokens by evaluating the transformer
  15236. // in case of unsuccessful decoding (error or warning),
  15237. // the kv_cache state will be returned to its original state
  15238. // (for non-recurrent models) or cleaned (for recurrent models)
  15239. //
  15240. // - lctx: llama context
  15241. // - batch: batch to evaluate
  15242. //
  15243. // return 0 on success
  15244. // return positive int on warning
  15245. // return negative int on error
  15246. //
  15247. static int llama_decode_internal(
  15248. llama_context & lctx,
  15249. llama_batch inp_batch) {
  15250. lctx.is_encoding = false;
  15251. if (inp_batch.n_tokens == 0) {
  15252. LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__);
  15253. return -1;
  15254. }
  15255. // temporary allocate memory for the input batch if needed
  15256. llama_batch_allocr batch_allocr(lctx, inp_batch);
  15257. const llama_batch & batch = batch_allocr.batch;
  15258. const uint32_t n_tokens_all = batch.n_tokens;
  15259. const auto & model = lctx.model;
  15260. const auto & hparams = model.hparams;
  15261. const auto & cparams = lctx.cparams;
  15262. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  15263. if (batch.token) {
  15264. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  15265. if (batch.token[i] < 0 || (uint32_t)batch.token[i] >= model.vocab.n_vocab) {
  15266. LLAMA_LOG_ERROR("%s: invalid token[%d] = %d\n", __func__, i, batch.token[i]);
  15267. return -1;
  15268. }
  15269. }
  15270. }
  15271. GGML_ASSERT(n_tokens_all <= cparams.n_batch);
  15272. GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
  15273. if (lctx.t_compute_start_us == 0) {
  15274. lctx.t_compute_start_us = ggml_time_us();
  15275. }
  15276. lctx.n_queued_tokens += n_tokens_all;
  15277. auto & kv_self = lctx.kv_self;
  15278. llama_kv_slot_restorer kv_slot_restorer(kv_self);
  15279. const int64_t n_embd = hparams.n_embd;
  15280. const int64_t n_vocab = hparams.n_vocab;
  15281. uint32_t n_outputs = 0;
  15282. uint32_t n_outputs_prev = 0;
  15283. const auto n_ubatch = cparams.n_ubatch;
  15284. // this indicates we are doing pooled embedding, so we ignore batch.logits and output all tokens
  15285. const bool embd_pooled = cparams.embeddings && cparams.pooling_type != LLAMA_POOLING_TYPE_NONE;
  15286. lctx.embd_seq.clear();
  15287. // count outputs
  15288. if (batch.logits && !embd_pooled) {
  15289. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  15290. n_outputs += batch.logits[i] != 0;
  15291. }
  15292. } else if (lctx.logits_all || embd_pooled) {
  15293. n_outputs = n_tokens_all;
  15294. } else {
  15295. // keep last output only
  15296. n_outputs = 1;
  15297. }
  15298. lctx.sbatch.from_batch(batch, batch.n_embd,
  15299. /* simple_split */ !kv_self.recurrent,
  15300. /* logits_all */ n_outputs == n_tokens_all);
  15301. // reserve output buffer
  15302. if (llama_output_reserve(lctx, n_outputs) < n_outputs) {
  15303. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_outputs);
  15304. return -2;
  15305. };
  15306. while (lctx.sbatch.n_tokens > 0) {
  15307. llama_ubatch ubatch;
  15308. if (kv_self.recurrent) {
  15309. if (embd_pooled) {
  15310. // Pooled embeddings cannot be split across ubatches (yet)
  15311. ubatch = lctx.sbatch.split_seq(n_ubatch);
  15312. } else {
  15313. // recurrent model architectures are easier to implement
  15314. // with equal-length sequences
  15315. ubatch = lctx.sbatch.split_equal(n_ubatch);
  15316. }
  15317. } else {
  15318. ubatch = lctx.sbatch.split_simple(n_ubatch);
  15319. }
  15320. const uint32_t n_tokens = ubatch.n_tokens;
  15321. // count the outputs in this u_batch
  15322. {
  15323. int32_t n_outputs_new = 0;
  15324. if (n_outputs == n_tokens_all) {
  15325. n_outputs_new = n_tokens;
  15326. } else {
  15327. GGML_ASSERT(ubatch.output);
  15328. for (uint32_t i = 0; i < n_tokens; i++) {
  15329. n_outputs_new += (int32_t) (ubatch.output[i] != 0);
  15330. }
  15331. }
  15332. // needs to happen before the graph is built
  15333. lctx.n_outputs = n_outputs_new;
  15334. }
  15335. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  15336. ggml_threadpool_t threadpool = n_tokens == 1 ? lctx.threadpool : lctx.threadpool_batch;
  15337. GGML_ASSERT(n_threads > 0);
  15338. // non-causal masks do not use the KV cache
  15339. if (hparams.causal_attn) {
  15340. llama_kv_cache_update(&lctx);
  15341. // if we have enough unused cells before the current head ->
  15342. // better to start searching from the beginning of the cache, hoping to fill it
  15343. if (kv_self.head > kv_self.used + 2*n_tokens) {
  15344. kv_self.head = 0;
  15345. }
  15346. const auto slot = llama_kv_cache_find_slot(kv_self, ubatch);
  15347. if (!slot) {
  15348. return 1;
  15349. }
  15350. kv_slot_restorer.save(slot);
  15351. if (!kv_self.recurrent) {
  15352. // a heuristic, to avoid attending the full cache if it is not yet utilized
  15353. // after enough generations, the benefit from this heuristic disappears
  15354. // if we start defragmenting the cache, the benefit from this will be more important
  15355. const uint32_t pad = llama_kv_cache_get_padding(cparams);
  15356. kv_self.n = std::min(kv_self.size, std::max(pad, GGML_PAD(llama_kv_cache_cell_max(kv_self), pad)));
  15357. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  15358. }
  15359. }
  15360. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  15361. ggml_backend_sched_reset(lctx.sched.get());
  15362. ggml_backend_sched_set_eval_callback(lctx.sched.get(), lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  15363. ggml_cgraph * gf = llama_build_graph(lctx, ubatch, false);
  15364. // the output is always the last tensor in the graph
  15365. struct ggml_tensor * res = ggml_graph_node(gf, -1);
  15366. struct ggml_tensor * embd = ggml_graph_node(gf, -2);
  15367. if (lctx.n_outputs == 0) {
  15368. // no output
  15369. res = nullptr;
  15370. embd = nullptr;
  15371. } else if (cparams.embeddings) {
  15372. embd = nullptr;
  15373. for (int i = ggml_graph_n_nodes(gf) - 1; i >= 0; --i) {
  15374. if (strcmp(ggml_graph_node(gf, i)->name, "result_embd_pooled") == 0) {
  15375. embd = ggml_graph_node(gf, i);
  15376. break;
  15377. }
  15378. }
  15379. } else {
  15380. embd = nullptr; // do not extract embeddings when not needed
  15381. GGML_ASSERT(strcmp(res->name, "result_output") == 0 && "missing result_output tensor");
  15382. }
  15383. if (!cparams.causal_attn) {
  15384. res = nullptr; // do not extract logits when not needed
  15385. }
  15386. // 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);
  15387. ggml_backend_sched_alloc_graph(lctx.sched.get(), gf);
  15388. llama_set_inputs(lctx, ubatch);
  15389. const auto compute_status = llama_graph_compute(lctx, gf, n_threads, threadpool);
  15390. if (compute_status != GGML_STATUS_SUCCESS) {
  15391. kv_slot_restorer.restore(kv_self);
  15392. switch (compute_status) {
  15393. case GGML_STATUS_ABORTED:
  15394. return 2;
  15395. case GGML_STATUS_ALLOC_FAILED:
  15396. return -2;
  15397. case GGML_STATUS_FAILED:
  15398. default:
  15399. return -3;
  15400. }
  15401. }
  15402. // update the kv ring buffer
  15403. {
  15404. kv_self.head += n_tokens;
  15405. // Ensure kv cache head points to a valid index.
  15406. if (kv_self.head >= kv_self.size) {
  15407. kv_self.head = 0;
  15408. }
  15409. }
  15410. // plot the computation graph in dot format (for debugging purposes)
  15411. //if (n_past%100 == 0) {
  15412. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  15413. //}
  15414. // extract logits
  15415. if (res) {
  15416. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(lctx.sched.get(), res);
  15417. GGML_ASSERT(backend_res != nullptr);
  15418. GGML_ASSERT(lctx.logits != nullptr);
  15419. float * logits_out = lctx.logits + n_outputs_prev*n_vocab;
  15420. const int32_t n_outputs_new = lctx.n_outputs;
  15421. if (n_outputs_new) {
  15422. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  15423. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_vocab <= (int64_t) lctx.logits_size);
  15424. ggml_backend_tensor_get_async(backend_res, res, logits_out, 0, n_outputs_new*n_vocab*sizeof(float));
  15425. }
  15426. }
  15427. // extract embeddings
  15428. if (embd) {
  15429. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched.get(), embd);
  15430. GGML_ASSERT(backend_embd != nullptr);
  15431. switch (cparams.pooling_type) {
  15432. case LLAMA_POOLING_TYPE_NONE:
  15433. {
  15434. // extract token embeddings
  15435. GGML_ASSERT(lctx.embd != nullptr);
  15436. float * embd_out = lctx.embd + n_outputs_prev*n_embd;
  15437. const int32_t n_outputs_new = lctx.n_outputs;
  15438. if (n_outputs_new) {
  15439. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  15440. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_embd <= (int64_t) lctx.embd_size);
  15441. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_outputs_new*n_embd*sizeof(float));
  15442. }
  15443. } break;
  15444. case LLAMA_POOLING_TYPE_MEAN:
  15445. case LLAMA_POOLING_TYPE_CLS:
  15446. case LLAMA_POOLING_TYPE_LAST:
  15447. {
  15448. // extract sequence embeddings (cleared before processing each batch)
  15449. auto & embd_seq_out = lctx.embd_seq;
  15450. for (uint32_t s = 0; s < ubatch.n_seqs; ++s) {
  15451. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  15452. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  15453. continue;
  15454. }
  15455. embd_seq_out[seq_id].resize(n_embd);
  15456. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  15457. }
  15458. } break;
  15459. case LLAMA_POOLING_TYPE_RANK:
  15460. {
  15461. // extract the rerank score - a single float per sequence
  15462. auto & embd_seq_out = lctx.embd_seq;
  15463. for (uint32_t s = 0; s < ubatch.n_seqs; ++s) {
  15464. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  15465. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  15466. continue;
  15467. }
  15468. embd_seq_out[seq_id].resize(1);
  15469. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (seq_id)*sizeof(float), sizeof(float));
  15470. }
  15471. } break;
  15472. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  15473. {
  15474. GGML_ABORT("unknown pooling type");
  15475. }
  15476. }
  15477. }
  15478. n_outputs_prev += lctx.n_outputs;
  15479. }
  15480. // set output mappings
  15481. {
  15482. bool sorted_output = true;
  15483. GGML_ASSERT(lctx.sbatch.out_ids.size() == n_outputs);
  15484. for (size_t i = 0; i < n_outputs; ++i) {
  15485. size_t out_id = lctx.sbatch.out_ids[i];
  15486. lctx.output_ids[out_id] = i;
  15487. if (out_id != i) {
  15488. sorted_output = false;
  15489. }
  15490. }
  15491. if (sorted_output) {
  15492. lctx.sbatch.out_ids.clear();
  15493. }
  15494. }
  15495. // set to total number of outputs in the batch, for use in llama_get_logits_ith
  15496. lctx.n_outputs = n_outputs;
  15497. // wait for the computation to finish (automatically done when obtaining the model output)
  15498. //llama_synchronize(&lctx);
  15499. // decide if we need to defrag the kv cache
  15500. if (cparams.causal_attn && cparams.defrag_thold >= 0.0f) {
  15501. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used)/float(kv_self.n) : 0.0f;
  15502. // queue defragmentation for next llama_kv_cache_update
  15503. if (fragmentation > cparams.defrag_thold) {
  15504. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  15505. llama_kv_cache_defrag(kv_self);
  15506. }
  15507. }
  15508. // Reset state for the next token before backend sync, to allow the CPU activities in the reset to
  15509. // overlap with device computation.
  15510. ggml_backend_sched_reset(lctx.sched.get());
  15511. return 0;
  15512. }
  15513. // encode a batch of tokens by evaluating the encoder part of the transformer
  15514. //
  15515. // - lctx: llama context
  15516. // - batch: batch to evaluate
  15517. //
  15518. // return 0 on success
  15519. // return positive int on warning
  15520. // return negative int on error
  15521. //
  15522. static int llama_encode_internal(
  15523. llama_context & lctx,
  15524. llama_batch inp_batch) {
  15525. lctx.is_encoding = true;
  15526. if (inp_batch.n_tokens == 0) {
  15527. LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__);
  15528. return -1;
  15529. }
  15530. // temporary allocate memory for the input batch if needed
  15531. llama_batch_allocr batch_allocr(lctx, inp_batch);
  15532. const llama_batch & batch = batch_allocr.batch;
  15533. const uint32_t n_tokens = batch.n_tokens;
  15534. const auto & model = lctx.model;
  15535. const auto & hparams = model.hparams;
  15536. const auto & cparams = lctx.cparams;
  15537. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  15538. if (batch.token) {
  15539. for (uint32_t i = 0; i < n_tokens; ++i) {
  15540. if (batch.token[i] < 0 || (uint32_t)batch.token[i] >= model.vocab.n_vocab) {
  15541. LLAMA_LOG_ERROR("%s: invalid token[%d] = %d\n", __func__, i, batch.token[i]);
  15542. return -1;
  15543. }
  15544. }
  15545. }
  15546. // micro-batching is not possible for non-causal encoding, so we process the batch in a single shot
  15547. GGML_ASSERT(cparams.n_ubatch >= n_tokens && "encoder requires n_ubatch >= n_tokens");
  15548. if (lctx.t_compute_start_us == 0) {
  15549. lctx.t_compute_start_us = ggml_time_us();
  15550. }
  15551. lctx.n_queued_tokens += n_tokens;
  15552. const int64_t n_embd = hparams.n_embd;
  15553. lctx.sbatch.from_batch(batch, batch.n_embd, /* simple_split */ true, /* logits_all */ true);
  15554. const llama_ubatch ubatch = lctx.sbatch.split_simple(n_tokens);
  15555. // reserve output buffer
  15556. if (llama_output_reserve(lctx, n_tokens) < n_tokens) {
  15557. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_tokens);
  15558. return -2;
  15559. };
  15560. for (uint32_t i = 0; i < n_tokens; ++i) {
  15561. lctx.output_ids[i] = i;
  15562. }
  15563. lctx.inp_embd_enc = NULL;
  15564. lctx.n_outputs = n_tokens;
  15565. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  15566. ggml_threadpool_t threadpool = n_tokens == 1 ? lctx.threadpool : lctx.threadpool_batch;
  15567. GGML_ASSERT(n_threads > 0);
  15568. ggml_backend_sched_reset(lctx.sched.get());
  15569. ggml_backend_sched_set_eval_callback(lctx.sched.get(), lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  15570. ggml_cgraph * gf = llama_build_graph(lctx, ubatch, false);
  15571. // the output embeddings after the final encoder normalization
  15572. struct ggml_tensor * embd = nullptr;
  15573. // there are two cases here
  15574. if (llama_model_has_decoder(&lctx.model)) {
  15575. // first case is an encoder-decoder T5 model where embeddings are passed to decoder
  15576. embd = ggml_graph_node(gf, -1);
  15577. GGML_ASSERT(strcmp(embd->name, "result_norm") == 0 && "missing result_output tensor");
  15578. } else {
  15579. // second case is an encoder-only T5 model
  15580. if (cparams.embeddings) {
  15581. // only output embeddings if required
  15582. embd = ggml_graph_node(gf, -1);
  15583. if (strcmp(embd->name, "result_embd_pooled") != 0) {
  15584. embd = ggml_graph_node(gf, -2);
  15585. }
  15586. GGML_ASSERT(strcmp(embd->name, "result_embd_pooled") == 0 && "missing embeddings tensor");
  15587. }
  15588. }
  15589. ggml_backend_sched_alloc_graph(lctx.sched.get(), gf);
  15590. llama_set_inputs(lctx, ubatch);
  15591. const auto compute_status = llama_graph_compute(lctx, gf, n_threads, threadpool);
  15592. switch (compute_status) {
  15593. case GGML_STATUS_SUCCESS:
  15594. break;
  15595. case GGML_STATUS_ABORTED:
  15596. return 2;
  15597. case GGML_STATUS_ALLOC_FAILED:
  15598. return -2;
  15599. case GGML_STATUS_FAILED:
  15600. default:
  15601. return -3;
  15602. }
  15603. // extract embeddings
  15604. if (embd) {
  15605. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched.get(), embd);
  15606. GGML_ASSERT(backend_embd != nullptr);
  15607. if (llama_model_has_decoder(&lctx.model)) {
  15608. lctx.embd_enc.resize(n_tokens*n_embd);
  15609. float * embd_out = lctx.embd_enc.data();
  15610. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_tokens*n_embd*sizeof(float));
  15611. GGML_ASSERT(!ubatch.equal_seqs); // TODO: handle equal splits
  15612. // remember the sequence ids used during the encoding - needed for cross attention later
  15613. lctx.seq_ids_enc.resize(n_tokens);
  15614. for (uint32_t i = 0; i < n_tokens; i++) {
  15615. for (int s = 0; s < ubatch.n_seq_id[i]; s++) {
  15616. llama_seq_id seq_id = ubatch.seq_id[i][s];
  15617. lctx.seq_ids_enc[i].insert(seq_id);
  15618. }
  15619. }
  15620. } else {
  15621. GGML_ASSERT(lctx.embd != nullptr);
  15622. switch (cparams.pooling_type) {
  15623. case LLAMA_POOLING_TYPE_NONE:
  15624. {
  15625. // extract token embeddings
  15626. GGML_ASSERT(lctx.embd != nullptr);
  15627. float * embd_out = lctx.embd;
  15628. GGML_ASSERT(n_tokens*n_embd <= (int64_t) lctx.embd_size);
  15629. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_tokens*n_embd*sizeof(float));
  15630. } break;
  15631. case LLAMA_POOLING_TYPE_MEAN:
  15632. case LLAMA_POOLING_TYPE_CLS:
  15633. case LLAMA_POOLING_TYPE_LAST:
  15634. {
  15635. // extract sequence embeddings
  15636. auto & embd_seq_out = lctx.embd_seq;
  15637. embd_seq_out.clear();
  15638. GGML_ASSERT(!ubatch.equal_seqs); // TODO: handle equal splits
  15639. for (uint32_t i = 0; i < n_tokens; i++) {
  15640. const llama_seq_id seq_id = ubatch.seq_id[i][0];
  15641. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  15642. continue;
  15643. }
  15644. embd_seq_out[seq_id].resize(n_embd);
  15645. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  15646. }
  15647. } break;
  15648. case LLAMA_POOLING_TYPE_RANK:
  15649. {
  15650. // TODO: this likely should be the same logic as in llama_decoder_internal, but better to
  15651. // wait for an encoder model that requires this pooling type in order to test it
  15652. // https://github.com/ggerganov/llama.cpp/pull/9510
  15653. GGML_ABORT("RANK pooling not implemented yet");
  15654. }
  15655. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  15656. {
  15657. GGML_ABORT("unknown pooling type");
  15658. }
  15659. }
  15660. }
  15661. }
  15662. // Reset state for the next token before backend sync, to allow the CPU activities in the reset to
  15663. // overlap with device computation.
  15664. ggml_backend_sched_reset(lctx.sched.get());
  15665. return 0;
  15666. }
  15667. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  15668. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  15669. auto & kv_self = lctx.kv_self;
  15670. const auto & hparams = lctx.model.hparams;
  15671. const uint32_t n_layer = hparams.n_layer;
  15672. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  15673. const uint32_t n_used = kv_self.used;
  15674. assert(n_used <= n_kv);
  15675. //const int64_t t_start = ggml_time_us();
  15676. // number of cells moved
  15677. uint32_t n_moves = 0;
  15678. // each move requires 6*n_layer tensors (see build_defrag)
  15679. // - source view, destination view, copy operation
  15680. // - x2 for keys and values
  15681. //const uint32_t max_moves = llama_model_max_nodes(model)/(6*n_layer);
  15682. // TODO: tmp fix https://github.com/ggerganov/llama.cpp/issues/6685#issuecomment-2057579516
  15683. const uint32_t max_moves = (llama_model_max_nodes(lctx.model) - 2*n_layer)/(6*n_layer);
  15684. // determine which KV cells to move where
  15685. //
  15686. // cell i moves to ids[i]
  15687. //
  15688. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  15689. //
  15690. std::vector<uint32_t> ids(n_kv, n_kv);
  15691. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  15692. const auto & cell0 = kv_self.cells[i0];
  15693. if (!cell0.is_empty()) {
  15694. ids[i0] = i0;
  15695. continue;
  15696. }
  15697. // found a hole - fill it with data from the end of the cache
  15698. uint32_t nh = 1;
  15699. // determine the size of the hole
  15700. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  15701. nh++;
  15702. }
  15703. uint32_t nf = 0;
  15704. uint32_t is = n_kv - 1;
  15705. // starting from the end, find nh non-empty cells
  15706. for (; is > i0; --is) {
  15707. const auto & cell1 = kv_self.cells[is];
  15708. if (cell1.is_empty() || ids[is] != n_kv) {
  15709. continue;
  15710. }
  15711. // non-empty cell which is not yet moved
  15712. nf++;
  15713. if (nf == nh) {
  15714. break;
  15715. }
  15716. }
  15717. // this can only happen if `n_used` is not accurate, which would be a bug
  15718. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  15719. nf = 0;
  15720. uint32_t i1 = is;
  15721. // are we moving a continuous block of memory?
  15722. bool cont = false;
  15723. // should we stop searching for the next move?
  15724. bool stop = false;
  15725. // go back and move the nf cells to the hole
  15726. for (; i1 < n_kv; ++i1) {
  15727. auto & cell1 = kv_self.cells[i1];
  15728. if (cell1.is_empty() || ids[i1] != n_kv) {
  15729. if (n_moves == max_moves) {
  15730. stop = true;
  15731. break;
  15732. }
  15733. cont = false;
  15734. continue;
  15735. }
  15736. // this cell goes to (i0 + nf)
  15737. ids[i1] = i0 + nf;
  15738. // move the cell meta data
  15739. kv_self.cells[i0 + nf] = cell1;
  15740. // clear the old cell and move the head there
  15741. cell1 = llama_kv_cell();
  15742. kv_self.head = n_used;
  15743. if (!cont) {
  15744. n_moves++;
  15745. cont = true;
  15746. }
  15747. nf++;
  15748. if (nf == nh) {
  15749. break;
  15750. }
  15751. }
  15752. if (stop || n_moves == max_moves) {
  15753. break;
  15754. }
  15755. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  15756. i0 += nh - 1;
  15757. }
  15758. if (n_moves == 0) {
  15759. return;
  15760. }
  15761. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  15762. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  15763. #if 0
  15764. // CPU defrag
  15765. //
  15766. // TODO: optimizations are possible:
  15767. // - multiple threads
  15768. // - avoid copying to the host memory when already there
  15769. //
  15770. // likely not worth the effort, as we have ggml_graph based defrag
  15771. //
  15772. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  15773. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  15774. const uint32_t kv_size = kv_self.size;
  15775. std::vector<uint8_t> buf_k;
  15776. std::vector<uint8_t> buf_v;
  15777. for (uint32_t il = 0; il < n_layer; ++il) {
  15778. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  15779. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  15780. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  15781. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  15782. buf_k.resize(k_size);
  15783. buf_v.resize(v_size);
  15784. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  15785. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  15786. // batch move [i, i+nm) to [id, id+nm)
  15787. // note: cells can move only to a lower index
  15788. for (uint32_t i = 0; i < n_kv; ++i) {
  15789. const uint32_t id = ids[i];
  15790. if (i == id || id == n_kv) {
  15791. continue;
  15792. }
  15793. uint32_t nm = 1;
  15794. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  15795. nm++;
  15796. }
  15797. // move keys
  15798. {
  15799. const int64_t os = i*k_size_row;
  15800. const int64_t od = id*k_size_row;
  15801. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  15802. }
  15803. // move values (note: they are transposed)
  15804. {
  15805. const int64_t os = i;
  15806. const int64_t od = id;
  15807. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  15808. 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);
  15809. }
  15810. }
  15811. i += nm - 1;
  15812. }
  15813. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  15814. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  15815. }
  15816. #else
  15817. // ggml_graph defrag
  15818. ggml_backend_sched_reset(lctx.sched.get());
  15819. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  15820. llama_graph_compute(lctx, gf, lctx.cparams.n_threads, lctx.threadpool);
  15821. #endif
  15822. //const int64_t t_end = ggml_time_us();
  15823. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  15824. }
  15825. static void llama_kv_cache_update_internal(struct llama_context & lctx) {
  15826. bool need_reserve = false;
  15827. if (lctx.kv_self.has_shift) {
  15828. if (!llama_kv_cache_can_shift(&lctx)) {
  15829. GGML_ABORT("The current context does not support K-shift");
  15830. }
  15831. // apply K-shift if needed
  15832. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE) {
  15833. ggml_backend_sched_reset(lctx.sched.get());
  15834. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  15835. ggml_backend_sched_alloc_graph(lctx.sched.get(), gf);
  15836. llama_set_k_shift(lctx);
  15837. llama_graph_compute(lctx, gf, lctx.cparams.n_threads, lctx.threadpool);
  15838. need_reserve = true;
  15839. }
  15840. {
  15841. auto & kv_self = lctx.kv_self;
  15842. kv_self.has_shift = false;
  15843. for (uint32_t i = 0; i < kv_self.size; ++i) {
  15844. kv_self.cells[i].delta = 0;
  15845. }
  15846. }
  15847. }
  15848. // defragment the KV cache if needed
  15849. if (lctx.kv_self.do_defrag) {
  15850. llama_kv_cache_defrag_internal(lctx);
  15851. need_reserve = true;
  15852. lctx.kv_self.do_defrag = false;
  15853. }
  15854. // reserve a worst case graph again
  15855. if (need_reserve) {
  15856. // TODO: extract to a function
  15857. // build worst-case graph
  15858. uint32_t n_seqs = 1; // TODO: worst-case number of sequences
  15859. uint32_t n_tokens = std::min(lctx.cparams.n_ctx, lctx.cparams.n_ubatch);
  15860. 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
  15861. llama_ubatch ubatch = { true, n_tokens, n_tokens / n_seqs, n_seqs, &token, nullptr, nullptr, nullptr, nullptr, nullptr};
  15862. ggml_cgraph * gf = llama_build_graph(lctx, ubatch, true);
  15863. // initialize scheduler with the worst-case graph
  15864. ggml_backend_sched_reset(lctx.sched.get());
  15865. if (!ggml_backend_sched_reserve(lctx.sched.get(), gf)) {
  15866. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  15867. }
  15868. }
  15869. }
  15870. //
  15871. // quantization
  15872. //
  15873. struct quantize_state_internal {
  15874. const llama_model & model;
  15875. const llama_model_quantize_params * params;
  15876. int n_attention_wv = 0;
  15877. int n_ffn_down = 0;
  15878. int n_ffn_gate = 0;
  15879. int n_ffn_up = 0;
  15880. int i_attention_wv = 0;
  15881. int i_ffn_down = 0;
  15882. int i_ffn_gate = 0;
  15883. int i_ffn_up = 0;
  15884. int n_k_quantized = 0;
  15885. int n_fallback = 0;
  15886. bool has_imatrix = false;
  15887. // used to figure out if a model shares tok_embd with the output weight
  15888. bool has_output = false;
  15889. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  15890. : model(model)
  15891. , params(params)
  15892. {}
  15893. };
  15894. static void llama_tensor_dequantize_internal(
  15895. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  15896. const size_t nelements, const int nthread
  15897. ) {
  15898. if (output.size() < nelements) {
  15899. output.resize(nelements);
  15900. }
  15901. float * f32_output = (float *) output.data();
  15902. const ggml_type_traits * qtype = ggml_get_type_traits(tensor->type);
  15903. if (ggml_is_quantized(tensor->type)) {
  15904. if (qtype->to_float == NULL) {
  15905. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  15906. }
  15907. } else if (tensor->type != GGML_TYPE_F16 &&
  15908. tensor->type != GGML_TYPE_BF16) {
  15909. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  15910. }
  15911. if (nthread < 2) {
  15912. if (tensor->type == GGML_TYPE_F16) {
  15913. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  15914. } else if (tensor->type == GGML_TYPE_BF16) {
  15915. ggml_bf16_to_fp32_row((ggml_bf16_t *)tensor->data, f32_output, nelements);
  15916. } else if (ggml_is_quantized(tensor->type)) {
  15917. qtype->to_float(tensor->data, f32_output, nelements);
  15918. } else {
  15919. GGML_ABORT("fatal error"); // unreachable
  15920. }
  15921. return;
  15922. }
  15923. size_t block_size;
  15924. if (tensor->type == GGML_TYPE_F16 ||
  15925. tensor->type == GGML_TYPE_BF16) {
  15926. block_size = 1;
  15927. } else {
  15928. block_size = (size_t)ggml_blck_size(tensor->type);
  15929. }
  15930. size_t block_size_bytes = ggml_type_size(tensor->type);
  15931. GGML_ASSERT(nelements % block_size == 0);
  15932. size_t nblocks = nelements / block_size;
  15933. size_t blocks_per_thread = nblocks / nthread;
  15934. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  15935. size_t in_buff_offs = 0;
  15936. size_t out_buff_offs = 0;
  15937. for (int tnum = 0; tnum < nthread; tnum++) {
  15938. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  15939. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  15940. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  15941. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  15942. if (typ == GGML_TYPE_F16) {
  15943. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  15944. } else if (typ == GGML_TYPE_BF16) {
  15945. ggml_bf16_to_fp32_row((ggml_bf16_t *)inbuf, outbuf, nels);
  15946. } else {
  15947. qtype->to_float(inbuf, outbuf, nels);
  15948. }
  15949. };
  15950. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  15951. in_buff_offs += thr_block_bytes;
  15952. out_buff_offs += thr_elems;
  15953. }
  15954. for (auto & w : workers) { w.join(); }
  15955. workers.clear();
  15956. }
  15957. static ggml_type llama_tensor_get_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  15958. const std::string name = ggml_get_name(tensor);
  15959. // TODO: avoid hardcoded tensor names - use the TN_* constants
  15960. const llm_arch arch = qs.model.arch;
  15961. const auto tn = LLM_TN(arch);
  15962. auto use_more_bits = [](int i_layer, int n_layers) -> bool {
  15963. return i_layer < n_layers/8 || i_layer >= 7*n_layers/8 || (i_layer - n_layers/8)%3 == 2;
  15964. };
  15965. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  15966. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  15967. if (n_expert > 1) {
  15968. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but occasionally randomly
  15969. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  15970. // for getting the current layer as I initially thought, and we need to resort to parsing the
  15971. // tensor name.
  15972. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  15973. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  15974. }
  15975. if (i_layer < 0 || i_layer >= n_layer) {
  15976. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  15977. }
  15978. }
  15979. return std::make_pair(i_layer, n_layer);
  15980. };
  15981. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  15982. // with the quantization of the output tensor
  15983. if (name == tn(LLM_TENSOR_OUTPUT, "weight") || (!qs.has_output && name == tn(LLM_TENSOR_TOKEN_EMBD, "weight"))) {
  15984. if (qs.params->output_tensor_type < GGML_TYPE_COUNT) {
  15985. new_type = qs.params->output_tensor_type;
  15986. } else {
  15987. int nx = tensor->ne[0];
  15988. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  15989. new_type = GGML_TYPE_Q8_0;
  15990. }
  15991. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  15992. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ||
  15993. ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  15994. new_type = GGML_TYPE_Q5_K;
  15995. }
  15996. else if (new_type != GGML_TYPE_Q8_0) {
  15997. new_type = GGML_TYPE_Q6_K;
  15998. }
  15999. }
  16000. } else if (name == "token_embd.weight") {
  16001. if (qs.params->token_embedding_type < GGML_TYPE_COUNT) {
  16002. new_type = qs.params->token_embedding_type;
  16003. } else {
  16004. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
  16005. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  16006. new_type = GGML_TYPE_Q2_K;
  16007. }
  16008. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  16009. new_type = GGML_TYPE_IQ3_S;
  16010. }
  16011. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  16012. new_type = GGML_TYPE_IQ3_S;
  16013. }
  16014. else if (new_type == GGML_TYPE_Q4_0_4_4 || new_type == GGML_TYPE_Q4_0_4_8 ||
  16015. new_type == GGML_TYPE_Q4_0_8_8) {
  16016. new_type = GGML_TYPE_Q4_0;
  16017. }
  16018. else if (ftype == LLAMA_FTYPE_MOSTLY_TQ1_0 || ftype == LLAMA_FTYPE_MOSTLY_TQ2_0) {
  16019. new_type = GGML_TYPE_Q4_K;
  16020. }
  16021. }
  16022. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  16023. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  16024. if (name.find("attn_v.weight") != std::string::npos) {
  16025. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  16026. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  16027. ++qs.i_attention_wv;
  16028. }
  16029. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  16030. new_type = GGML_TYPE_Q4_K;
  16031. }
  16032. else if (name.find("ffn_down") != std::string::npos) {
  16033. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  16034. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  16035. }
  16036. ++qs.i_ffn_down;
  16037. }
  16038. else if (name.find("attn_output.weight") != std::string::npos) {
  16039. if (qs.model.hparams.n_expert == 8) {
  16040. new_type = GGML_TYPE_Q5_K;
  16041. } else {
  16042. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) new_type = GGML_TYPE_IQ2_XXS;
  16043. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  16044. }
  16045. }
  16046. } else if (name.find("attn_v.weight") != std::string::npos) {
  16047. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  16048. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  16049. }
  16050. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  16051. new_type = GGML_TYPE_Q4_K;
  16052. }
  16053. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  16054. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  16055. }
  16056. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S) && qs.model.hparams.n_gqa() >= 4) {
  16057. new_type = GGML_TYPE_Q4_K;
  16058. }
  16059. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  16060. new_type = GGML_TYPE_Q4_K;
  16061. }
  16062. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  16063. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  16064. }
  16065. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  16066. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  16067. new_type = GGML_TYPE_Q5_K;
  16068. }
  16069. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  16070. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  16071. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  16072. if (qs.model.type == MODEL_70B) {
  16073. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  16074. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  16075. // nearly negligible increase in model size by quantizing this tensor with more bits:
  16076. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  16077. }
  16078. if (qs.model.hparams.n_expert == 8) {
  16079. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  16080. // TODO: explore better strategies
  16081. new_type = GGML_TYPE_Q8_0;
  16082. }
  16083. ++qs.i_attention_wv;
  16084. } else if (name.find("attn_k.weight") != std::string::npos) {
  16085. if (qs.model.hparams.n_expert == 8) {
  16086. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  16087. // TODO: explore better strategies
  16088. new_type = GGML_TYPE_Q8_0;
  16089. }
  16090. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  16091. new_type = GGML_TYPE_IQ3_XXS;
  16092. }
  16093. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  16094. new_type = GGML_TYPE_IQ2_S;
  16095. }
  16096. } else if (name.find("attn_q.weight") != std::string::npos) {
  16097. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  16098. new_type = GGML_TYPE_IQ3_XXS;
  16099. }
  16100. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  16101. new_type = GGML_TYPE_IQ2_S;
  16102. }
  16103. } else if (name.find("ffn_down") != std::string::npos) {
  16104. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  16105. int i_layer = info.first, n_layer = info.second;
  16106. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  16107. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  16108. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  16109. }
  16110. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  16111. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  16112. }
  16113. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  16114. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  16115. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  16116. : GGML_TYPE_Q3_K;
  16117. }
  16118. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  16119. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  16120. new_type = GGML_TYPE_Q4_K;
  16121. }
  16122. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  16123. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  16124. }
  16125. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  16126. if (arch == LLM_ARCH_FALCON) {
  16127. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  16128. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  16129. } else {
  16130. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  16131. }
  16132. }
  16133. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  16134. new_type = GGML_TYPE_Q5_K;
  16135. }
  16136. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  16137. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  16138. new_type = GGML_TYPE_Q5_K;
  16139. }
  16140. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  16141. && qs.has_imatrix && i_layer < n_layer/8) {
  16142. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  16143. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  16144. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  16145. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  16146. }
  16147. ++qs.i_ffn_down;
  16148. } else if (name.find("attn_output.weight") != std::string::npos) {
  16149. if (arch != LLM_ARCH_FALCON) {
  16150. if (qs.model.hparams.n_expert == 8) {
  16151. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  16152. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  16153. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  16154. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  16155. new_type = GGML_TYPE_Q5_K;
  16156. }
  16157. } else {
  16158. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  16159. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  16160. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  16161. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  16162. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  16163. }
  16164. } else {
  16165. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  16166. }
  16167. }
  16168. else if (name.find("attn_qkv.weight") != std::string::npos) {
  16169. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  16170. new_type = GGML_TYPE_Q4_K;
  16171. }
  16172. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  16173. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  16174. }
  16175. else if (name.find("ffn_gate") != std::string::npos) {
  16176. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  16177. int i_layer = info.first, n_layer = info.second;
  16178. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  16179. new_type = GGML_TYPE_IQ3_XXS;
  16180. }
  16181. ++qs.i_ffn_gate;
  16182. }
  16183. else if (name.find("ffn_up") != std::string::npos) {
  16184. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  16185. int i_layer = info.first, n_layer = info.second;
  16186. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  16187. new_type = GGML_TYPE_IQ3_XXS;
  16188. }
  16189. ++qs.i_ffn_up;
  16190. }
  16191. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  16192. //}
  16193. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  16194. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  16195. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  16196. //}
  16197. // This can be used to reduce the size of the Q5_K_S model.
  16198. // The associated PPL increase is fully in line with the size reduction
  16199. //else {
  16200. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  16201. //}
  16202. bool convert_incompatible_tensor = false;
  16203. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  16204. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  16205. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  16206. new_type == GGML_TYPE_IQ3_XXS || new_type == GGML_TYPE_IQ1_S || new_type == GGML_TYPE_IQ3_S ||
  16207. new_type == GGML_TYPE_IQ1_M) {
  16208. int nx = tensor->ne[0];
  16209. int ny = tensor->ne[1];
  16210. if (nx % QK_K != 0) {
  16211. 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));
  16212. convert_incompatible_tensor = true;
  16213. } else {
  16214. ++qs.n_k_quantized;
  16215. }
  16216. }
  16217. if (convert_incompatible_tensor) {
  16218. switch (new_type) {
  16219. case GGML_TYPE_TQ1_0:
  16220. case GGML_TYPE_TQ2_0: new_type = GGML_TYPE_Q4_0; break; // TODO: use a symmetric type instead
  16221. case GGML_TYPE_IQ2_XXS:
  16222. case GGML_TYPE_IQ2_XS:
  16223. case GGML_TYPE_IQ2_S:
  16224. case GGML_TYPE_IQ3_XXS:
  16225. case GGML_TYPE_IQ3_S:
  16226. case GGML_TYPE_IQ1_S:
  16227. case GGML_TYPE_IQ1_M:
  16228. case GGML_TYPE_Q2_K:
  16229. case GGML_TYPE_Q3_K:
  16230. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  16231. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  16232. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  16233. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  16234. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  16235. }
  16236. if (tensor->ne[0] % ggml_blck_size(new_type) != 0) {
  16237. new_type = GGML_TYPE_F16;
  16238. }
  16239. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  16240. ++qs.n_fallback;
  16241. }
  16242. return new_type;
  16243. }
  16244. static size_t llama_tensor_quantize_internal(enum ggml_type new_type, const float * f32_data, void * new_data, const int64_t chunk_size, int64_t nrows, int64_t n_per_row, const float * imatrix, std::vector<std::thread> & workers, const int nthread) {
  16245. if (nthread < 2) {
  16246. // single-thread
  16247. size_t new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, imatrix);
  16248. if (!ggml_validate_row_data(new_type, new_data, new_size)) {
  16249. throw std::runtime_error("quantized data validation failed");
  16250. }
  16251. return new_size;
  16252. }
  16253. std::mutex mutex;
  16254. int64_t counter = 0;
  16255. size_t new_size = 0;
  16256. bool valid = true;
  16257. auto compute = [&mutex, &counter, &new_size, &valid, new_type, f32_data, new_data, chunk_size,
  16258. nrows, n_per_row, imatrix]() {
  16259. const int64_t nrows_per_chunk = chunk_size / n_per_row;
  16260. size_t local_size = 0;
  16261. while (true) {
  16262. std::unique_lock<std::mutex> lock(mutex);
  16263. int64_t first_row = counter; counter += nrows_per_chunk;
  16264. if (first_row >= nrows) {
  16265. if (local_size > 0) {
  16266. new_size += local_size;
  16267. }
  16268. break;
  16269. }
  16270. lock.unlock();
  16271. const int64_t this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  16272. size_t this_size = ggml_quantize_chunk(new_type, f32_data, new_data, first_row * n_per_row, this_nrow, n_per_row, imatrix);
  16273. local_size += this_size;
  16274. // validate the quantized data
  16275. const size_t row_size = ggml_row_size(new_type, n_per_row);
  16276. void * this_data = (char *) new_data + first_row * row_size;
  16277. if (!ggml_validate_row_data(new_type, this_data, this_size)) {
  16278. std::unique_lock<std::mutex> lock(mutex);
  16279. valid = false;
  16280. break;
  16281. }
  16282. }
  16283. };
  16284. for (int it = 0; it < nthread - 1; ++it) {
  16285. workers.emplace_back(compute);
  16286. }
  16287. compute();
  16288. for (auto & w : workers) { w.join(); }
  16289. workers.clear();
  16290. if (!valid) {
  16291. throw std::runtime_error("quantized data validation failed");
  16292. }
  16293. return new_size;
  16294. }
  16295. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  16296. ggml_type default_type;
  16297. llama_ftype ftype = params->ftype;
  16298. switch (params->ftype) {
  16299. case LLAMA_FTYPE_MOSTLY_Q4_0: default_type = GGML_TYPE_Q4_0; break;
  16300. case LLAMA_FTYPE_MOSTLY_Q4_1: default_type = GGML_TYPE_Q4_1; break;
  16301. case LLAMA_FTYPE_MOSTLY_Q5_0: default_type = GGML_TYPE_Q5_0; break;
  16302. case LLAMA_FTYPE_MOSTLY_Q5_1: default_type = GGML_TYPE_Q5_1; break;
  16303. case LLAMA_FTYPE_MOSTLY_Q8_0: default_type = GGML_TYPE_Q8_0; break;
  16304. case LLAMA_FTYPE_MOSTLY_F16: default_type = GGML_TYPE_F16; break;
  16305. case LLAMA_FTYPE_MOSTLY_BF16: default_type = GGML_TYPE_BF16; break;
  16306. case LLAMA_FTYPE_ALL_F32: default_type = GGML_TYPE_F32; break;
  16307. // K-quants
  16308. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  16309. case LLAMA_FTYPE_MOSTLY_Q2_K: default_type = GGML_TYPE_Q2_K; break;
  16310. case LLAMA_FTYPE_MOSTLY_IQ3_XS: default_type = GGML_TYPE_IQ3_S; break;
  16311. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  16312. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  16313. case LLAMA_FTYPE_MOSTLY_Q3_K_L: default_type = GGML_TYPE_Q3_K; break;
  16314. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  16315. case LLAMA_FTYPE_MOSTLY_Q4_K_M: default_type = GGML_TYPE_Q4_K; break;
  16316. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  16317. case LLAMA_FTYPE_MOSTLY_Q5_K_M: default_type = GGML_TYPE_Q5_K; break;
  16318. case LLAMA_FTYPE_MOSTLY_Q6_K: default_type = GGML_TYPE_Q6_K; break;
  16319. case LLAMA_FTYPE_MOSTLY_TQ1_0: default_type = GGML_TYPE_TQ1_0; break;
  16320. case LLAMA_FTYPE_MOSTLY_TQ2_0: default_type = GGML_TYPE_TQ2_0; break;
  16321. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: default_type = GGML_TYPE_IQ2_XXS; break;
  16322. case LLAMA_FTYPE_MOSTLY_IQ2_XS: default_type = GGML_TYPE_IQ2_XS; break;
  16323. case LLAMA_FTYPE_MOSTLY_IQ2_S: default_type = GGML_TYPE_IQ2_XS; break;
  16324. case LLAMA_FTYPE_MOSTLY_IQ2_M: default_type = GGML_TYPE_IQ2_S; break;
  16325. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: default_type = GGML_TYPE_IQ3_XXS; break;
  16326. case LLAMA_FTYPE_MOSTLY_IQ1_S: default_type = GGML_TYPE_IQ1_S; break;
  16327. case LLAMA_FTYPE_MOSTLY_IQ1_M: default_type = GGML_TYPE_IQ1_M; break;
  16328. case LLAMA_FTYPE_MOSTLY_IQ4_NL: default_type = GGML_TYPE_IQ4_NL; break;
  16329. case LLAMA_FTYPE_MOSTLY_IQ4_XS: default_type = GGML_TYPE_IQ4_XS; break;
  16330. case LLAMA_FTYPE_MOSTLY_IQ3_S: default_type = GGML_TYPE_IQ3_S; break;
  16331. case LLAMA_FTYPE_MOSTLY_IQ3_M: default_type = GGML_TYPE_IQ3_S; break;
  16332. case LLAMA_FTYPE_MOSTLY_Q4_0_4_4: default_type = GGML_TYPE_Q4_0_4_4; break;
  16333. case LLAMA_FTYPE_MOSTLY_Q4_0_4_8: default_type = GGML_TYPE_Q4_0_4_8; break;
  16334. case LLAMA_FTYPE_MOSTLY_Q4_0_8_8: default_type = GGML_TYPE_Q4_0_8_8; break;
  16335. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  16336. }
  16337. int nthread = params->nthread;
  16338. if (nthread <= 0) {
  16339. nthread = std::thread::hardware_concurrency();
  16340. }
  16341. // mmap consistently increases speed Linux, and also increases speed on Windows with
  16342. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  16343. #if defined(__linux__) || defined(_WIN32)
  16344. constexpr bool use_mmap = true;
  16345. #else
  16346. constexpr bool use_mmap = false;
  16347. #endif
  16348. llama_model_kv_override * kv_overrides = nullptr;
  16349. if (params->kv_overrides) {
  16350. auto v = (std::vector<llama_model_kv_override>*)params->kv_overrides;
  16351. kv_overrides = v->data();
  16352. }
  16353. llama_model_loader ml(fname_inp, use_mmap, /*check_tensors*/ true, kv_overrides);
  16354. ml.init_mappings(false); // no prefetching
  16355. llama_model model;
  16356. llm_load_arch(ml, model);
  16357. llm_load_hparams(ml, model);
  16358. llm_load_stats(ml, model);
  16359. struct quantize_state_internal qs(model, params);
  16360. if (params->only_copy) {
  16361. ftype = model.ftype;
  16362. }
  16363. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  16364. if (params->imatrix) {
  16365. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  16366. if (imatrix_data) {
  16367. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  16368. qs.has_imatrix = true;
  16369. // check imatrix for nans or infs
  16370. for (const auto & kv : *imatrix_data) {
  16371. for (float f : kv.second) {
  16372. if (!std::isfinite(f)) {
  16373. throw std::runtime_error(format("imatrix contains non-finite value %f\n", f));
  16374. }
  16375. }
  16376. }
  16377. }
  16378. }
  16379. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  16380. gguf_context_ptr ctx_out { gguf_init_empty() };
  16381. // copy the KV pairs from the input file
  16382. gguf_set_kv (ctx_out.get(), ml.meta.get());
  16383. gguf_set_val_u32(ctx_out.get(), "general.quantization_version", GGML_QNT_VERSION); // TODO: use LLM_KV
  16384. gguf_set_val_u32(ctx_out.get(), "general.file_type", ftype); // TODO: use LLM_KV
  16385. // Remove split metadata
  16386. gguf_remove_key(ctx_out.get(), ml.llm_kv(LLM_KV_SPLIT_NO).c_str());
  16387. gguf_remove_key(ctx_out.get(), ml.llm_kv(LLM_KV_SPLIT_COUNT).c_str());
  16388. gguf_remove_key(ctx_out.get(), ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str());
  16389. if (params->kv_overrides) {
  16390. const std::vector<llama_model_kv_override> & overrides = *(const std::vector<llama_model_kv_override> *)params->kv_overrides;
  16391. for (const auto & o : overrides) {
  16392. if (o.key[0] == 0) break;
  16393. if (o.tag == LLAMA_KV_OVERRIDE_TYPE_FLOAT) {
  16394. gguf_set_val_f32(ctx_out.get(), o.key, o.val_f64);
  16395. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_INT) {
  16396. gguf_set_val_i32(ctx_out.get(), o.key, o.val_i64);
  16397. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_BOOL) {
  16398. gguf_set_val_bool(ctx_out.get(), o.key, o.val_bool);
  16399. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_STR) {
  16400. gguf_set_val_str(ctx_out.get(), o.key, o.val_str);
  16401. } else {
  16402. LLAMA_LOG_WARN("%s: unknown KV override type for key %s\n", __func__, o.key);
  16403. }
  16404. }
  16405. }
  16406. // make a list of weights
  16407. std::vector<const llama_model_loader::llama_tensor_weight *> tensors;
  16408. tensors.reserve(ml.weights_map.size());
  16409. for (const auto & it : ml.weights_map) {
  16410. tensors.push_back(&it.second);
  16411. }
  16412. // keep_split requires that the weights are sorted by split index
  16413. if (params->keep_split) {
  16414. std::sort(tensors.begin(), tensors.end(), [](const llama_model_loader::llama_tensor_weight * a, const llama_model_loader::llama_tensor_weight * b) {
  16415. if (a->idx == b->idx) {
  16416. return a->offs < b->offs;
  16417. }
  16418. return a->idx < b->idx;
  16419. });
  16420. }
  16421. for (const auto * it : tensors) {
  16422. const struct ggml_tensor * tensor = it->tensor;
  16423. const std::string name = ggml_get_name(tensor);
  16424. // TODO: avoid hardcoded tensor names - use the TN_* constants
  16425. if (name.find("attn_v.weight") != std::string::npos ||
  16426. name.find("attn_qkv.weight") != std::string::npos ||
  16427. name.find("attn_kv_b.weight")!= std::string::npos) {
  16428. ++qs.n_attention_wv;
  16429. } else if (name == LLM_TN(model.arch)(LLM_TENSOR_OUTPUT, "weight")) {
  16430. qs.has_output = true;
  16431. }
  16432. }
  16433. qs.n_ffn_down = qs.n_ffn_gate = qs.n_ffn_up = (int)model.hparams.n_layer;
  16434. // sanity checks
  16435. {
  16436. const auto & n_head_kv_iter = model.hparams.n_head_kv_arr.begin();
  16437. // attention layers have a non-zero number of kv heads
  16438. int32_t n_attn_layer = model.hparams.n_layer - std::count(n_head_kv_iter, n_head_kv_iter + model.hparams.n_layer, 0);
  16439. if (llama_model_has_encoder(&model)) {
  16440. n_attn_layer *= 3;
  16441. }
  16442. if (qs.n_attention_wv != n_attn_layer) {
  16443. LLAMA_LOG_WARN("%s: n_attention_wv is unexpected, expected: %d, found: %d\n", __func__, n_attn_layer, qs.n_attention_wv);
  16444. }
  16445. }
  16446. size_t total_size_org = 0;
  16447. size_t total_size_new = 0;
  16448. std::vector<std::thread> workers;
  16449. workers.reserve(nthread);
  16450. int idx = 0;
  16451. std::vector<no_init<uint8_t>> read_data;
  16452. std::vector<no_init<uint8_t>> work;
  16453. std::vector<no_init<float>> f32_conv_buf;
  16454. uint16_t n_split = 1;
  16455. // Assume split index is continuous
  16456. if (params->keep_split) {
  16457. for (const auto * it : tensors) {
  16458. n_split = std::max(uint16_t(it->idx + 1), n_split);
  16459. }
  16460. }
  16461. std::vector<gguf_context_ptr> ctx_outs(n_split);
  16462. ctx_outs[0] = std::move(ctx_out);
  16463. // populate the original tensors so we get an initial meta data
  16464. for (const auto * it : tensors) {
  16465. uint16_t i_split = params->keep_split ? it->idx : 0;
  16466. struct ggml_tensor * tensor = it->tensor;
  16467. if (!ctx_outs[i_split]) {
  16468. ctx_outs[i_split].reset(gguf_init_empty());
  16469. }
  16470. gguf_add_tensor(ctx_outs[i_split].get(), tensor);
  16471. }
  16472. // Set split info if needed
  16473. if (n_split > 1) {
  16474. for (size_t i = 0; i < ctx_outs.size(); ++i) {
  16475. gguf_set_val_u16(ctx_outs[i].get(), ml.llm_kv(LLM_KV_SPLIT_NO).c_str(), i);
  16476. gguf_set_val_u16(ctx_outs[i].get(), ml.llm_kv(LLM_KV_SPLIT_COUNT).c_str(), n_split);
  16477. gguf_set_val_i32(ctx_outs[i].get(), ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str(), ml.n_tensors);
  16478. }
  16479. }
  16480. int cur_split = -1;
  16481. std::ofstream fout;
  16482. auto close_ofstream = [&]() {
  16483. // Write metadata and close file handler
  16484. if (fout.is_open()) {
  16485. fout.seekp(0);
  16486. std::vector<uint8_t> data(gguf_get_meta_size(ctx_outs[cur_split].get()));
  16487. gguf_get_meta_data(ctx_outs[cur_split].get(), data.data());
  16488. fout.write((const char *) data.data(), data.size());
  16489. fout.close();
  16490. }
  16491. };
  16492. auto new_ofstream = [&](int index) {
  16493. cur_split = index;
  16494. GGML_ASSERT(ctx_outs[cur_split] && "Find uninitialized gguf_context");
  16495. std::string fname = fname_out;
  16496. if (params->keep_split) {
  16497. char split_path[PATH_MAX] = {0};
  16498. llama_split_path(split_path, sizeof(split_path), fname_out.c_str(), cur_split, n_split);
  16499. fname = std::string(split_path);
  16500. }
  16501. fout = std::ofstream(fname, std::ios::binary);
  16502. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  16503. const size_t meta_size = gguf_get_meta_size(ctx_outs[cur_split].get());
  16504. // placeholder for the meta data
  16505. ::zeros(fout, meta_size);
  16506. };
  16507. const auto tn = LLM_TN(model.arch);
  16508. new_ofstream(0);
  16509. for (const auto * it : tensors) {
  16510. const auto & weight = *it;
  16511. struct ggml_tensor * tensor = weight.tensor;
  16512. if (weight.idx != cur_split && params->keep_split) {
  16513. close_ofstream();
  16514. new_ofstream(weight.idx);
  16515. }
  16516. const std::string name = ggml_get_name(tensor);
  16517. if (!ml.use_mmap) {
  16518. if (read_data.size() < ggml_nbytes(tensor)) {
  16519. read_data.resize(ggml_nbytes(tensor));
  16520. }
  16521. tensor->data = read_data.data();
  16522. }
  16523. ml.load_data_for(tensor);
  16524. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  16525. ++idx, ml.n_tensors,
  16526. ggml_get_name(tensor),
  16527. llama_format_tensor_shape(tensor).c_str(),
  16528. ggml_type_name(tensor->type));
  16529. // This used to be a regex, but <regex> has an extreme cost to compile times.
  16530. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  16531. // quantize only 2D and 3D tensors (experts)
  16532. quantize &= (ggml_n_dims(tensor) >= 2);
  16533. // do not quantize norm tensors
  16534. quantize &= name.find("_norm.weight") == std::string::npos;
  16535. quantize &= params->quantize_output_tensor || name != "output.weight";
  16536. quantize &= !params->only_copy;
  16537. // do not quantize expert gating tensors
  16538. // NOTE: can't use LLM_TN here because the layer number is not known
  16539. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  16540. // do not quantize positional embeddings and token types (BERT)
  16541. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  16542. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  16543. // do not quantize Mamba's small yet 2D weights
  16544. // NOTE: can't use LLM_TN here because the layer number is not known
  16545. quantize &= name.find("ssm_conv1d.weight") == std::string::npos;
  16546. // do not quantize RWKV's time_mix_first tensors
  16547. quantize &= name.find("time_mix_first.weight") == std::string::npos;
  16548. quantize &= name.find("time_mix_w1.weight") == std::string::npos;
  16549. quantize &= name.find("time_mix_w2.weight") == std::string::npos;
  16550. quantize &= name.find("time_mix_decay_w1.weight") == std::string::npos;
  16551. quantize &= name.find("time_mix_decay_w2.weight") == std::string::npos;
  16552. // do not quantize relative position bias (T5)
  16553. quantize &= name.find("attn_rel_b.weight") == std::string::npos;
  16554. enum ggml_type new_type;
  16555. void * new_data;
  16556. size_t new_size;
  16557. if (quantize) {
  16558. new_type = default_type;
  16559. // get more optimal quantization type based on the tensor shape, layer, etc.
  16560. if (!params->pure && ggml_is_quantized(default_type)) {
  16561. new_type = llama_tensor_get_type(qs, new_type, tensor, ftype);
  16562. }
  16563. if (params->token_embedding_type < GGML_TYPE_COUNT && strcmp(tensor->name, "token_embd.weight") == 0) {
  16564. new_type = params->token_embedding_type;
  16565. }
  16566. if (params->output_tensor_type < GGML_TYPE_COUNT && strcmp(tensor->name, "output.weight") == 0) {
  16567. new_type = params->output_tensor_type;
  16568. }
  16569. // If we've decided to quantize to the same type the tensor is already
  16570. // in then there's nothing to do.
  16571. quantize = tensor->type != new_type;
  16572. }
  16573. if (!quantize) {
  16574. new_type = tensor->type;
  16575. new_data = tensor->data;
  16576. new_size = ggml_nbytes(tensor);
  16577. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  16578. } else {
  16579. const int64_t nelements = ggml_nelements(tensor);
  16580. const float * imatrix = nullptr;
  16581. if (imatrix_data) {
  16582. auto it = imatrix_data->find(tensor->name);
  16583. if (it == imatrix_data->end()) {
  16584. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  16585. } else {
  16586. if (it->second.size() == (size_t)tensor->ne[0]*tensor->ne[2]) {
  16587. imatrix = it->second.data();
  16588. } else {
  16589. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  16590. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name);
  16591. // this can happen when quantizing an old mixtral model with split tensors with a new incompatible imatrix
  16592. // this is a significant error and it may be good idea to abort the process if this happens,
  16593. // since many people will miss the error and not realize that most of the model is being quantized without an imatrix
  16594. // tok_embd should be ignored in this case, since it always causes this warning
  16595. if (name != tn(LLM_TENSOR_TOKEN_EMBD, "weight")) {
  16596. throw std::runtime_error(format("imatrix size %d is different from tensor size %d for %s",
  16597. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name));
  16598. }
  16599. }
  16600. }
  16601. }
  16602. if ((new_type == GGML_TYPE_IQ2_XXS ||
  16603. new_type == GGML_TYPE_IQ2_XS ||
  16604. new_type == GGML_TYPE_IQ2_S ||
  16605. new_type == GGML_TYPE_IQ1_S ||
  16606. (new_type == GGML_TYPE_IQ1_M && strcmp(tensor->name, "token_embd.weight") && strcmp(tensor->name, "output.weight")) ||
  16607. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  16608. LLAMA_LOG_ERROR("\n\n============================================================\n");
  16609. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  16610. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  16611. LLAMA_LOG_ERROR("============================================================\n\n");
  16612. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  16613. }
  16614. float * f32_data;
  16615. if (tensor->type == GGML_TYPE_F32) {
  16616. f32_data = (float *) tensor->data;
  16617. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  16618. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  16619. } else {
  16620. llama_tensor_dequantize_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  16621. f32_data = (float *) f32_conv_buf.data();
  16622. }
  16623. int chunk_size_multiplier = 1;
  16624. if (new_type == GGML_TYPE_Q4_0_4_4 || new_type == GGML_TYPE_Q4_0_4_8 || new_type == GGML_TYPE_Q4_0_8_8) {
  16625. if ((new_type == GGML_TYPE_Q4_0_8_8) && (tensor->ne[1] % 8 != 0)) new_type = GGML_TYPE_Q4_0;
  16626. else if (tensor->ne[1] % 4 != 0) new_type = GGML_TYPE_Q4_0;
  16627. if (new_type == GGML_TYPE_Q4_0_8_8) chunk_size_multiplier = 8;
  16628. else if (new_type == GGML_TYPE_Q4_0_4_4 || new_type == GGML_TYPE_Q4_0_4_8) chunk_size_multiplier = 4;
  16629. }
  16630. LLAMA_LOG_INFO("converting to %s .. ", ggml_type_name(new_type));
  16631. fflush(stdout);
  16632. if (work.size() < (size_t)nelements * 4) {
  16633. work.resize(nelements * 4); // upper bound on size
  16634. }
  16635. new_data = work.data();
  16636. const int64_t n_per_row = tensor->ne[0];
  16637. const int64_t nrows = tensor->ne[1];
  16638. static const int64_t min_chunk_size = 32 * 512;
  16639. const int64_t chunk_size = (n_per_row >= min_chunk_size ? n_per_row : n_per_row * ((min_chunk_size + n_per_row - 1)/n_per_row)) *
  16640. chunk_size_multiplier;
  16641. const int64_t nelements_matrix = tensor->ne[0] * tensor->ne[1];
  16642. const int64_t nchunk = (nelements_matrix + chunk_size - 1)/chunk_size;
  16643. const int64_t nthread_use = nthread > 1 ? std::max((int64_t)1, std::min((int64_t)nthread, nchunk)) : 1;
  16644. // quantize each expert separately since they have different importance matrices
  16645. new_size = 0;
  16646. for (int64_t i03 = 0; i03 < tensor->ne[2]; ++i03) {
  16647. const float * f32_data_03 = f32_data + i03 * nelements_matrix;
  16648. void * new_data_03 = (char *)new_data + ggml_row_size(new_type, n_per_row) * i03 * nrows;
  16649. const float * imatrix_03 = imatrix ? imatrix + i03 * n_per_row : nullptr;
  16650. new_size += llama_tensor_quantize_internal(new_type, f32_data_03, new_data_03, chunk_size, nrows, n_per_row, imatrix_03, workers, nthread_use);
  16651. }
  16652. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB\n", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  16653. }
  16654. total_size_org += ggml_nbytes(tensor);
  16655. total_size_new += new_size;
  16656. // update the gguf meta data as we go
  16657. gguf_set_tensor_type(ctx_outs[cur_split].get(), name.c_str(), new_type);
  16658. gguf_set_tensor_data(ctx_outs[cur_split].get(), name.c_str(), new_data, new_size);
  16659. // write tensor data + padding
  16660. fout.write((const char *) new_data, new_size);
  16661. zeros(fout, GGML_PAD(new_size, align) - new_size);
  16662. }
  16663. close_ofstream();
  16664. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  16665. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  16666. if (qs.n_fallback > 0) {
  16667. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n",
  16668. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  16669. }
  16670. }
  16671. static void llama_lora_adapter_init_internal(struct llama_model * model, const char * path_lora, struct llama_lora_adapter & adapter) {
  16672. LLAMA_LOG_INFO("%s: loading lora adapter from '%s' ...\n", __func__, path_lora);
  16673. ggml_context * ctx_init;
  16674. struct gguf_init_params meta_gguf_params = {
  16675. /* .no_alloc = */ true,
  16676. /* .ctx = */ &ctx_init,
  16677. };
  16678. gguf_context_ptr ctx_gguf { gguf_init_from_file(path_lora, meta_gguf_params) };
  16679. if (!ctx_gguf) {
  16680. throw std::runtime_error("failed to load lora adapter file from " + std::string(path_lora));
  16681. }
  16682. ggml_context_ptr ctx { ctx_init };
  16683. // check metadata
  16684. {
  16685. auto get_kv_str = [&](const std::string & key) -> std::string {
  16686. int id = gguf_find_key(ctx_gguf.get(), key.c_str());
  16687. return id < 0 ? "" : std::string(gguf_get_val_str(ctx_gguf.get(), id));
  16688. };
  16689. auto get_kv_f32 = [&](const std::string & key) -> float {
  16690. int id = gguf_find_key(ctx_gguf.get(), key.c_str());
  16691. return id < 0 ? 0.0f : gguf_get_val_f32(ctx_gguf.get(), id);
  16692. };
  16693. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  16694. auto general_type = get_kv_str(llm_kv(LLM_KV_GENERAL_TYPE));
  16695. if (general_type != "adapter") {
  16696. throw std::runtime_error("expect general.type to be 'adapter', but got: " + general_type);
  16697. }
  16698. auto general_arch_str = get_kv_str(llm_kv(LLM_KV_GENERAL_ARCHITECTURE));
  16699. auto general_arch = llm_arch_from_string(general_arch_str);
  16700. if (general_arch != model->arch) {
  16701. throw std::runtime_error("model arch and LoRA arch mismatch");
  16702. }
  16703. auto adapter_type = get_kv_str(llm_kv(LLM_KV_ADAPTER_TYPE));
  16704. if (adapter_type != "lora") {
  16705. throw std::runtime_error("expect adapter.type to be 'lora', but got: " + adapter_type);
  16706. }
  16707. adapter.alpha = get_kv_f32(llm_kv(LLM_KV_ADAPTER_LORA_ALPHA));
  16708. }
  16709. int n_tensors = gguf_get_n_tensors(ctx_gguf.get());
  16710. // contexts for each buffer type
  16711. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  16712. auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
  16713. auto it = ctx_map.find(buft);
  16714. if (it == ctx_map.end()) {
  16715. // add a new context
  16716. struct ggml_init_params params = {
  16717. /*.mem_size =*/ n_tensors*ggml_tensor_overhead(),
  16718. /*.mem_buffer =*/ NULL,
  16719. /*.no_alloc =*/ true,
  16720. };
  16721. ggml_context * buft_ctx = ggml_init(params);
  16722. if (!buft_ctx) {
  16723. return nullptr;
  16724. }
  16725. ctx_map[buft] = buft_ctx;
  16726. adapter.ctxs.emplace_back(buft_ctx);
  16727. return buft_ctx;
  16728. };
  16729. return it->second;
  16730. };
  16731. // bundle lora_a and lora_b into pairs
  16732. std::map<std::string, llama_lora_weight> ab_map;
  16733. auto str_endswith = [](const std::string & str, const std::string & suffix) {
  16734. return str.size() >= suffix.size() && str.compare(str.size()-suffix.size(), suffix.size(), suffix) == 0;
  16735. };
  16736. for (ggml_tensor * cur = ggml_get_first_tensor(ctx.get()); cur; cur = ggml_get_next_tensor(ctx.get(), cur)) {
  16737. std::string name(cur->name);
  16738. if (str_endswith(name, ".lora_a")) {
  16739. replace_all(name, ".lora_a", "");
  16740. if (ab_map.find(name) == ab_map.end()) {
  16741. ab_map[name] = llama_lora_weight(cur, nullptr);
  16742. } else {
  16743. ab_map[name].a = cur;
  16744. }
  16745. } else if (str_endswith(name, ".lora_b")) {
  16746. replace_all(name, ".lora_b", "");
  16747. if (ab_map.find(name) == ab_map.end()) {
  16748. ab_map[name] = llama_lora_weight(nullptr, cur);
  16749. } else {
  16750. ab_map[name].b = cur;
  16751. }
  16752. } else {
  16753. throw std::runtime_error("LoRA tensor '" + name + "' has unexpected suffix");
  16754. }
  16755. }
  16756. // add tensors
  16757. for (auto & it : ab_map) {
  16758. const std::string & name = it.first;
  16759. llama_lora_weight & w = it.second;
  16760. if (!w.a || !w.b) {
  16761. throw std::runtime_error("LoRA tensor pair for '" + name + "' is missing one component");
  16762. }
  16763. // device buft and device ctx
  16764. auto * model_tensor = llama_get_model_tensor(model, name.c_str());
  16765. if (!model_tensor) {
  16766. throw std::runtime_error("LoRA tensor '" + name + "' does not exist in base model");
  16767. }
  16768. struct ggml_context * dev_ctx = ctx_for_buft(ggml_backend_buffer_get_type(model_tensor->buffer));
  16769. // validate tensor shape
  16770. if (model_tensor->ne[0] != w.a->ne[0] || model_tensor->ne[1] != w.b->ne[1]) {
  16771. throw std::runtime_error("tensor '" + name + "' has incorrect shape");
  16772. }
  16773. if (w.a->ne[1] != w.b->ne[0]) {
  16774. throw std::runtime_error("lora_a tensor is not transposed (hint: adapter from \"finetune\" example is no longer supported)");
  16775. }
  16776. // save tensor to adapter
  16777. struct ggml_tensor * tensor_a = ggml_dup_tensor(dev_ctx, w.a);
  16778. struct ggml_tensor * tensor_b = ggml_dup_tensor(dev_ctx, w.b);
  16779. ggml_set_name(tensor_a, w.a->name);
  16780. ggml_set_name(tensor_b, w.b->name);
  16781. adapter.ab_map[name] = llama_lora_weight(tensor_a, tensor_b);
  16782. }
  16783. // allocate tensors / buffers and zero
  16784. {
  16785. adapter.ctxs.reserve(ctx_map.size());
  16786. adapter.bufs.reserve(ctx_map.size());
  16787. for (auto & it : ctx_map) {
  16788. ggml_backend_buffer_type_t buft = it.first;
  16789. ggml_context * ctx_dev = it.second;
  16790. ggml_backend_buffer_ptr buf { ggml_backend_alloc_ctx_tensors_from_buft(ctx_dev, buft) };
  16791. if (!buf) {
  16792. throw std::runtime_error("failed to allocate buffer for lora adapter\n");
  16793. }
  16794. LLAMA_LOG_INFO("%s: %10s LoRA buffer size = %8.2f MiB\n", __func__, ggml_backend_buffer_name(buf.get()), ggml_backend_buffer_get_size(buf.get())/1024.0/1024.0);
  16795. adapter.bufs.emplace_back(std::move(buf));
  16796. }
  16797. }
  16798. // set tensor data
  16799. {
  16800. llama_file gguf_file(path_lora, "rb");
  16801. std::vector<uint8_t> read_buf;
  16802. auto set_tensor = [&](struct ggml_tensor * orig, struct ggml_tensor * dev) {
  16803. size_t offs = gguf_get_data_offset(ctx_gguf.get()) + gguf_get_tensor_offset(ctx_gguf.get(), gguf_find_tensor(ctx_gguf.get(), orig->name));
  16804. size_t size = ggml_nbytes(orig);
  16805. read_buf.resize(size);
  16806. gguf_file.seek(offs, SEEK_SET);
  16807. gguf_file.read_raw(read_buf.data(), size);
  16808. ggml_backend_tensor_set(dev, read_buf.data(), 0, size);
  16809. };
  16810. for (auto & it : adapter.ab_map) {
  16811. auto orig = ab_map[it.first];
  16812. auto dev = it.second;
  16813. set_tensor(orig.a, dev.a);
  16814. set_tensor(orig.b, dev.b);
  16815. }
  16816. }
  16817. LLAMA_LOG_INFO("%s: loaded %zu tensors from lora file\n", __func__, adapter.ab_map.size()*2);
  16818. }
  16819. int32_t llama_lora_adapter_set(
  16820. struct llama_context * ctx,
  16821. struct llama_lora_adapter * adapter,
  16822. float scale) {
  16823. if (ctx->cparams.flash_attn) {
  16824. LLAMA_LOG_ERROR("%s: flash_attn is not compatible with LoRA\n", __func__);
  16825. return -1;
  16826. }
  16827. ctx->lora_adapters[adapter] = scale;
  16828. return 0;
  16829. }
  16830. int32_t llama_lora_adapter_remove(
  16831. struct llama_context * ctx,
  16832. struct llama_lora_adapter * adapter) {
  16833. auto pos = ctx->lora_adapters.find(adapter);
  16834. if (pos != ctx->lora_adapters.end()) {
  16835. ctx->lora_adapters.erase(pos);
  16836. return 0;
  16837. }
  16838. return -1;
  16839. }
  16840. void llama_lora_adapter_clear(struct llama_context * ctx) {
  16841. ctx->lora_adapters.clear();
  16842. }
  16843. void llama_lora_adapter_free(struct llama_lora_adapter * adapter) {
  16844. delete adapter;
  16845. }
  16846. //
  16847. // interface implementation
  16848. //
  16849. struct llama_model_params llama_model_default_params() {
  16850. struct llama_model_params result = {
  16851. /*.devices =*/ nullptr,
  16852. /*.n_gpu_layers =*/ 0,
  16853. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  16854. /*.main_gpu =*/ 0,
  16855. /*.tensor_split =*/ nullptr,
  16856. /*.rpc_servers =*/ nullptr,
  16857. /*.progress_callback =*/ nullptr,
  16858. /*.progress_callback_user_data =*/ nullptr,
  16859. /*.kv_overrides =*/ nullptr,
  16860. /*.vocab_only =*/ false,
  16861. /*.use_mmap =*/ true,
  16862. /*.use_mlock =*/ false,
  16863. /*.check_tensors =*/ false,
  16864. };
  16865. #ifdef GGML_USE_METAL
  16866. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  16867. result.n_gpu_layers = 999;
  16868. #endif
  16869. return result;
  16870. }
  16871. struct llama_context_params llama_context_default_params() {
  16872. struct llama_context_params result = {
  16873. /*.n_ctx =*/ 512,
  16874. /*.n_batch =*/ 2048,
  16875. /*.n_ubatch =*/ 512,
  16876. /*.n_seq_max =*/ 1,
  16877. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  16878. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  16879. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  16880. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  16881. /*.attention_type =*/ LLAMA_ATTENTION_TYPE_UNSPECIFIED,
  16882. /*.rope_freq_base =*/ 0.0f,
  16883. /*.rope_freq_scale =*/ 0.0f,
  16884. /*.yarn_ext_factor =*/ -1.0f,
  16885. /*.yarn_attn_factor =*/ 1.0f,
  16886. /*.yarn_beta_fast =*/ 32.0f,
  16887. /*.yarn_beta_slow =*/ 1.0f,
  16888. /*.yarn_orig_ctx =*/ 0,
  16889. /*.defrag_thold =*/ -1.0f,
  16890. /*.cb_eval =*/ nullptr,
  16891. /*.cb_eval_user_data =*/ nullptr,
  16892. /*.type_k =*/ GGML_TYPE_F16,
  16893. /*.type_v =*/ GGML_TYPE_F16,
  16894. /*.logits_all =*/ false,
  16895. /*.embeddings =*/ false,
  16896. /*.offload_kqv =*/ true,
  16897. /*.flash_attn =*/ false,
  16898. /*.no_perf =*/ true,
  16899. /*.abort_callback =*/ nullptr,
  16900. /*.abort_callback_data =*/ nullptr,
  16901. };
  16902. return result;
  16903. }
  16904. struct llama_sampler_chain_params llama_sampler_chain_default_params() {
  16905. struct llama_sampler_chain_params result = {
  16906. /*.no_perf =*/ true,
  16907. };
  16908. return result;
  16909. }
  16910. struct llama_model_quantize_params llama_model_quantize_default_params() {
  16911. struct llama_model_quantize_params result = {
  16912. /*.nthread =*/ 0,
  16913. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  16914. /*.output_tensor_type =*/ GGML_TYPE_COUNT,
  16915. /*.token_embedding_type =*/ GGML_TYPE_COUNT,
  16916. /*.allow_requantize =*/ false,
  16917. /*.quantize_output_tensor =*/ true,
  16918. /*.only_copy =*/ false,
  16919. /*.pure =*/ false,
  16920. /*.keep_split =*/ false,
  16921. /*.imatrix =*/ nullptr,
  16922. /*.kv_overrides =*/ nullptr,
  16923. };
  16924. return result;
  16925. }
  16926. size_t llama_max_devices(void) {
  16927. return 16;
  16928. }
  16929. bool llama_supports_mmap(void) {
  16930. return llama_mmap::SUPPORTED;
  16931. }
  16932. bool llama_supports_mlock(void) {
  16933. return llama_mlock::SUPPORTED;
  16934. }
  16935. bool llama_supports_gpu_offload(void) {
  16936. return ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_GPU) != nullptr ||
  16937. llama_supports_rpc();
  16938. }
  16939. bool llama_supports_rpc(void) {
  16940. return ggml_backend_reg_by_name("RPC") != nullptr;
  16941. }
  16942. void llama_backend_init(void) {
  16943. ggml_time_init();
  16944. // needed to initialize f16 tables
  16945. {
  16946. struct ggml_init_params params = { 0, NULL, false };
  16947. struct ggml_context * ctx = ggml_init(params);
  16948. ggml_free(ctx);
  16949. }
  16950. }
  16951. void llama_numa_init(enum ggml_numa_strategy numa) {
  16952. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  16953. auto * dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
  16954. GGML_ASSERT(dev && "CPU backend is not loaded");
  16955. auto * reg = ggml_backend_dev_backend_reg(dev);
  16956. auto * numa_init_fn = (decltype(ggml_numa_init) *) ggml_backend_reg_get_proc_address(reg, "ggml_backend_cpu_numa_init");
  16957. numa_init_fn(numa);
  16958. }
  16959. }
  16960. void llama_attach_threadpool(
  16961. struct llama_context * ctx,
  16962. ggml_threadpool_t threadpool,
  16963. ggml_threadpool_t threadpool_batch) {
  16964. ctx->threadpool = threadpool;
  16965. ctx->threadpool_batch = threadpool_batch ? threadpool_batch : threadpool;
  16966. }
  16967. void llama_detach_threadpool(struct llama_context * ctx) {
  16968. ctx->threadpool = nullptr;
  16969. ctx->threadpool_batch = nullptr;
  16970. }
  16971. void llama_backend_free(void) {
  16972. ggml_quantize_free();
  16973. }
  16974. int64_t llama_time_us(void) {
  16975. return ggml_time_us();
  16976. }
  16977. struct llama_model * llama_load_model_from_file(
  16978. const char * path_model,
  16979. struct llama_model_params params) {
  16980. ggml_time_init();
  16981. llama_model * model = new llama_model;
  16982. unsigned cur_percentage = 0;
  16983. if (params.progress_callback == NULL) {
  16984. params.progress_callback_user_data = &cur_percentage;
  16985. params.progress_callback = [](float progress, void * ctx) {
  16986. unsigned * cur_percentage_p = (unsigned *) ctx;
  16987. unsigned percentage = (unsigned) (100 * progress);
  16988. while (percentage > *cur_percentage_p) {
  16989. *cur_percentage_p = percentage;
  16990. LLAMA_LOG_CONT(".");
  16991. if (percentage >= 100) {
  16992. LLAMA_LOG_CONT("\n");
  16993. }
  16994. }
  16995. return true;
  16996. };
  16997. }
  16998. if (params.rpc_servers != nullptr && params.rpc_servers[0] != '\0') {
  16999. // split the servers set them into model->rpc_servers
  17000. std::string servers(params.rpc_servers);
  17001. size_t pos = 0;
  17002. while ((pos = servers.find(',')) != std::string::npos) {
  17003. std::string server = servers.substr(0, pos);
  17004. model->rpc_servers.push_back(server);
  17005. servers.erase(0, pos + 1);
  17006. }
  17007. model->rpc_servers.push_back(servers);
  17008. }
  17009. // add RPC devices
  17010. if (!model->rpc_servers.empty()) {
  17011. ggml_backend_reg_t rpc_reg = ggml_backend_reg_by_name("RPC");
  17012. if (!rpc_reg) {
  17013. LLAMA_LOG_ERROR("%s: failed to find RPC backend\n", __func__);
  17014. llama_free_model(model);
  17015. return nullptr;
  17016. }
  17017. typedef ggml_backend_dev_t (*ggml_backend_rpc_add_device_t)(const char * endpoint);
  17018. ggml_backend_rpc_add_device_t ggml_backend_rpc_add_device_fn = (ggml_backend_rpc_add_device_t) ggml_backend_reg_get_proc_address(rpc_reg, "ggml_backend_rpc_add_device");
  17019. if (!ggml_backend_rpc_add_device_fn) {
  17020. LLAMA_LOG_ERROR("%s: failed to find RPC device add function\n", __func__);
  17021. llama_free_model(model);
  17022. return nullptr;
  17023. }
  17024. for (const std::string & server : model->rpc_servers) {
  17025. ggml_backend_dev_t dev = ggml_backend_rpc_add_device_fn(server.c_str());
  17026. if (dev) {
  17027. model->devices.push_back(dev);
  17028. } else {
  17029. LLAMA_LOG_ERROR("%s: failed to add RPC device for server '%s'\n", __func__, server.c_str());
  17030. llama_free_model(model);
  17031. return nullptr;
  17032. }
  17033. }
  17034. }
  17035. // create list of devices to use with this model
  17036. if (params.devices) {
  17037. for (ggml_backend_dev_t * dev = params.devices; *dev; ++dev) {
  17038. model->devices.push_back(*dev);
  17039. }
  17040. } else {
  17041. // use all available devices
  17042. for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
  17043. ggml_backend_dev_t dev = ggml_backend_dev_get(i);
  17044. switch (ggml_backend_dev_type(dev)) {
  17045. case GGML_BACKEND_DEVICE_TYPE_CPU:
  17046. case GGML_BACKEND_DEVICE_TYPE_ACCEL:
  17047. // skip CPU backends since they are handled separately
  17048. break;
  17049. case GGML_BACKEND_DEVICE_TYPE_GPU:
  17050. model->devices.push_back(dev);
  17051. break;
  17052. }
  17053. }
  17054. }
  17055. // if using single GPU mode, remove all except the main GPU
  17056. if (params.split_mode == LLAMA_SPLIT_MODE_NONE) {
  17057. if (params.main_gpu < 0 || params.main_gpu >= (int)model->devices.size()) {
  17058. LLAMA_LOG_ERROR("%s: invalid value for main_gpu: %d (available devices: %d)\n", __func__, params.main_gpu, (int)model->devices.size());
  17059. llama_free_model(model);
  17060. return nullptr;
  17061. }
  17062. ggml_backend_dev_t main_gpu = model->devices[params.main_gpu];
  17063. model->devices.clear();
  17064. model->devices.push_back(main_gpu);
  17065. }
  17066. for (auto * dev : model->devices) {
  17067. size_t free, total; // NOLINT
  17068. ggml_backend_dev_memory(dev, &free, &total);
  17069. LLAMA_LOG_INFO("%s: using device %s (%s) - %zu MiB free\n", __func__, ggml_backend_dev_name(dev), ggml_backend_dev_description(dev), free/1024/1024);
  17070. }
  17071. int status = llama_model_load(path_model, *model, params);
  17072. GGML_ASSERT(status <= 0);
  17073. if (status < 0) {
  17074. if (status == -1) {
  17075. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  17076. } else if (status == -2) {
  17077. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  17078. }
  17079. llama_free_model(model);
  17080. return nullptr;
  17081. }
  17082. return model;
  17083. }
  17084. void llama_free_model(struct llama_model * model) {
  17085. delete model;
  17086. }
  17087. struct llama_context * llama_new_context_with_model(
  17088. struct llama_model * model,
  17089. struct llama_context_params params) {
  17090. if (!model) {
  17091. LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
  17092. return nullptr;
  17093. }
  17094. if (params.n_batch == 0 && params.n_ubatch == 0) {
  17095. LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
  17096. return nullptr;
  17097. }
  17098. if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
  17099. LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
  17100. return nullptr;
  17101. }
  17102. if (params.flash_attn && model->arch == LLM_ARCH_GROK) {
  17103. LLAMA_LOG_WARN("%s: flash_attn is not compatible with Grok - forcing off\n", __func__);
  17104. params.flash_attn = false;
  17105. }
  17106. if (params.flash_attn && model->hparams.n_embd_head_k != model->hparams.n_embd_head_v) {
  17107. LLAMA_LOG_WARN("%s: flash_attn requires n_embd_head_k == n_embd_head_v - forcing off\n", __func__);
  17108. params.flash_attn = false;
  17109. }
  17110. if (ggml_is_quantized(params.type_v) && !params.flash_attn) {
  17111. LLAMA_LOG_ERROR("%s: V cache quantization requires flash_attn\n", __func__);
  17112. return nullptr;
  17113. }
  17114. llama_context * ctx = new llama_context(*model);
  17115. const auto & hparams = model->hparams;
  17116. auto & cparams = ctx->cparams;
  17117. cparams.n_seq_max = std::max(1u, params.n_seq_max);
  17118. cparams.n_threads = params.n_threads;
  17119. cparams.n_threads_batch = params.n_threads_batch;
  17120. cparams.yarn_ext_factor = params.yarn_ext_factor;
  17121. cparams.yarn_attn_factor = params.yarn_attn_factor;
  17122. cparams.yarn_beta_fast = params.yarn_beta_fast;
  17123. cparams.yarn_beta_slow = params.yarn_beta_slow;
  17124. cparams.defrag_thold = params.defrag_thold;
  17125. cparams.embeddings = params.embeddings;
  17126. cparams.offload_kqv = params.offload_kqv;
  17127. cparams.flash_attn = params.flash_attn;
  17128. cparams.no_perf = params.no_perf;
  17129. cparams.pooling_type = params.pooling_type;
  17130. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  17131. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  17132. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  17133. // this is necessary due to kv_self.n being padded later during inference
  17134. cparams.n_ctx = GGML_PAD(cparams.n_ctx, llama_kv_cache_get_padding(cparams));
  17135. // with causal attention, the batch size is limited by the context size
  17136. cparams.n_batch = hparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
  17137. // the batch has to be at least GGML_KQ_MASK_PAD because we will be padding the KQ_mask
  17138. // this is required by GPU kernels in order to avoid out-of-bounds accesses (e.g. ggml_flash_attn_ext)
  17139. // ref: https://github.com/ggerganov/llama.cpp/pull/5021
  17140. if (cparams.n_batch < GGML_KQ_MASK_PAD) {
  17141. LLAMA_LOG_WARN("%s: n_batch is less than GGML_KQ_MASK_PAD - increasing to %d\n", __func__, GGML_KQ_MASK_PAD);
  17142. cparams.n_batch = GGML_KQ_MASK_PAD;
  17143. }
  17144. cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
  17145. cparams.n_ctx_orig_yarn = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  17146. hparams.n_ctx_orig_yarn != 0 ? hparams.n_ctx_orig_yarn :
  17147. hparams.n_ctx_train;
  17148. cparams.cb_eval = params.cb_eval;
  17149. cparams.cb_eval_user_data = params.cb_eval_user_data;
  17150. auto rope_scaling_type = params.rope_scaling_type;
  17151. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  17152. rope_scaling_type = hparams.rope_scaling_type_train;
  17153. }
  17154. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  17155. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  17156. }
  17157. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  17158. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  17159. }
  17160. cparams.yarn_attn_factor *= hparams.rope_attn_factor;
  17161. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  17162. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  17163. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  17164. } else {
  17165. cparams.pooling_type = hparams.pooling_type;
  17166. }
  17167. }
  17168. if (params.attention_type == LLAMA_ATTENTION_TYPE_UNSPECIFIED) {
  17169. cparams.causal_attn = hparams.causal_attn;
  17170. } else {
  17171. cparams.causal_attn = params.attention_type == LLAMA_ATTENTION_TYPE_CAUSAL;
  17172. }
  17173. const uint32_t n_ctx_per_seq = cparams.n_ctx / cparams.n_seq_max;
  17174. LLAMA_LOG_INFO("%s: n_seq_max = %u\n", __func__, cparams.n_seq_max);
  17175. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  17176. LLAMA_LOG_INFO("%s: n_ctx_per_seq = %u\n", __func__, n_ctx_per_seq);
  17177. LLAMA_LOG_INFO("%s: n_batch = %u\n", __func__, cparams.n_batch);
  17178. LLAMA_LOG_INFO("%s: n_ubatch = %u\n", __func__, cparams.n_ubatch);
  17179. LLAMA_LOG_INFO("%s: flash_attn = %d\n", __func__, cparams.flash_attn);
  17180. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  17181. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  17182. if (n_ctx_per_seq < hparams.n_ctx_train) {
  17183. LLAMA_LOG_WARN("%s: n_ctx_per_seq (%u) < n_ctx_train (%u) -- the full capacity of the model will not be utilized\n",
  17184. __func__, n_ctx_per_seq, hparams.n_ctx_train);
  17185. }
  17186. if (n_ctx_per_seq > hparams.n_ctx_train) {
  17187. LLAMA_LOG_WARN("%s: n_ctx_pre_seq (%u) > n_ctx_train (%u) -- possible training context overflow\n",
  17188. __func__, n_ctx_per_seq, hparams.n_ctx_train);
  17189. }
  17190. ctx->logits_all = params.logits_all;
  17191. // build worst-case graph for encoder if a model contains encoder
  17192. ctx->is_encoding = llama_model_has_encoder(model);
  17193. uint32_t kv_size = cparams.n_ctx;
  17194. ggml_type type_k = params.type_k;
  17195. ggml_type type_v = params.type_v;
  17196. // Mamba only needs a constant number of KV cache cells per sequence
  17197. if (llama_model_is_recurrent(model)) {
  17198. // Mamba needs at least as many KV cells as there are sequences kept at any time
  17199. kv_size = std::max((uint32_t) 1, params.n_seq_max);
  17200. // it's probably best to keep as much precision as possible for the states
  17201. type_k = GGML_TYPE_F32; // required by ggml_ssm_conv for Mamba's conv_states
  17202. type_v = GGML_TYPE_F32; // required by ggml_ssm_scan for Mamba's ssm_states
  17203. }
  17204. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  17205. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  17206. if (!hparams.vocab_only) {
  17207. // GPU backends
  17208. for (auto * dev : model->devices) {
  17209. ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr);
  17210. if (backend == nullptr) {
  17211. LLAMA_LOG_ERROR("%s: failed to initialize %s backend\n", __func__, ggml_backend_dev_name(dev));
  17212. llama_free(ctx);
  17213. return nullptr;
  17214. }
  17215. ctx->backends.emplace_back(backend);
  17216. }
  17217. // add ACCEL backends (such as BLAS)
  17218. for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
  17219. ggml_backend_dev_t dev = ggml_backend_dev_get(i);
  17220. if (ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_ACCEL) {
  17221. ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr);
  17222. if (backend == nullptr) {
  17223. LLAMA_LOG_ERROR("%s: failed to initialize %s backend\n", __func__, ggml_backend_dev_name(dev));
  17224. llama_free(ctx);
  17225. return nullptr;
  17226. }
  17227. ctx->backends.emplace_back(backend);
  17228. }
  17229. }
  17230. // add CPU backend
  17231. ctx->backend_cpu = ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr);
  17232. if (ctx->backend_cpu == nullptr) {
  17233. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  17234. llama_free(ctx);
  17235. return nullptr;
  17236. }
  17237. ctx->backends.emplace_back(ctx->backend_cpu);
  17238. // create a list of the set_n_threads functions in the backends
  17239. for (auto & backend : ctx->backends) {
  17240. ggml_backend_dev_t dev = ggml_backend_get_device(backend.get());
  17241. ggml_backend_reg_t reg = dev ? ggml_backend_dev_backend_reg(dev) : nullptr;
  17242. if (reg) {
  17243. auto ggml_backend_set_n_threads_fn = (ggml_backend_set_n_threads_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_n_threads");
  17244. if (ggml_backend_set_n_threads_fn) {
  17245. ctx->set_n_threads_fns.emplace_back(backend.get(), ggml_backend_set_n_threads_fn);
  17246. }
  17247. }
  17248. }
  17249. llama_set_abort_callback(ctx, params.abort_callback, params.abort_callback_data);
  17250. if (!llama_kv_cache_init(ctx->kv_self, ctx, type_k, type_v, kv_size, cparams.offload_kqv)) {
  17251. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  17252. llama_free(ctx);
  17253. return nullptr;
  17254. }
  17255. {
  17256. size_t memory_size_k = 0;
  17257. size_t memory_size_v = 0;
  17258. for (auto & k : ctx->kv_self.k_l) {
  17259. memory_size_k += ggml_nbytes(k);
  17260. }
  17261. for (auto & v : ctx->kv_self.v_l) {
  17262. memory_size_v += ggml_nbytes(v);
  17263. }
  17264. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  17265. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  17266. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  17267. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  17268. }
  17269. // graph outputs buffer
  17270. {
  17271. // resized during inference when a batch uses more outputs
  17272. if (llama_output_reserve(*ctx, params.n_seq_max) < params.n_seq_max) {
  17273. LLAMA_LOG_ERROR("%s: failed to reserve initial output buffer\n", __func__);
  17274. llama_free(ctx);
  17275. return nullptr;
  17276. }
  17277. LLAMA_LOG_INFO("%s: %10s output buffer size = %8.2f MiB\n", __func__,
  17278. ggml_backend_buffer_name(ctx->buf_output.get()),
  17279. ggml_backend_buffer_get_size(ctx->buf_output.get()) / 1024.0 / 1024.0);
  17280. }
  17281. // scheduler and compute buffers
  17282. {
  17283. // buffer types used for the compute buffer of each backend
  17284. std::vector<ggml_backend_buffer_type_t> backend_buft;
  17285. std::vector<ggml_backend_t> backend_ptrs;
  17286. for (auto & backend : ctx->backends) {
  17287. auto * buft = ggml_backend_get_default_buffer_type(backend.get());
  17288. auto backend_type = ggml_backend_dev_type(ggml_backend_get_device(backend.get()));
  17289. if (backend_type == GGML_BACKEND_DEVICE_TYPE_CPU && !model->devices.empty()) {
  17290. // use the host buffer of the first device CPU for faster transfer of the intermediate state
  17291. auto * dev = model->devices[0];
  17292. auto * host_buft = ggml_backend_dev_host_buffer_type(dev);
  17293. if (host_buft) {
  17294. buft = host_buft;
  17295. }
  17296. }
  17297. backend_buft.push_back(buft);
  17298. backend_ptrs.push_back(backend.get());
  17299. }
  17300. const size_t max_nodes = llama_model_max_nodes(*model);
  17301. // buffer used to store the computation graph and the tensor meta data
  17302. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*max_nodes + ggml_graph_overhead_custom(max_nodes, false));
  17303. // TODO: move these checks to ggml_backend_sched
  17304. // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
  17305. bool pipeline_parallel =
  17306. llama_get_device_count(*model) > 1 &&
  17307. model->n_gpu_layers > (int)model->hparams.n_layer &&
  17308. model->split_mode == LLAMA_SPLIT_MODE_LAYER &&
  17309. params.offload_kqv;
  17310. // pipeline parallelism requires support for async compute and events in all devices
  17311. if (pipeline_parallel) {
  17312. for (auto & backend : ctx->backends) {
  17313. auto dev_type = ggml_backend_dev_type(ggml_backend_get_device(backend.get()));
  17314. if (dev_type == GGML_BACKEND_DEVICE_TYPE_CPU) {
  17315. // ignore CPU backend
  17316. continue;
  17317. }
  17318. auto * dev = ggml_backend_get_device(backend.get());
  17319. ggml_backend_dev_props props;
  17320. ggml_backend_dev_get_props(dev, &props);
  17321. if (!props.caps.async || !props.caps.events) {
  17322. // device does not support async compute or events
  17323. pipeline_parallel = false;
  17324. break;
  17325. }
  17326. }
  17327. }
  17328. ctx->sched.reset(ggml_backend_sched_new(backend_ptrs.data(), backend_buft.data(), backend_ptrs.size(), max_nodes, pipeline_parallel));
  17329. if (pipeline_parallel) {
  17330. LLAMA_LOG_INFO("%s: pipeline parallelism enabled (n_copies=%d)\n", __func__, ggml_backend_sched_get_n_copies(ctx->sched.get()));
  17331. }
  17332. // initialize scheduler with the worst-case graph
  17333. uint32_t n_seqs = 1; // TODO: worst-case number of sequences
  17334. uint32_t n_tokens = std::min(cparams.n_ctx, cparams.n_ubatch);
  17335. 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
  17336. llama_ubatch ubatch_pp = { true, n_tokens, n_tokens / n_seqs, n_seqs, &token, nullptr, nullptr, nullptr, nullptr, nullptr};
  17337. ggml_cgraph * gf_pp = llama_build_graph(*ctx, ubatch_pp, true);
  17338. // reserve pp graph first so that buffers are only allocated once
  17339. ggml_backend_sched_reserve(ctx->sched.get(), gf_pp);
  17340. int n_splits_pp = ggml_backend_sched_get_n_splits(ctx->sched.get());
  17341. int n_nodes_pp = ggml_graph_n_nodes(gf_pp);
  17342. // reserve with tg graph to get the number of splits and nodes
  17343. llama_ubatch ubatch_tg = { true, 1, 1, n_seqs, &token, nullptr, nullptr, nullptr, nullptr, nullptr};
  17344. ggml_cgraph * gf_tg = llama_build_graph(*ctx, ubatch_tg, true);
  17345. ggml_backend_sched_reserve(ctx->sched.get(), gf_tg);
  17346. int n_splits_tg = ggml_backend_sched_get_n_splits(ctx->sched.get());
  17347. int n_nodes_tg = ggml_graph_n_nodes(gf_tg);
  17348. // reserve again with pp graph to avoid ggml-alloc reallocations during inference
  17349. gf_pp = llama_build_graph(*ctx, ubatch_pp, true);
  17350. if (!ggml_backend_sched_reserve(ctx->sched.get(), gf_pp)) {
  17351. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  17352. llama_free(ctx);
  17353. return nullptr;
  17354. }
  17355. for (size_t i = 0; i < backend_ptrs.size(); ++i) {
  17356. ggml_backend_t backend = backend_ptrs[i];
  17357. ggml_backend_buffer_type_t buft = backend_buft[i];
  17358. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched.get(), backend);
  17359. if (size > 1) {
  17360. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  17361. ggml_backend_buft_name(buft),
  17362. size / 1024.0 / 1024.0);
  17363. }
  17364. }
  17365. if (n_nodes_pp == n_nodes_tg) {
  17366. LLAMA_LOG_INFO("%s: graph nodes = %d\n", __func__, n_nodes_pp);
  17367. } else {
  17368. LLAMA_LOG_INFO("%s: graph nodes = %d (with bs=%d), %d (with bs=1)\n", __func__, n_nodes_pp, n_tokens, n_nodes_tg);
  17369. }
  17370. if (n_splits_pp == n_splits_tg) {
  17371. LLAMA_LOG_INFO("%s: graph splits = %d\n", __func__, n_splits_pp);
  17372. } else {
  17373. LLAMA_LOG_INFO("%s: graph splits = %d (with bs=%d), %d (with bs=1)\n", __func__, n_splits_pp, n_tokens, n_splits_tg);
  17374. }
  17375. }
  17376. }
  17377. return ctx;
  17378. }
  17379. void llama_free(struct llama_context * ctx) {
  17380. delete ctx;
  17381. }
  17382. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  17383. return ctx->cparams.n_ctx;
  17384. }
  17385. uint32_t llama_n_batch(const struct llama_context * ctx) {
  17386. return ctx->cparams.n_batch;
  17387. }
  17388. uint32_t llama_n_ubatch(const struct llama_context * ctx) {
  17389. return ctx->cparams.n_ubatch;
  17390. }
  17391. uint32_t llama_n_seq_max(const struct llama_context * ctx) {
  17392. return ctx->kv_self.size;
  17393. }
  17394. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  17395. return model->vocab.type;
  17396. }
  17397. int32_t llama_n_vocab(const struct llama_model * model) {
  17398. return model->hparams.n_vocab;
  17399. }
  17400. int32_t llama_n_ctx_train(const struct llama_model * model) {
  17401. return model->hparams.n_ctx_train;
  17402. }
  17403. int32_t llama_n_embd(const struct llama_model * model) {
  17404. return model->hparams.n_embd;
  17405. }
  17406. int32_t llama_n_layer(const struct llama_model * model) {
  17407. return model->hparams.n_layer;
  17408. }
  17409. int32_t llama_n_head(const struct llama_model * model) {
  17410. return model->hparams.n_head();
  17411. }
  17412. const struct llama_model * llama_get_model(const struct llama_context * ctx) {
  17413. return &ctx->model;
  17414. }
  17415. enum llama_pooling_type llama_pooling_type(const struct llama_context * ctx) {
  17416. return ctx->cparams.pooling_type;
  17417. }
  17418. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  17419. switch (model->arch) {
  17420. // these models do not use RoPE
  17421. case LLM_ARCH_GPT2:
  17422. case LLM_ARCH_GPTJ:
  17423. case LLM_ARCH_MPT:
  17424. case LLM_ARCH_REFACT:
  17425. case LLM_ARCH_BLOOM:
  17426. case LLM_ARCH_MAMBA:
  17427. case LLM_ARCH_JINA_BERT_V2:
  17428. case LLM_ARCH_T5:
  17429. case LLM_ARCH_T5ENCODER:
  17430. case LLM_ARCH_JAIS:
  17431. case LLM_ARCH_RWKV6:
  17432. return LLAMA_ROPE_TYPE_NONE;
  17433. // use what we call a normal RoPE, operating on pairs of consecutive head values
  17434. case LLM_ARCH_LLAMA:
  17435. case LLM_ARCH_MLLAMA:
  17436. case LLM_ARCH_BAICHUAN:
  17437. case LLM_ARCH_STARCODER:
  17438. case LLM_ARCH_PLAMO:
  17439. case LLM_ARCH_ORION:
  17440. case LLM_ARCH_INTERNLM2:
  17441. case LLM_ARCH_MINICPM:
  17442. case LLM_ARCH_XVERSE:
  17443. case LLM_ARCH_COMMAND_R:
  17444. case LLM_ARCH_OLMO:
  17445. case LLM_ARCH_ARCTIC:
  17446. case LLM_ARCH_DEEPSEEK2:
  17447. case LLM_ARCH_CHATGLM:
  17448. case LLM_ARCH_GRANITE:
  17449. case LLM_ARCH_GRANITE_MOE:
  17450. case LLM_ARCH_CHAMELEON:
  17451. case LLM_ARCH_SOLAR:
  17452. return LLAMA_ROPE_TYPE_NORM;
  17453. // the pairs of head values are offset by n_rot/2
  17454. case LLM_ARCH_FALCON:
  17455. case LLM_ARCH_GROK:
  17456. case LLM_ARCH_DBRX:
  17457. case LLM_ARCH_BERT:
  17458. case LLM_ARCH_NOMIC_BERT:
  17459. case LLM_ARCH_STABLELM:
  17460. case LLM_ARCH_BITNET:
  17461. case LLM_ARCH_QWEN:
  17462. case LLM_ARCH_QWEN2:
  17463. case LLM_ARCH_QWEN2MOE:
  17464. case LLM_ARCH_OLMO2:
  17465. case LLM_ARCH_OLMOE:
  17466. case LLM_ARCH_PHI2:
  17467. case LLM_ARCH_PHI3:
  17468. case LLM_ARCH_GEMMA:
  17469. case LLM_ARCH_GEMMA2:
  17470. case LLM_ARCH_STARCODER2:
  17471. case LLM_ARCH_OPENELM:
  17472. case LLM_ARCH_GPTNEOX:
  17473. case LLM_ARCH_CODESHELL:
  17474. case LLM_ARCH_NEMOTRON:
  17475. case LLM_ARCH_EXAONE:
  17476. case LLM_ARCH_MINICPM3:
  17477. return LLAMA_ROPE_TYPE_NEOX;
  17478. // all model arches should be listed explicitly here
  17479. case LLM_ARCH_UNKNOWN:
  17480. GGML_ABORT("unknown architecture");
  17481. }
  17482. return LLAMA_ROPE_TYPE_NONE;
  17483. }
  17484. float llama_rope_freq_scale_train(const struct llama_model * model) {
  17485. return model->hparams.rope_freq_scale_train;
  17486. }
  17487. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  17488. const auto & it = model->gguf_kv.find(key);
  17489. if (it == model->gguf_kv.end()) {
  17490. if (buf_size > 0) {
  17491. buf[0] = '\0';
  17492. }
  17493. return -1;
  17494. }
  17495. return snprintf(buf, buf_size, "%s", it->second.c_str());
  17496. }
  17497. int32_t llama_model_meta_count(const struct llama_model * model) {
  17498. return (int)model->gguf_kv.size();
  17499. }
  17500. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  17501. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  17502. if (buf_size > 0) {
  17503. buf[0] = '\0';
  17504. }
  17505. return -1;
  17506. }
  17507. auto it = model->gguf_kv.begin();
  17508. std::advance(it, i);
  17509. return snprintf(buf, buf_size, "%s", it->first.c_str());
  17510. }
  17511. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  17512. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  17513. if (buf_size > 0) {
  17514. buf[0] = '\0';
  17515. }
  17516. return -1;
  17517. }
  17518. auto it = model->gguf_kv.begin();
  17519. std::advance(it, i);
  17520. return snprintf(buf, buf_size, "%s", it->second.c_str());
  17521. }
  17522. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  17523. return snprintf(buf, buf_size, "%s %s %s",
  17524. llama_model_arch_name(model->arch),
  17525. llama_model_type_name(model->type),
  17526. llama_model_ftype_name(model->ftype).c_str());
  17527. }
  17528. uint64_t llama_model_size(const struct llama_model * model) {
  17529. return model->n_bytes;
  17530. }
  17531. uint64_t llama_model_n_params(const struct llama_model * model) {
  17532. return model->n_elements;
  17533. }
  17534. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  17535. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  17536. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  17537. return it.first == name;
  17538. });
  17539. if (it == model->tensors_by_name.end()) {
  17540. return nullptr;
  17541. }
  17542. return it->second;
  17543. }
  17544. bool llama_model_has_encoder(const struct llama_model * model) {
  17545. switch (model->arch) {
  17546. case LLM_ARCH_T5: return true;
  17547. case LLM_ARCH_T5ENCODER: return true;
  17548. default: return false;
  17549. }
  17550. }
  17551. bool llama_model_has_decoder(const struct llama_model * model) {
  17552. switch (model->arch) {
  17553. case LLM_ARCH_T5ENCODER: return false;
  17554. default: return true;
  17555. }
  17556. }
  17557. llama_token llama_model_decoder_start_token(const struct llama_model * model) {
  17558. return model->hparams.dec_start_token_id;
  17559. }
  17560. bool llama_model_is_recurrent(const struct llama_model * model) {
  17561. switch (model->arch) {
  17562. case LLM_ARCH_MAMBA: return true;
  17563. case LLM_ARCH_RWKV6: return true;
  17564. default: return false;
  17565. }
  17566. }
  17567. uint32_t llama_model_quantize(
  17568. const char * fname_inp,
  17569. const char * fname_out,
  17570. const llama_model_quantize_params * params) {
  17571. try {
  17572. llama_model_quantize_internal(fname_inp, fname_out, params);
  17573. return 0;
  17574. } catch (const std::exception & err) {
  17575. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  17576. return 1;
  17577. }
  17578. }
  17579. struct llama_lora_adapter * llama_lora_adapter_init(struct llama_model * model, const char * path_lora) {
  17580. try {
  17581. struct llama_lora_adapter * adapter = new llama_lora_adapter(model);
  17582. llama_lora_adapter_init_internal(model, path_lora, *adapter);
  17583. return adapter;
  17584. } catch (const std::exception & err) {
  17585. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  17586. return nullptr;
  17587. }
  17588. }
  17589. static bool llama_control_vector_init(struct llama_control_vector & cvec, const llama_model & model) {
  17590. GGML_ASSERT(cvec.tensors.empty());
  17591. GGML_ASSERT(cvec.ctxs.empty());
  17592. GGML_ASSERT(cvec.bufs.empty());
  17593. // create a context for each buffer type
  17594. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  17595. auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
  17596. auto it = ctx_map.find(buft);
  17597. if (it == ctx_map.end()) {
  17598. struct ggml_init_params params = {
  17599. /*.mem_size =*/ model.hparams.n_layer*ggml_tensor_overhead(),
  17600. /*.mem_buffer =*/ NULL,
  17601. /*.no_alloc =*/ true,
  17602. };
  17603. ggml_context * ctx = ggml_init(params);
  17604. if (!ctx) {
  17605. return nullptr;
  17606. }
  17607. ctx_map[buft] = ctx;
  17608. cvec.ctxs.emplace_back(ctx);
  17609. return ctx;
  17610. }
  17611. return it->second;
  17612. };
  17613. // make tensors
  17614. cvec.tensors.reserve(model.hparams.n_layer);
  17615. cvec.tensors.push_back(nullptr); // there's never a tensor for layer 0
  17616. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  17617. ggml_backend_buffer_type_t buft = select_buft(*model.dev_layer.at(il).buft_list,
  17618. [&](ggml_context * ctx) {
  17619. ggml_tensor * cur = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_embd);
  17620. ggml_tensor * layer_dir = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_embd);
  17621. return ggml_add(ctx, cur, layer_dir);
  17622. });
  17623. ggml_context * ctx = ctx_for_buft(buft);
  17624. if (!ctx) {
  17625. LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
  17626. return false;
  17627. }
  17628. ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_embd);
  17629. cvec.tensors.push_back(tensor);
  17630. }
  17631. // allocate tensors / buffers and zero
  17632. cvec.bufs.reserve(ctx_map.size());
  17633. for (auto it : ctx_map) {
  17634. ggml_backend_buffer_type_t buft = it.first;
  17635. ggml_context * ctx = it.second;
  17636. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  17637. if (!buf) {
  17638. LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
  17639. return false;
  17640. }
  17641. ggml_backend_buffer_clear(buf, 0);
  17642. cvec.bufs.emplace_back(buf);
  17643. }
  17644. return true;
  17645. }
  17646. int32_t llama_control_vector_apply(struct llama_context * lctx, const float * data, size_t len, int32_t n_embd, int32_t il_start, int32_t il_end) {
  17647. const llama_model & model = lctx->model;
  17648. llama_control_vector & cvec = lctx->cvec;
  17649. if (data == nullptr) {
  17650. // disable the current control vector (but leave allocated for later)
  17651. cvec.layer_start = -1;
  17652. cvec.layer_end = -1;
  17653. return 0;
  17654. }
  17655. if (n_embd != (int) model.hparams.n_embd) {
  17656. LLAMA_LOG_ERROR("%s: control vector n_embd does not match model\n", __func__);
  17657. return 1;
  17658. }
  17659. if (cvec.tensors.empty()) {
  17660. if (!llama_control_vector_init(cvec, model)) {
  17661. return 1;
  17662. }
  17663. }
  17664. cvec.layer_start = il_start;
  17665. cvec.layer_end = il_end;
  17666. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  17667. assert(cvec.tensors[il] != nullptr);
  17668. const size_t off = n_embd * (il - 1); // buffer doesn't have data for layer 0, since it's never present
  17669. if (off + n_embd <= len) {
  17670. ggml_backend_tensor_set(cvec.tensors[il], data + off, 0, n_embd * ggml_element_size(cvec.tensors[il]));
  17671. }
  17672. }
  17673. return 0;
  17674. }
  17675. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_seq_max) {
  17676. struct llama_kv_cache_view result = {
  17677. /*.n_cells = */ 0,
  17678. /*.n_seq_max = */ n_seq_max,
  17679. /*.token_count = */ 0,
  17680. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  17681. /*.max_contiguous = */ 0,
  17682. /*.max_contiguous_idx = */ -1,
  17683. /*.cells = */ nullptr,
  17684. /*.cells_sequences = */ nullptr,
  17685. };
  17686. return result;
  17687. }
  17688. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  17689. if (view->cells != nullptr) {
  17690. free(view->cells);
  17691. view->cells = nullptr;
  17692. }
  17693. if (view->cells_sequences != nullptr) {
  17694. free(view->cells_sequences);
  17695. view->cells_sequences = nullptr;
  17696. }
  17697. }
  17698. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  17699. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  17700. view->n_cells = int32_t(ctx->kv_self.size);
  17701. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  17702. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  17703. view->cells = (struct llama_kv_cache_view_cell *)p;
  17704. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_seq_max * view->n_cells);
  17705. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  17706. view->cells_sequences = (llama_seq_id *)p;
  17707. }
  17708. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  17709. llama_kv_cache_view_cell * c_curr = view->cells;
  17710. llama_seq_id * cs_curr = view->cells_sequences;
  17711. int32_t used_cells = 0;
  17712. int32_t token_count = 0;
  17713. int32_t curr_contig_idx = -1;
  17714. uint32_t max_contig = 0;
  17715. int32_t max_contig_idx = -1;
  17716. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_seq_max) {
  17717. const size_t curr_size = kv_cells[i].seq_id.size();
  17718. token_count += curr_size;
  17719. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  17720. if (curr_size > 0) {
  17721. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  17722. max_contig = i - curr_contig_idx;
  17723. max_contig_idx = curr_contig_idx;
  17724. }
  17725. curr_contig_idx = -1;
  17726. } else if (curr_contig_idx < 0) {
  17727. curr_contig_idx = i;
  17728. }
  17729. int seq_idx = 0;
  17730. for (const llama_seq_id it : kv_cells[i].seq_id) {
  17731. if (seq_idx >= view->n_seq_max) {
  17732. break;
  17733. }
  17734. cs_curr[seq_idx] = it;
  17735. seq_idx++;
  17736. }
  17737. if (seq_idx != 0) {
  17738. used_cells++;
  17739. }
  17740. for (; seq_idx < view->n_seq_max; seq_idx++) {
  17741. cs_curr[seq_idx] = -1;
  17742. }
  17743. }
  17744. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  17745. max_contig_idx = curr_contig_idx;
  17746. max_contig = kv_cells.size() - curr_contig_idx;
  17747. }
  17748. view->max_contiguous = max_contig;
  17749. view->max_contiguous_idx = max_contig_idx;
  17750. view->token_count = token_count;
  17751. view->used_cells = used_cells;
  17752. if (uint32_t(used_cells) != ctx->kv_self.used) {
  17753. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  17754. __func__, ctx->kv_self.used, used_cells);
  17755. }
  17756. }
  17757. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  17758. int result = 0;
  17759. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  17760. result += ctx->kv_self.cells[i].seq_id.size();
  17761. }
  17762. return result;
  17763. }
  17764. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  17765. return ctx->kv_self.used;
  17766. }
  17767. void llama_kv_cache_clear(struct llama_context * ctx) {
  17768. llama_kv_cache_clear(ctx->kv_self);
  17769. }
  17770. bool llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  17771. return llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  17772. }
  17773. 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) {
  17774. if (seq_id_src == seq_id_dst) {
  17775. return;
  17776. }
  17777. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  17778. }
  17779. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  17780. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  17781. }
  17782. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  17783. if (delta == 0) {
  17784. return;
  17785. }
  17786. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  17787. }
  17788. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  17789. if (d == 1) {
  17790. return;
  17791. }
  17792. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  17793. }
  17794. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  17795. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  17796. }
  17797. void llama_kv_cache_defrag(struct llama_context * ctx) {
  17798. llama_kv_cache_defrag(ctx->kv_self);
  17799. }
  17800. void llama_kv_cache_update(struct llama_context * ctx) {
  17801. llama_kv_cache_update_internal(*ctx);
  17802. }
  17803. bool llama_kv_cache_can_shift(struct llama_context * ctx) {
  17804. return !ctx->kv_self.recurrent && ctx->model.arch != LLM_ARCH_DEEPSEEK2; // not supported due to MLA
  17805. }
  17806. // deprecated
  17807. size_t llama_get_state_size(struct llama_context * ctx) {
  17808. return llama_state_get_size(ctx);
  17809. }
  17810. // deprecated
  17811. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  17812. return llama_state_get_data(ctx, dst, -1);
  17813. }
  17814. // deprecated
  17815. size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
  17816. return llama_state_set_data(ctx, src, -1);
  17817. }
  17818. // deprecated
  17819. 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) {
  17820. return llama_state_load_file(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  17821. }
  17822. // deprecated
  17823. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  17824. return llama_state_save_file(ctx, path_session, tokens, n_token_count);
  17825. }
  17826. // TODO: replace all non-fatal assertions with returned errors or exceptions
  17827. struct llama_data_write {
  17828. virtual void write(const void * src, size_t size) = 0;
  17829. virtual void write_tensor_data(const struct ggml_tensor * tensor, size_t offset, size_t size) = 0;
  17830. virtual size_t get_size_written() = 0;
  17831. virtual ~llama_data_write() = default;
  17832. void write_string(const std::string & str) {
  17833. uint32_t str_size = str.size();
  17834. write(&str_size, sizeof(str_size));
  17835. write(str.data(), str_size);
  17836. }
  17837. void write_model_info(const struct llama_context * ctx) {
  17838. std::string arch_str = LLM_ARCH_NAMES.at(ctx->model.arch);
  17839. write_string(arch_str);
  17840. // TODO: add more model-specific info which should prevent loading the session file if not identical
  17841. }
  17842. //void write_rng(const std::mt19937 & rng) {
  17843. // std::ostringstream rng_ss;
  17844. // rng_ss << rng;
  17845. // const std::string & rng_str = rng_ss.str();
  17846. // write_string(rng_str);
  17847. //}
  17848. void write_output_ids(struct llama_context * ctx) {
  17849. llama_output_reorder(ctx);
  17850. const uint32_t n_outputs = ctx->n_outputs;
  17851. std::vector<int32_t> output_pos;
  17852. const size_t n_batch = ctx->cparams.n_batch;
  17853. const auto & output_ids = ctx->output_ids;
  17854. GGML_ASSERT(n_outputs <= ctx->output_size);
  17855. output_pos.resize(n_outputs);
  17856. // build a more compact representation of the output ids
  17857. for (size_t i = 0; i < n_batch; ++i) {
  17858. // map an output id to a position in the batch
  17859. int32_t pos = output_ids[i];
  17860. if (pos >= 0) {
  17861. GGML_ASSERT((uint32_t) pos < n_outputs);
  17862. output_pos[pos] = i;
  17863. }
  17864. }
  17865. write(&n_outputs, sizeof(n_outputs));
  17866. if (n_outputs) {
  17867. write(output_pos.data(), n_outputs * sizeof(int32_t));
  17868. }
  17869. }
  17870. void write_logits(const struct llama_context * ctx) {
  17871. const uint64_t logits_size = std::min((uint64_t) ctx->logits_size, (uint64_t) ctx->n_outputs * ctx->model.hparams.n_vocab);
  17872. write(&logits_size, sizeof(logits_size));
  17873. if (logits_size) {
  17874. write(ctx->logits, logits_size * sizeof(float));
  17875. }
  17876. }
  17877. void write_embeddings(const struct llama_context * ctx) {
  17878. const uint64_t embeddings_size = std::min((uint64_t) ctx->embd_size, (uint64_t) ctx->n_outputs * ctx->model.hparams.n_embd);
  17879. write(&embeddings_size, sizeof(embeddings_size));
  17880. if (embeddings_size) {
  17881. write(ctx->embd, embeddings_size * sizeof(float));
  17882. }
  17883. }
  17884. void write_kv_cache_meta(const llama_kv_cache & kv_self, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges, llama_seq_id seq_id = -1) {
  17885. for (const auto & range : cell_ranges) {
  17886. for (uint32_t i = range.first; i < range.second; ++i) {
  17887. const auto & cell = kv_self.cells[i];
  17888. const llama_pos pos = cell.pos;
  17889. const uint32_t n_seq_id = seq_id == -1 ? cell.seq_id.size() : 0;
  17890. write(&pos, sizeof(pos));
  17891. write(&n_seq_id, sizeof(n_seq_id));
  17892. if (n_seq_id) {
  17893. for (auto seq_id : cell.seq_id) {
  17894. write(&seq_id, sizeof(seq_id));
  17895. }
  17896. }
  17897. }
  17898. }
  17899. }
  17900. void write_kv_cache_data(const struct llama_context * ctx, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges) {
  17901. const struct llama_kv_cache & kv_self = ctx->kv_self;
  17902. const struct llama_hparams & hparams = ctx->model.hparams;
  17903. const uint32_t v_trans = kv_self.v_trans ? 1 : 0;
  17904. const uint32_t n_layer = hparams.n_layer;
  17905. write(&v_trans, sizeof(v_trans));
  17906. write(&n_layer, sizeof(n_layer));
  17907. std::vector<uint8_t> tmp_buf;
  17908. // Iterate and write all the keys first, each row is a cell
  17909. // Get whole range at a time
  17910. for (uint32_t il = 0; il < n_layer; ++il) {
  17911. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  17912. // Write key type
  17913. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  17914. write(&k_type_i, sizeof(k_type_i));
  17915. // Write row size of key
  17916. const uint64_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  17917. write(&k_size_row, sizeof(k_size_row));
  17918. // Read each range of cells of k_size length each into tmp_buf and write out
  17919. for (const auto & range : cell_ranges) {
  17920. const size_t range_size = range.second - range.first;
  17921. const size_t buf_size = range_size * k_size_row;
  17922. write_tensor_data(kv_self.k_l[il], range.first * k_size_row, buf_size);
  17923. }
  17924. }
  17925. if (!kv_self.v_trans) {
  17926. for (uint32_t il = 0; il < n_layer; ++il) {
  17927. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  17928. // Write value type
  17929. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  17930. write(&v_type_i, sizeof(v_type_i));
  17931. // Write row size of value
  17932. const uint64_t v_size_row = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa);
  17933. write(&v_size_row, sizeof(v_size_row));
  17934. // Read each range of cells of v_size length each into tmp_buf and write out
  17935. for (const auto & range : cell_ranges) {
  17936. const size_t range_size = range.second - range.first;
  17937. const size_t buf_size = range_size * v_size_row;
  17938. write_tensor_data(kv_self.v_l[il], range.first * v_size_row, buf_size);
  17939. }
  17940. }
  17941. } else {
  17942. // When v is transposed, we also need the element size and get the element ranges from each row
  17943. const uint32_t kv_size = kv_self.size;
  17944. for (uint32_t il = 0; il < n_layer; ++il) {
  17945. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  17946. // Write value type
  17947. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  17948. write(&v_type_i, sizeof(v_type_i));
  17949. // Write element size
  17950. const uint32_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  17951. write(&v_size_el, sizeof(v_size_el));
  17952. // Write GQA embedding size
  17953. write(&n_embd_v_gqa, sizeof(n_embd_v_gqa));
  17954. // For each row, we get the element values of each cell
  17955. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  17956. // Read each range of cells of v_size_el length each into tmp_buf and write out
  17957. for (const auto & range : cell_ranges) {
  17958. const size_t range_size = range.second - range.first;
  17959. const size_t src_offset = (range.first + j * kv_size) * v_size_el;
  17960. const size_t buf_size = range_size * v_size_el;
  17961. write_tensor_data(kv_self.v_l[il], src_offset, buf_size);
  17962. }
  17963. }
  17964. }
  17965. }
  17966. }
  17967. void write_kv_cache(const struct llama_context * ctx, llama_seq_id seq_id = -1) {
  17968. const struct llama_kv_cache & kv_self = ctx->kv_self;
  17969. std::vector<std::pair<uint32_t, uint32_t>> cell_ranges; // ranges, from inclusive, to exclusive
  17970. uint32_t cell_count = 0;
  17971. // Count the number of cells with the specified seq_id
  17972. // Find all the ranges of cells with this seq id (or all, when -1)
  17973. uint32_t cell_range_begin = kv_self.size;
  17974. for (uint32_t i = 0; i < kv_self.size; ++i) {
  17975. const auto & cell = kv_self.cells[i];
  17976. if ((seq_id == -1 && !cell.is_empty()) || cell.has_seq_id(seq_id)) {
  17977. ++cell_count;
  17978. if (cell_range_begin == kv_self.size) {
  17979. cell_range_begin = i;
  17980. }
  17981. } else {
  17982. if (cell_range_begin != kv_self.size) {
  17983. cell_ranges.emplace_back(cell_range_begin, i);
  17984. cell_range_begin = kv_self.size;
  17985. }
  17986. }
  17987. }
  17988. if (cell_range_begin != kv_self.size) {
  17989. cell_ranges.emplace_back(cell_range_begin, kv_self.size);
  17990. }
  17991. // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
  17992. uint32_t cell_count_check = 0;
  17993. for (const auto & range : cell_ranges) {
  17994. cell_count_check += range.second - range.first;
  17995. }
  17996. GGML_ASSERT(cell_count == cell_count_check);
  17997. write(&cell_count, sizeof(cell_count));
  17998. write_kv_cache_meta(kv_self, cell_ranges, seq_id);
  17999. write_kv_cache_data(ctx, cell_ranges);
  18000. }
  18001. };
  18002. struct llama_data_read {
  18003. virtual const uint8_t * read(size_t size) = 0;
  18004. virtual void read_to(void * dst, size_t size) = 0;
  18005. virtual size_t get_size_read() = 0;
  18006. virtual ~llama_data_read() = default;
  18007. void read_string(std::string & str) {
  18008. uint32_t str_size;
  18009. read_to(&str_size, sizeof(str_size));
  18010. str.assign((const char *) read(str_size), str_size);
  18011. }
  18012. // validate model information
  18013. void read_model_info(const struct llama_context * ctx) {
  18014. std::string cur_arch_str = LLM_ARCH_NAMES.at(ctx->model.arch);
  18015. std::string arch_str;
  18016. read_string(arch_str);
  18017. if (cur_arch_str != arch_str) {
  18018. throw std::runtime_error(format("wrong model arch: '%s' instead of '%s'", arch_str.c_str(), cur_arch_str.c_str()));
  18019. }
  18020. // TODO: add more info which needs to be identical but which is not verified otherwise
  18021. }
  18022. //void read_rng(std::mt19937 & rng) {
  18023. // std::string rng_str;
  18024. // read_string(rng_str);
  18025. // std::istringstream rng_ss(rng_str);
  18026. // rng_ss >> rng;
  18027. // if (rng_ss.fail()) {
  18028. // throw std::runtime_error("failed to load RNG state");
  18029. // }
  18030. //}
  18031. void read_output_ids(struct llama_context * ctx) {
  18032. std::vector<int32_t> output_pos;
  18033. uint32_t n_outputs;
  18034. read_to(&n_outputs, sizeof(n_outputs));
  18035. if (n_outputs > llama_output_reserve(*ctx, n_outputs)) {
  18036. throw std::runtime_error("could not reserve outputs");
  18037. }
  18038. if (n_outputs) {
  18039. output_pos.resize(n_outputs);
  18040. read_to(output_pos.data(), n_outputs * sizeof(int32_t));
  18041. for (int32_t i = 0; i < (int32_t) output_pos.size(); ++i) {
  18042. int32_t id = output_pos[i];
  18043. if ((uint32_t) id >= ctx->cparams.n_batch) {
  18044. throw std::runtime_error(format("invalid output id, %d does not fit in batch size of %u", id, ctx->cparams.n_batch));
  18045. }
  18046. ctx->output_ids[id] = i;
  18047. }
  18048. ctx->n_outputs = n_outputs;
  18049. }
  18050. }
  18051. void read_logits(struct llama_context * ctx) {
  18052. uint64_t logits_size;
  18053. read_to(&logits_size, sizeof(logits_size));
  18054. if (ctx->logits_size < logits_size) {
  18055. throw std::runtime_error("logits buffer too small");
  18056. }
  18057. if (logits_size) {
  18058. read_to(ctx->logits, logits_size * sizeof(float));
  18059. }
  18060. }
  18061. void read_embeddings(struct llama_context * ctx) {
  18062. uint64_t embeddings_size;
  18063. read_to(&embeddings_size, sizeof(embeddings_size));
  18064. if (ctx->embd_size < embeddings_size) {
  18065. throw std::runtime_error("embeddings buffer too small");
  18066. }
  18067. if (embeddings_size) {
  18068. read_to(ctx->embd, embeddings_size * sizeof(float));
  18069. }
  18070. }
  18071. bool read_kv_cache_meta(struct llama_context * ctx, uint32_t cell_count, llama_seq_id dest_seq_id = -1) {
  18072. struct llama_kv_cache & kv_self = ctx->kv_self;
  18073. if (dest_seq_id != -1) {
  18074. // single sequence
  18075. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  18076. llama_ubatch batch = ctx->sbatch.reserve_ubatch(cell_count, /* has_embd */ false);
  18077. batch.n_tokens = cell_count;
  18078. batch.n_seq_tokens = cell_count;
  18079. batch.n_seqs = 1;
  18080. for (uint32_t i = 0; i < cell_count; ++i) {
  18081. llama_pos pos;
  18082. uint32_t n_seq_id;
  18083. read_to(&pos, sizeof(pos));
  18084. read_to(&n_seq_id, sizeof(n_seq_id));
  18085. if (n_seq_id != 0) {
  18086. LLAMA_LOG_ERROR("%s: invalid seq_id-agnostic kv cell\n", __func__);
  18087. return false;
  18088. }
  18089. batch.pos[i] = pos;
  18090. }
  18091. batch.n_seq_id[0] = 1;
  18092. batch.seq_id[0] = &dest_seq_id;
  18093. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  18094. LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
  18095. return false;
  18096. }
  18097. // DEBUG CHECK: kv_self.head should be our first cell, kv_self.head + cell_count - 1 should be our last cell (verify seq_id and pos values)
  18098. // Assume that this is one contiguous block of cells
  18099. GGML_ASSERT(kv_self.head + cell_count <= kv_self.size);
  18100. GGML_ASSERT(kv_self.cells[kv_self.head].pos == batch.pos[0]);
  18101. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].pos == batch.pos[cell_count - 1]);
  18102. GGML_ASSERT(kv_self.cells[kv_self.head].has_seq_id(dest_seq_id));
  18103. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].has_seq_id(dest_seq_id));
  18104. } else {
  18105. // whole KV cache restore
  18106. if (cell_count > kv_self.size) {
  18107. LLAMA_LOG_ERROR("%s: not enough cells in kv cache\n", __func__);
  18108. return false;
  18109. }
  18110. llama_kv_cache_clear(kv_self);
  18111. for (uint32_t i = 0; i < cell_count; ++i) {
  18112. llama_kv_cell & cell = kv_self.cells[i];
  18113. llama_pos pos;
  18114. uint32_t n_seq_id;
  18115. read_to(&pos, sizeof(pos));
  18116. read_to(&n_seq_id, sizeof(n_seq_id));
  18117. cell.pos = pos;
  18118. for (uint32_t j = 0; j < n_seq_id; ++j) {
  18119. llama_seq_id seq_id;
  18120. read_to(&seq_id, sizeof(seq_id));
  18121. if (seq_id < 0 || (uint32_t) seq_id >= llama_n_seq_max(ctx)) {
  18122. LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, %u)\n", __func__, seq_id, llama_n_seq_max(ctx));
  18123. return false;
  18124. }
  18125. cell.seq_id.insert(seq_id);
  18126. if (kv_self.recurrent) {
  18127. int32_t & tail = kv_self.cells[seq_id].tail;
  18128. if (tail != -1) {
  18129. LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tail);
  18130. return false;
  18131. }
  18132. tail = i;
  18133. }
  18134. }
  18135. }
  18136. kv_self.head = 0;
  18137. kv_self.used = cell_count;
  18138. }
  18139. if (kv_self.recurrent) {
  18140. for (uint32_t i = 0; i < cell_count; ++i) {
  18141. uint32_t cell_id = kv_self.head + i;
  18142. // make sure the recurrent states will keep their restored state
  18143. kv_self.cells[cell_id].src = cell_id;
  18144. }
  18145. }
  18146. return true;
  18147. }
  18148. bool read_kv_cache_data(struct llama_context * ctx, uint32_t cell_count) {
  18149. const struct llama_hparams & hparams = ctx->model.hparams;
  18150. struct llama_kv_cache & kv_self = ctx->kv_self;
  18151. uint32_t v_trans;
  18152. uint32_t n_layer;
  18153. read_to(&v_trans, sizeof(v_trans));
  18154. read_to(&n_layer, sizeof(n_layer));
  18155. if (n_layer != hparams.n_layer) {
  18156. LLAMA_LOG_ERROR("%s: mismatched layer count (%u instead of %u)\n", __func__, n_layer, hparams.n_layer);
  18157. return false;
  18158. }
  18159. if (cell_count > kv_self.size) {
  18160. LLAMA_LOG_ERROR("%s: not enough cells in kv cache to restore state (%u > %u)\n", __func__, cell_count, kv_self.size);
  18161. return false;
  18162. }
  18163. if (kv_self.v_trans != (bool) v_trans) {
  18164. LLAMA_LOG_ERROR("%s: incompatible V transposition\n", __func__);
  18165. return false;
  18166. }
  18167. // For each layer, read the keys for each cell, one row is one cell, read as one contiguous block
  18168. for (uint32_t il = 0; il < n_layer; ++il) {
  18169. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  18170. // Read type of key
  18171. int32_t k_type_i_ref;
  18172. read_to(&k_type_i_ref, sizeof(k_type_i_ref));
  18173. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  18174. if (k_type_i != k_type_i_ref) {
  18175. LLAMA_LOG_ERROR("%s: mismatched key type (%d != %d, layer %d)\n", __func__, k_type_i, k_type_i_ref, il);
  18176. return false;
  18177. }
  18178. // Read row size of key
  18179. uint64_t k_size_row_ref;
  18180. read_to(&k_size_row_ref, sizeof(k_size_row_ref));
  18181. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  18182. if (k_size_row != k_size_row_ref) {
  18183. LLAMA_LOG_ERROR("%s: mismatched key row size (%zu != %zu, layer %d)\n", __func__, k_size_row, (size_t) k_size_row_ref, il);
  18184. return false;
  18185. }
  18186. if (cell_count) {
  18187. // Read and set the keys for the whole cell range
  18188. ggml_backend_tensor_set(kv_self.k_l[il], read(cell_count * k_size_row), kv_self.head * k_size_row, cell_count * k_size_row);
  18189. }
  18190. }
  18191. if (!kv_self.v_trans) {
  18192. for (uint32_t il = 0; il < n_layer; ++il) {
  18193. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  18194. // Read type of value
  18195. int32_t v_type_i_ref;
  18196. read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  18197. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  18198. if (v_type_i != v_type_i_ref) {
  18199. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  18200. return false;
  18201. }
  18202. // Read row size of value
  18203. uint64_t v_size_row_ref;
  18204. read_to(&v_size_row_ref, sizeof(v_size_row_ref));
  18205. const size_t v_size_row = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa);
  18206. if (v_size_row != v_size_row_ref) {
  18207. LLAMA_LOG_ERROR("%s: mismatched value row size (%zu != %zu, layer %d)\n", __func__, v_size_row, (size_t) v_size_row_ref, il);
  18208. return false;
  18209. }
  18210. if (cell_count) {
  18211. // Read and set the values for the whole cell range
  18212. ggml_backend_tensor_set(kv_self.v_l[il], read(cell_count * v_size_row), kv_self.head * v_size_row, cell_count * v_size_row);
  18213. }
  18214. }
  18215. } else {
  18216. // For each layer, read the values for each cell (transposed)
  18217. for (uint32_t il = 0; il < n_layer; ++il) {
  18218. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  18219. // Read type of value
  18220. int32_t v_type_i_ref;
  18221. read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  18222. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  18223. if (v_type_i != v_type_i_ref) {
  18224. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  18225. return false;
  18226. }
  18227. // Read element size of value
  18228. uint32_t v_size_el_ref;
  18229. read_to(&v_size_el_ref, sizeof(v_size_el_ref));
  18230. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  18231. if (v_size_el != v_size_el_ref) {
  18232. LLAMA_LOG_ERROR("%s: mismatched value element size (%zu != %zu, layer %d)\n", __func__, v_size_el, (size_t) v_size_el_ref, il);
  18233. return false;
  18234. }
  18235. // Read GQA embedding size
  18236. uint32_t n_embd_v_gqa_ref;
  18237. read_to(&n_embd_v_gqa_ref, sizeof(n_embd_v_gqa_ref));
  18238. if (n_embd_v_gqa != n_embd_v_gqa_ref) {
  18239. LLAMA_LOG_ERROR("%s: mismatched GQA embedding size (%u != %u, layer %d)\n", __func__, n_embd_v_gqa, n_embd_v_gqa_ref, il);
  18240. return false;
  18241. }
  18242. if (cell_count) {
  18243. // For each row in the transposed matrix, read the values for the whole cell range
  18244. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  18245. const size_t dst_offset = (kv_self.head + j * kv_self.size) * v_size_el;
  18246. ggml_backend_tensor_set(kv_self.v_l[il], read(cell_count * v_size_el), dst_offset, cell_count * v_size_el);
  18247. }
  18248. }
  18249. }
  18250. }
  18251. return true;
  18252. }
  18253. void read_kv_cache(struct llama_context * ctx, llama_seq_id seq_id = -1) {
  18254. uint32_t cell_count;
  18255. read_to(&cell_count, sizeof(cell_count));
  18256. bool res = read_kv_cache_meta(ctx, cell_count, seq_id) && read_kv_cache_data(ctx, cell_count);
  18257. if (!res) {
  18258. if (seq_id == -1) {
  18259. llama_kv_cache_clear(ctx);
  18260. } else {
  18261. llama_kv_cache_seq_rm(ctx, seq_id, -1, -1);
  18262. }
  18263. throw std::runtime_error("failed to restore kv cache");
  18264. }
  18265. }
  18266. };
  18267. struct llama_data_write_dummy : llama_data_write {
  18268. size_t size_written = 0;
  18269. llama_data_write_dummy() {}
  18270. void write(const void * /* src */, size_t size) override {
  18271. size_written += size;
  18272. }
  18273. void write_tensor_data(const struct ggml_tensor * /* tensor */, size_t /* offset */, size_t size) override {
  18274. size_written += size;
  18275. }
  18276. size_t get_size_written() override {
  18277. return size_written;
  18278. }
  18279. };
  18280. struct llama_data_write_buffer : llama_data_write {
  18281. uint8_t * ptr;
  18282. size_t buf_size = 0;
  18283. size_t size_written = 0;
  18284. llama_data_write_buffer(uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
  18285. void write(const void * src, size_t size) override {
  18286. if (size > buf_size) {
  18287. throw std::runtime_error("unexpectedly reached end of buffer");
  18288. }
  18289. memcpy(ptr, src, size);
  18290. ptr += size;
  18291. size_written += size;
  18292. buf_size -= size;
  18293. }
  18294. void write_tensor_data(const struct ggml_tensor * tensor, size_t offset, size_t size) override {
  18295. if (size > buf_size) {
  18296. throw std::runtime_error("unexpectedly reached end of buffer");
  18297. }
  18298. ggml_backend_tensor_get(tensor, ptr, offset, size);
  18299. ptr += size;
  18300. size_written += size;
  18301. buf_size -= size;
  18302. }
  18303. size_t get_size_written() override {
  18304. return size_written;
  18305. }
  18306. };
  18307. struct llama_data_read_buffer : llama_data_read {
  18308. const uint8_t * ptr;
  18309. size_t buf_size = 0;
  18310. size_t size_read = 0;
  18311. llama_data_read_buffer(const uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
  18312. const uint8_t * read(size_t size) override {
  18313. const uint8_t * base_ptr = ptr;
  18314. if (size > buf_size) {
  18315. throw std::runtime_error("unexpectedly reached end of buffer");
  18316. }
  18317. ptr += size;
  18318. size_read += size;
  18319. buf_size -= size;
  18320. return base_ptr;
  18321. }
  18322. void read_to(void * dst, size_t size) override {
  18323. memcpy(dst, read(size), size);
  18324. }
  18325. size_t get_size_read() override {
  18326. return size_read;
  18327. }
  18328. };
  18329. struct llama_data_write_file : llama_data_write {
  18330. llama_file * file;
  18331. size_t size_written = 0;
  18332. std::vector<uint8_t> temp_buffer;
  18333. llama_data_write_file(llama_file * f) : file(f) {}
  18334. void write(const void * src, size_t size) override {
  18335. file->write_raw(src, size);
  18336. size_written += size;
  18337. }
  18338. void write_tensor_data(const struct ggml_tensor * tensor, size_t offset, size_t size) override {
  18339. temp_buffer.resize(size);
  18340. ggml_backend_tensor_get(tensor, temp_buffer.data(), offset, size);
  18341. write(temp_buffer.data(), temp_buffer.size());
  18342. }
  18343. size_t get_size_written() override {
  18344. return size_written;
  18345. }
  18346. };
  18347. struct llama_data_read_file : llama_data_read {
  18348. llama_file * file;
  18349. size_t size_read = 0;
  18350. std::vector<uint8_t> temp_buffer;
  18351. llama_data_read_file(llama_file * f) : file(f) {}
  18352. void read_to(void * dst, size_t size) override {
  18353. file->read_raw(dst, size);
  18354. size_read += size;
  18355. }
  18356. const uint8_t * read(size_t size) override {
  18357. temp_buffer.resize(size);
  18358. read_to(temp_buffer.data(), size);
  18359. return temp_buffer.data();
  18360. }
  18361. size_t get_size_read() override {
  18362. return size_read;
  18363. }
  18364. };
  18365. /** copy state data into either a buffer or file depending on the passed in context
  18366. *
  18367. * file context:
  18368. * llama_file file("/path", "wb");
  18369. * llama_data_write_file data_ctx(&file);
  18370. * llama_state_get_data_internal(ctx, data_ctx);
  18371. *
  18372. * buffer context:
  18373. * std::vector<uint8_t> buf(max_size, 0);
  18374. * llama_data_write_buffer data_ctx(buf.data(), max_size);
  18375. * llama_state_get_data_internal(ctx, data_ctx);
  18376. *
  18377. */
  18378. static size_t llama_state_get_data_internal(struct llama_context * ctx, llama_data_write & data_ctx) {
  18379. llama_synchronize(ctx);
  18380. data_ctx.write_model_info(ctx);
  18381. // copy outputs
  18382. data_ctx.write_output_ids(ctx);
  18383. data_ctx.write_logits(ctx);
  18384. data_ctx.write_embeddings(ctx);
  18385. data_ctx.write_kv_cache(ctx);
  18386. return data_ctx.get_size_written();
  18387. }
  18388. size_t llama_state_get_data(struct llama_context * ctx, uint8_t * dst, size_t size) {
  18389. llama_data_write_buffer data_ctx(dst, size);
  18390. try {
  18391. return llama_state_get_data_internal(ctx, data_ctx);
  18392. } catch (const std::exception & err) {
  18393. LLAMA_LOG_ERROR("%s: error saving state: %s\n", __func__, err.what());
  18394. return 0;
  18395. }
  18396. }
  18397. // Returns the *actual* size of the state.
  18398. // Intended to be used when saving to state to a buffer.
  18399. size_t llama_state_get_size(struct llama_context * ctx) {
  18400. llama_data_write_dummy data_ctx;
  18401. try {
  18402. return llama_state_get_data_internal(ctx, data_ctx);
  18403. } catch (const std::exception & err) {
  18404. LLAMA_LOG_ERROR("%s: error getting state size: %s\n", __func__, err.what());
  18405. return 0;
  18406. }
  18407. }
  18408. static size_t llama_state_set_data_internal(struct llama_context * ctx, llama_data_read & data_ctx) {
  18409. llama_synchronize(ctx);
  18410. data_ctx.read_model_info(ctx);
  18411. // set outputs
  18412. data_ctx.read_output_ids(ctx);
  18413. data_ctx.read_logits(ctx);
  18414. data_ctx.read_embeddings(ctx);
  18415. data_ctx.read_kv_cache(ctx);
  18416. return data_ctx.get_size_read();
  18417. }
  18418. // Sets the state reading from the specified source address
  18419. size_t llama_state_set_data(struct llama_context * ctx, const uint8_t * src, size_t size) {
  18420. llama_data_read_buffer data_ctx(src, size);
  18421. try {
  18422. return llama_state_set_data_internal(ctx, data_ctx);
  18423. } catch (const std::exception & err) {
  18424. LLAMA_LOG_ERROR("%s: error loading state: %s\n", __func__, err.what());
  18425. return 0;
  18426. }
  18427. }
  18428. static bool llama_state_load_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) {
  18429. llama_file file(path_session, "rb");
  18430. // sanity checks
  18431. {
  18432. const uint32_t magic = file.read_u32();
  18433. const uint32_t version = file.read_u32();
  18434. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  18435. LLAMA_LOG_ERROR("%s: unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  18436. return false;
  18437. }
  18438. }
  18439. // load the prompt
  18440. {
  18441. const uint32_t n_token_count = file.read_u32();
  18442. if (n_token_count > n_token_capacity) {
  18443. LLAMA_LOG_ERROR("%s: token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  18444. return false;
  18445. }
  18446. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  18447. *n_token_count_out = n_token_count;
  18448. }
  18449. // restore the context state
  18450. {
  18451. const size_t n_state_size_cur = file.size - file.tell();
  18452. llama_data_read_file data_ctx(&file);
  18453. const size_t n_read = llama_state_set_data_internal(ctx, data_ctx);
  18454. if (n_read != n_state_size_cur) {
  18455. LLAMA_LOG_ERROR("%s: did not read all of the session file data! size %zu, got %zu\n", __func__, n_state_size_cur, n_read);
  18456. return false;
  18457. }
  18458. }
  18459. return true;
  18460. }
  18461. bool llama_state_load_file(struct llama_context * ctx, const char * path_session, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
  18462. try {
  18463. return llama_state_load_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  18464. } catch (const std::exception & err) {
  18465. LLAMA_LOG_ERROR("%s: error loading session file: %s\n", __func__, err.what());
  18466. return false;
  18467. }
  18468. }
  18469. static bool llama_state_save_file_internal(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  18470. llama_file file(path_session, "wb");
  18471. file.write_u32(LLAMA_SESSION_MAGIC);
  18472. file.write_u32(LLAMA_SESSION_VERSION);
  18473. // save the prompt
  18474. file.write_u32((uint32_t) n_token_count);
  18475. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  18476. // save the context state using stream saving
  18477. llama_data_write_file data_ctx(&file);
  18478. llama_state_get_data_internal(ctx, data_ctx);
  18479. return true;
  18480. }
  18481. bool llama_state_save_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  18482. try {
  18483. return llama_state_save_file_internal(ctx, path_session, tokens, n_token_count);
  18484. } catch (const std::exception & err) {
  18485. LLAMA_LOG_ERROR("%s: error saving session file: %s\n", __func__, err.what());
  18486. return false;
  18487. }
  18488. }
  18489. static size_t llama_state_seq_get_data_internal(struct llama_context * ctx, llama_data_write & data_ctx, llama_seq_id seq_id) {
  18490. llama_synchronize(ctx);
  18491. data_ctx.write_kv_cache(ctx, seq_id);
  18492. return data_ctx.get_size_written();
  18493. }
  18494. size_t llama_state_seq_get_size(struct llama_context * ctx, llama_seq_id seq_id) {
  18495. llama_data_write_dummy data_ctx;
  18496. return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  18497. }
  18498. size_t llama_state_seq_get_data(struct llama_context * ctx, uint8_t * dst, size_t size, llama_seq_id seq_id) {
  18499. llama_data_write_buffer data_ctx(dst, size);
  18500. try {
  18501. return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  18502. } catch (const std::exception & err) {
  18503. LLAMA_LOG_ERROR("%s: error saving sequence state: %s\n", __func__, err.what());
  18504. return 0;
  18505. }
  18506. }
  18507. static size_t llama_state_seq_set_data_internal(struct llama_context * ctx, llama_data_read & data_ctx, llama_seq_id dest_seq_id) {
  18508. llama_synchronize(ctx);
  18509. data_ctx.read_kv_cache(ctx, dest_seq_id);
  18510. return data_ctx.get_size_read();
  18511. }
  18512. size_t llama_state_seq_set_data(struct llama_context * ctx, const uint8_t * src, size_t size, llama_seq_id dest_seq_id) {
  18513. llama_data_read_buffer data_ctx(src, size);
  18514. try {
  18515. return llama_state_seq_set_data_internal(ctx, data_ctx, dest_seq_id);
  18516. } catch (const std::exception & err) {
  18517. LLAMA_LOG_ERROR("%s: error loading sequence state: %s\n", __func__, err.what());
  18518. return 0;
  18519. }
  18520. }
  18521. static size_t llama_state_seq_save_file_internal(struct llama_context * ctx, const char * filepath, llama_seq_id seq_id, const llama_token * tokens, size_t n_token_count) {
  18522. llama_file file(filepath, "wb");
  18523. file.write_u32(LLAMA_STATE_SEQ_MAGIC);
  18524. file.write_u32(LLAMA_STATE_SEQ_VERSION);
  18525. // save the prompt
  18526. file.write_u32((uint32_t) n_token_count);
  18527. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  18528. // save the context state using stream saving
  18529. llama_data_write_file data_ctx(&file);
  18530. llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  18531. const size_t res = file.tell();
  18532. GGML_ASSERT(res == sizeof(uint32_t) * 3 + sizeof(llama_token) * n_token_count + data_ctx.get_size_written());
  18533. return res;
  18534. }
  18535. static size_t llama_state_seq_load_file_internal(struct llama_context * ctx, const char * filepath, llama_seq_id dest_seq_id, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
  18536. llama_file file(filepath, "rb");
  18537. // version checks
  18538. {
  18539. const uint32_t magic = file.read_u32();
  18540. const uint32_t version = file.read_u32();
  18541. if (magic != LLAMA_STATE_SEQ_MAGIC || version != LLAMA_STATE_SEQ_VERSION) {
  18542. LLAMA_LOG_ERROR("%s: unknown (magic, version) for sequence state file: %08x, %08x\n", __func__, magic, version);
  18543. return 0;
  18544. }
  18545. }
  18546. // load the prompt
  18547. {
  18548. const uint32_t n_token_count = file.read_u32();
  18549. if (n_token_count > n_token_capacity) {
  18550. LLAMA_LOG_ERROR("%s: token count in sequence state file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  18551. return 0;
  18552. }
  18553. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  18554. *n_token_count_out = n_token_count;
  18555. }
  18556. // restore the context state
  18557. {
  18558. const size_t state_size = file.size - file.tell();
  18559. llama_data_read_file data_ctx(&file);
  18560. const size_t nread = llama_state_seq_set_data_internal(ctx, data_ctx, dest_seq_id);
  18561. if (!nread) {
  18562. LLAMA_LOG_ERROR("%s: failed to restore sequence state\n", __func__);
  18563. return 0;
  18564. }
  18565. GGML_ASSERT(nread <= state_size);
  18566. GGML_ASSERT(nread + sizeof(uint32_t) * 3 + sizeof(llama_token) * *n_token_count_out == file.tell());
  18567. }
  18568. return file.tell();
  18569. }
  18570. size_t llama_state_seq_save_file(struct llama_context * ctx, const char * filepath, llama_seq_id seq_id, const llama_token * tokens, size_t n_token_count) {
  18571. try {
  18572. return llama_state_seq_save_file_internal(ctx, filepath, seq_id, tokens, n_token_count);
  18573. } catch (const std::exception & err) {
  18574. LLAMA_LOG_ERROR("%s: error saving sequence state file: %s\n", __func__, err.what());
  18575. return 0;
  18576. }
  18577. }
  18578. size_t llama_state_seq_load_file(struct llama_context * ctx, const char * filepath, llama_seq_id dest_seq_id, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
  18579. try {
  18580. return llama_state_seq_load_file_internal(ctx, filepath, dest_seq_id, tokens_out, n_token_capacity, n_token_count_out);
  18581. } catch (const std::exception & err) {
  18582. LLAMA_LOG_ERROR("%s: error loading sequence state file: %s\n", __func__, err.what());
  18583. return 0;
  18584. }
  18585. }
  18586. void llama_set_n_threads(struct llama_context * ctx, int32_t n_threads, int32_t n_threads_batch) {
  18587. ctx->cparams.n_threads = n_threads;
  18588. ctx->cparams.n_threads_batch = n_threads_batch;
  18589. }
  18590. int32_t llama_n_threads(struct llama_context * ctx) {
  18591. return ctx->cparams.n_threads;
  18592. }
  18593. int32_t llama_n_threads_batch(struct llama_context * ctx) {
  18594. return ctx->cparams.n_threads_batch;
  18595. }
  18596. void llama_set_abort_callback(struct llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
  18597. ctx->abort_callback = abort_callback;
  18598. ctx->abort_callback_data = abort_callback_data;
  18599. for (auto & backend : ctx->backends) {
  18600. auto * reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(backend.get()));
  18601. auto * set_abort_callback_fn = (ggml_backend_set_abort_callback_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_abort_callback");
  18602. if (set_abort_callback_fn) {
  18603. set_abort_callback_fn(backend.get(), ctx->abort_callback, ctx->abort_callback_data);
  18604. }
  18605. }
  18606. }
  18607. void llama_set_embeddings(struct llama_context * ctx, bool embeddings) {
  18608. ctx->cparams.embeddings = embeddings;
  18609. }
  18610. void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn) {
  18611. ctx->cparams.causal_attn = causal_attn;
  18612. }
  18613. void llama_set_cross_attention(struct llama_context * ctx, bool cross_attention) {
  18614. ctx->cparams.cross_attn = cross_attention;
  18615. }
  18616. struct llama_batch llama_batch_get_one(
  18617. llama_token * tokens,
  18618. int32_t n_tokens) {
  18619. return {
  18620. /*n_tokens =*/ n_tokens,
  18621. /*tokens =*/ tokens,
  18622. /*embd =*/ nullptr,
  18623. /*n_embd =*/ 0,
  18624. /*pos =*/ nullptr,
  18625. /*n_seq_id =*/ nullptr,
  18626. /*seq_id =*/ nullptr,
  18627. /*logits =*/ nullptr,
  18628. };
  18629. }
  18630. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  18631. llama_batch batch = {
  18632. /*n_tokens =*/ 0,
  18633. /*tokens =*/ nullptr,
  18634. /*embd =*/ nullptr,
  18635. /*n_embd =*/ 0,
  18636. /*pos =*/ nullptr,
  18637. /*n_seq_id =*/ nullptr,
  18638. /*seq_id =*/ nullptr,
  18639. /*logits =*/ nullptr,
  18640. };
  18641. if (embd) {
  18642. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  18643. batch.n_embd = embd;
  18644. } else {
  18645. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  18646. }
  18647. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  18648. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  18649. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  18650. for (int i = 0; i < n_tokens_alloc; ++i) {
  18651. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  18652. }
  18653. batch.seq_id[n_tokens_alloc] = nullptr;
  18654. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  18655. return batch;
  18656. }
  18657. void llama_batch_free(struct llama_batch batch) {
  18658. if (batch.token) free(batch.token);
  18659. if (batch.embd) free(batch.embd);
  18660. if (batch.pos) free(batch.pos);
  18661. if (batch.n_seq_id) free(batch.n_seq_id);
  18662. if (batch.seq_id) {
  18663. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  18664. free(batch.seq_id[i]);
  18665. }
  18666. free(batch.seq_id);
  18667. }
  18668. if (batch.logits) free(batch.logits);
  18669. }
  18670. int32_t llama_encode(
  18671. struct llama_context * ctx,
  18672. struct llama_batch batch) {
  18673. const int ret = llama_encode_internal(*ctx, batch);
  18674. if (ret != 0) {
  18675. LLAMA_LOG_ERROR("%s: failed to encode, ret = %d\n", __func__, ret);
  18676. }
  18677. return ret;
  18678. }
  18679. int32_t llama_decode(
  18680. struct llama_context * ctx,
  18681. struct llama_batch batch) {
  18682. const int ret = llama_decode_internal(*ctx, batch);
  18683. if (ret != 0) {
  18684. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  18685. }
  18686. return ret;
  18687. }
  18688. void llama_synchronize(struct llama_context * ctx) {
  18689. ggml_backend_sched_synchronize(ctx->sched.get());
  18690. // FIXME: if multiple single tokens are evaluated without a synchronization,
  18691. // the stats will be added to the prompt evaluation stats
  18692. // this should only happen when using batch size 1 to evaluate a batch
  18693. // add the evaluation to the stats
  18694. if (ctx->n_queued_tokens == 1) {
  18695. if (!ctx->cparams.no_perf) {
  18696. ctx->t_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  18697. }
  18698. ctx->n_eval++;
  18699. } else if (ctx->n_queued_tokens > 1) {
  18700. if (!ctx->cparams.no_perf) {
  18701. ctx->t_p_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  18702. }
  18703. ctx->n_p_eval += ctx->n_queued_tokens;
  18704. }
  18705. // get a more accurate load time, upon first eval
  18706. if (ctx->n_queued_tokens > 0 && !ctx->has_evaluated_once) {
  18707. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  18708. ctx->has_evaluated_once = true;
  18709. }
  18710. ctx->n_queued_tokens = 0;
  18711. ctx->t_compute_start_us = 0;
  18712. }
  18713. float * llama_get_logits(struct llama_context * ctx) {
  18714. llama_synchronize(ctx);
  18715. // reorder logits for backward compatibility
  18716. // TODO: maybe deprecate this
  18717. llama_output_reorder(ctx);
  18718. return ctx->logits;
  18719. }
  18720. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  18721. int32_t j = -1;
  18722. llama_synchronize(ctx);
  18723. try {
  18724. if (ctx->logits == nullptr) {
  18725. throw std::runtime_error("no logits");
  18726. }
  18727. if (i < 0) {
  18728. j = ctx->n_outputs + i;
  18729. if (j < 0) {
  18730. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  18731. }
  18732. } else if ((size_t) i >= ctx->output_ids.size()) {
  18733. throw std::runtime_error(format("out of range [0, %zu)", ctx->output_ids.size()));
  18734. } else {
  18735. j = ctx->output_ids[i];
  18736. }
  18737. if (j < 0) {
  18738. throw std::runtime_error(format("batch.logits[%d] != true", i));
  18739. }
  18740. if (j >= ctx->n_outputs) {
  18741. // This should not happen
  18742. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  18743. }
  18744. return ctx->logits + j*ctx->model.hparams.n_vocab;
  18745. } catch (const std::exception & err) {
  18746. LLAMA_LOG_ERROR("%s: invalid logits id %d, reason: %s\n", __func__, i, err.what());
  18747. #ifndef NDEBUG
  18748. GGML_ABORT("fatal error");
  18749. #else
  18750. return nullptr;
  18751. #endif
  18752. }
  18753. }
  18754. float * llama_get_embeddings(struct llama_context * ctx) {
  18755. llama_synchronize(ctx);
  18756. // reorder embeddings for backward compatibility
  18757. // TODO: maybe deprecate this
  18758. llama_output_reorder(ctx);
  18759. return ctx->embd;
  18760. }
  18761. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  18762. int32_t j = -1;
  18763. llama_synchronize(ctx);
  18764. try {
  18765. if (ctx->embd == nullptr) {
  18766. throw std::runtime_error("no embeddings");
  18767. }
  18768. if (i < 0) {
  18769. j = ctx->n_outputs + i;
  18770. if (j < 0) {
  18771. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  18772. }
  18773. } else if ((size_t) i >= ctx->output_ids.size()) {
  18774. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  18775. } else {
  18776. j = ctx->output_ids[i];
  18777. }
  18778. if (j < 0) {
  18779. throw std::runtime_error(format("batch.logits[%d] != true", i));
  18780. }
  18781. if (j >= ctx->n_outputs) {
  18782. // This should not happen
  18783. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  18784. }
  18785. return ctx->embd + j*ctx->model.hparams.n_embd;
  18786. } catch (const std::exception & err) {
  18787. LLAMA_LOG_ERROR("%s: invalid embeddings id %d, reason: %s\n", __func__, i, err.what());
  18788. #ifndef NDEBUG
  18789. GGML_ABORT("fatal error");
  18790. #else
  18791. return nullptr;
  18792. #endif
  18793. }
  18794. }
  18795. float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id) {
  18796. llama_synchronize(ctx);
  18797. auto it = ctx->embd_seq.find(seq_id);
  18798. if (it == ctx->embd_seq.end()) {
  18799. return nullptr;
  18800. }
  18801. return it->second.data();
  18802. }
  18803. //
  18804. // vocab
  18805. //
  18806. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  18807. return llama_token_get_text_impl(model->vocab, token);
  18808. }
  18809. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  18810. return llama_token_get_score_impl(model->vocab, token);
  18811. }
  18812. enum llama_token_attr llama_token_get_attr(const struct llama_model * model, llama_token token) {
  18813. return llama_token_get_attr_impl(model->vocab, token);
  18814. }
  18815. bool llama_token_is_eog(const struct llama_model * model, llama_token token) {
  18816. return llama_token_is_eog_impl(model->vocab, token);
  18817. }
  18818. bool llama_token_is_control(const struct llama_model * model, llama_token token) {
  18819. return llama_token_is_control_impl(model->vocab, token);
  18820. }
  18821. llama_token llama_token_bos(const struct llama_model * model) {
  18822. return llama_token_bos_impl(model->vocab);
  18823. }
  18824. llama_token llama_token_eos(const struct llama_model * model) {
  18825. return llama_token_eos_impl(model->vocab);
  18826. }
  18827. llama_token llama_token_eot(const struct llama_model * model) {
  18828. return llama_token_eot_impl(model->vocab);
  18829. }
  18830. llama_token llama_token_cls(const struct llama_model * model) {
  18831. return llama_token_cls_impl(model->vocab);
  18832. }
  18833. llama_token llama_token_sep(const struct llama_model * model) {
  18834. return llama_token_sep_impl(model->vocab);
  18835. }
  18836. llama_token llama_token_nl (const struct llama_model * model) {
  18837. return llama_token_nl_impl(model->vocab);
  18838. }
  18839. llama_token llama_token_pad(const struct llama_model * model) {
  18840. return llama_token_pad_impl(model->vocab);
  18841. }
  18842. bool llama_add_bos_token(const struct llama_model * model) {
  18843. return llama_add_bos_token_impl(model->vocab);
  18844. }
  18845. bool llama_add_eos_token(const struct llama_model * model) {
  18846. return llama_add_eos_token_impl(model->vocab);
  18847. }
  18848. llama_token llama_token_prefix(const struct llama_model * model) {
  18849. return llama_token_prefix_impl(model->vocab);
  18850. }
  18851. llama_token llama_token_middle(const struct llama_model * model) {
  18852. return llama_token_middle_impl(model->vocab);
  18853. }
  18854. llama_token llama_token_suffix(const struct llama_model * model) {
  18855. return llama_token_suffix_impl(model->vocab);
  18856. }
  18857. llama_token llama_token_fim_pre(const struct llama_model * model) {
  18858. return llama_token_fim_pre_impl(model->vocab);
  18859. }
  18860. llama_token llama_token_fim_suf(const struct llama_model * model) {
  18861. return llama_token_fim_suf_impl(model->vocab);
  18862. }
  18863. llama_token llama_token_fim_mid(const struct llama_model * model) {
  18864. return llama_token_fim_mid_impl(model->vocab);
  18865. }
  18866. llama_token llama_token_fim_pad(const struct llama_model * model) {
  18867. return llama_token_fim_pad_impl(model->vocab);
  18868. }
  18869. llama_token llama_token_fim_rep(const struct llama_model * model) {
  18870. return llama_token_fim_rep_impl(model->vocab);
  18871. }
  18872. llama_token llama_token_fim_sep(const struct llama_model * model) {
  18873. return llama_token_fim_sep_impl(model->vocab);
  18874. }
  18875. //
  18876. // tokenization
  18877. //
  18878. int32_t llama_tokenize(
  18879. const struct llama_model * model,
  18880. const char * text,
  18881. int32_t text_len,
  18882. llama_token * tokens,
  18883. int32_t n_tokens_max,
  18884. bool add_special,
  18885. bool parse_special) {
  18886. return llama_tokenize_impl(model->vocab, text, text_len, tokens, n_tokens_max, add_special, parse_special);
  18887. }
  18888. int32_t llama_token_to_piece(
  18889. const struct llama_model * model,
  18890. llama_token token,
  18891. char * buf,
  18892. int32_t length,
  18893. int32_t lstrip,
  18894. bool special) {
  18895. return llama_token_to_piece_impl(model->vocab, token, buf, length, lstrip, special);
  18896. }
  18897. int32_t llama_detokenize(
  18898. const struct llama_model * model,
  18899. const llama_token * tokens,
  18900. int32_t n_tokens,
  18901. char * text,
  18902. int32_t text_len_max,
  18903. bool remove_special,
  18904. bool unparse_special) {
  18905. return llama_detokenize_impl(model->vocab, tokens, n_tokens, text, text_len_max, remove_special, unparse_special);
  18906. }
  18907. //
  18908. // chat templates
  18909. //
  18910. static llm_chat_template llama_chat_detect_template(const std::string & tmpl) {
  18911. if (LLM_CHAT_TEMPLATES.find(tmpl) != LLM_CHAT_TEMPLATES.end()) {
  18912. return LLM_CHAT_TEMPLATES.at(tmpl);
  18913. }
  18914. auto tmpl_contains = [&tmpl](const char * haystack) -> bool {
  18915. return tmpl.find(haystack) != std::string::npos;
  18916. };
  18917. if (tmpl_contains("<|im_start|>")) {
  18918. return LLM_CHAT_TEMPLATE_CHATML;
  18919. } else if (tmpl.find("mistral") == 0 || tmpl_contains("[INST]")) {
  18920. if (tmpl_contains("[SYSTEM_PROMPT]")) {
  18921. return LLM_CHAT_TEMPLATE_MISTRAL_V7;
  18922. } else if (
  18923. // catches official 'v1' template
  18924. tmpl_contains("' [INST] ' + system_message")
  18925. // catches official 'v3' and 'v3-tekken' templates
  18926. || tmpl_contains("[AVAILABLE_TOOLS]")
  18927. ) {
  18928. // Official mistral 'v1', 'v3' and 'v3-tekken' templates
  18929. // See: https://github.com/mistralai/cookbook/blob/main/concept-deep-dive/tokenization/chat_templates.md
  18930. // See: https://github.com/mistralai/cookbook/blob/main/concept-deep-dive/tokenization/templates.md
  18931. if (tmpl_contains(" [INST]")) {
  18932. return LLM_CHAT_TEMPLATE_MISTRAL_V1;
  18933. } else if (tmpl_contains("\"[INST]\"")) {
  18934. return LLM_CHAT_TEMPLATE_MISTRAL_V3_TEKKEN;
  18935. }
  18936. return LLM_CHAT_TEMPLATE_MISTRAL_V3;
  18937. } else {
  18938. // llama2 template and its variants
  18939. // [variant] support system message
  18940. // See: https://huggingface.co/blog/llama2#how-to-prompt-llama-2
  18941. bool support_system_message = tmpl_contains("<<SYS>>");
  18942. bool add_bos_inside_history = tmpl_contains("bos_token + '[INST]");
  18943. bool strip_message = tmpl_contains("content.strip()");
  18944. if (strip_message) {
  18945. return LLM_CHAT_TEMPLATE_LLAMA_2_SYS_STRIP;
  18946. } else if (add_bos_inside_history) {
  18947. return LLM_CHAT_TEMPLATE_LLAMA_2_SYS_BOS;
  18948. } else if (support_system_message) {
  18949. return LLM_CHAT_TEMPLATE_LLAMA_2_SYS;
  18950. } else {
  18951. return LLM_CHAT_TEMPLATE_LLAMA_2;
  18952. }
  18953. }
  18954. } else if (tmpl_contains("<|assistant|>") && tmpl_contains("<|end|>")) {
  18955. return LLM_CHAT_TEMPLATE_PHI_3;
  18956. } else if (tmpl_contains("<|user|>") && tmpl_contains("<|endoftext|>")) {
  18957. return LLM_CHAT_TEMPLATE_ZEPHYR;
  18958. } else if (tmpl_contains("bos_token + message['role']")) {
  18959. return LLM_CHAT_TEMPLATE_MONARCH;
  18960. } else if (tmpl_contains("<start_of_turn>")) {
  18961. return LLM_CHAT_TEMPLATE_GEMMA;
  18962. } else if (tmpl_contains("'\\n\\nAssistant: ' + eos_token")) {
  18963. // OrionStarAI/Orion-14B-Chat
  18964. return LLM_CHAT_TEMPLATE_ORION;
  18965. } else if (tmpl_contains("GPT4 Correct ")) {
  18966. // openchat/openchat-3.5-0106
  18967. return LLM_CHAT_TEMPLATE_OPENCHAT;
  18968. } else if (tmpl_contains("USER: ") && tmpl_contains("ASSISTANT: ")) {
  18969. // eachadea/vicuna-13b-1.1 (and Orca variant)
  18970. if (tmpl_contains("SYSTEM: ")) {
  18971. return LLM_CHAT_TEMPLATE_VICUNA_ORCA;
  18972. }
  18973. return LLM_CHAT_TEMPLATE_VICUNA;
  18974. } else if (tmpl_contains("### Instruction:") && tmpl_contains("<|EOT|>")) {
  18975. // deepseek-ai/deepseek-coder-33b-instruct
  18976. return LLM_CHAT_TEMPLATE_DEEPSEEK;
  18977. } else if (tmpl_contains("<|START_OF_TURN_TOKEN|>") && tmpl_contains("<|USER_TOKEN|>")) {
  18978. // CohereForAI/c4ai-command-r-plus
  18979. return LLM_CHAT_TEMPLATE_COMMAND_R;
  18980. } else if (tmpl_contains("<|start_header_id|>") && tmpl_contains("<|end_header_id|>")) {
  18981. return LLM_CHAT_TEMPLATE_LLAMA_3;
  18982. } else if (tmpl_contains("[gMASK]sop")) {
  18983. // chatglm3-6b
  18984. return LLM_CHAT_TEMPLATE_CHATGML_3;
  18985. } else if (tmpl_contains("[gMASK]<sop>")) {
  18986. return LLM_CHAT_TEMPLATE_CHATGML_4;
  18987. } else if (tmpl_contains(LU8("<用户>"))) {
  18988. // MiniCPM-3B-OpenHermes-2.5-v2-GGUF
  18989. return LLM_CHAT_TEMPLATE_MINICPM;
  18990. } else if (tmpl_contains("'Assistant: ' + message['content'] + eos_token")) {
  18991. return LLM_CHAT_TEMPLATE_DEEPSEEK_2;
  18992. } else if (tmpl_contains("[|system|]") && tmpl_contains("[|assistant|]") && tmpl_contains("[|endofturn|]")) {
  18993. // ref: https://huggingface.co/LGAI-EXAONE/EXAONE-3.0-7.8B-Instruct/discussions/8#66bae61b1893d14ee8ed85bb
  18994. // EXAONE-3.0-7.8B-Instruct
  18995. return LLM_CHAT_TEMPLATE_EXAONE_3;
  18996. } else if (tmpl_contains("rwkv-world")) {
  18997. return LLM_CHAT_TEMPLATE_RWKV_WORLD;
  18998. } else if (tmpl_contains("<|start_of_role|>")) {
  18999. return LLM_CHAT_TEMPLATE_GRANITE;
  19000. }
  19001. return LLM_CHAT_TEMPLATE_UNKNOWN;
  19002. }
  19003. // Simple version of "llama_apply_chat_template" that only works with strings
  19004. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  19005. static int32_t llama_chat_apply_template_internal(
  19006. const llm_chat_template tmpl,
  19007. const std::vector<const llama_chat_message *> & chat,
  19008. std::string & dest, bool add_ass) {
  19009. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  19010. std::stringstream ss;
  19011. if (tmpl == LLM_CHAT_TEMPLATE_CHATML) {
  19012. // chatml template
  19013. for (auto message : chat) {
  19014. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  19015. }
  19016. if (add_ass) {
  19017. ss << "<|im_start|>assistant\n";
  19018. }
  19019. } else if (tmpl == LLM_CHAT_TEMPLATE_MISTRAL_V7) {
  19020. // Official mistral 'v7' template
  19021. // See: https://huggingface.co/mistralai/Mistral-Large-Instruct-2411#basic-instruct-template-v7
  19022. for (auto message : chat) {
  19023. std::string role(message->role);
  19024. std::string content(message->content);
  19025. if (role == "system") {
  19026. ss << "[SYSTEM_PROMPT] " << content << "[/SYSTEM_PROMPT]";
  19027. } else if (role == "user") {
  19028. ss << "[INST] " << content << "[/INST]";
  19029. }
  19030. else {
  19031. ss << " " << content << "</s>";
  19032. }
  19033. }
  19034. } else if (tmpl == LLM_CHAT_TEMPLATE_MISTRAL_V1
  19035. || tmpl == LLM_CHAT_TEMPLATE_MISTRAL_V3
  19036. || tmpl == LLM_CHAT_TEMPLATE_MISTRAL_V3_TEKKEN) {
  19037. // See: https://github.com/mistralai/cookbook/blob/main/concept-deep-dive/tokenization/chat_templates.md
  19038. // See: https://github.com/mistralai/cookbook/blob/main/concept-deep-dive/tokenization/templates.md
  19039. std::string leading_space = tmpl == LLM_CHAT_TEMPLATE_MISTRAL_V1 ? " " : "";
  19040. std::string trailing_space = tmpl == LLM_CHAT_TEMPLATE_MISTRAL_V3_TEKKEN ? "" : " ";
  19041. bool trim_assistant_message = tmpl == LLM_CHAT_TEMPLATE_MISTRAL_V3;
  19042. bool is_inside_turn = false;
  19043. for (auto message : chat) {
  19044. if (!is_inside_turn) {
  19045. ss << leading_space << "[INST]" << trailing_space;
  19046. is_inside_turn = true;
  19047. }
  19048. std::string role(message->role);
  19049. std::string content(message->content);
  19050. if (role == "system") {
  19051. ss << content << "\n\n";
  19052. } else if (role == "user") {
  19053. ss << content << leading_space << "[/INST]";
  19054. } else {
  19055. ss << trailing_space << (trim_assistant_message ? trim(content) : content) << "</s>";
  19056. is_inside_turn = false;
  19057. }
  19058. }
  19059. } else if (
  19060. tmpl == LLM_CHAT_TEMPLATE_LLAMA_2
  19061. || tmpl == LLM_CHAT_TEMPLATE_LLAMA_2_SYS
  19062. || tmpl == LLM_CHAT_TEMPLATE_LLAMA_2_SYS_BOS
  19063. || tmpl == LLM_CHAT_TEMPLATE_LLAMA_2_SYS_STRIP) {
  19064. // llama2 template and its variants
  19065. // [variant] support system message
  19066. // See: https://huggingface.co/blog/llama2#how-to-prompt-llama-2
  19067. bool support_system_message = tmpl != LLM_CHAT_TEMPLATE_LLAMA_2;
  19068. // [variant] add BOS inside history
  19069. bool add_bos_inside_history = tmpl == LLM_CHAT_TEMPLATE_LLAMA_2_SYS_BOS;
  19070. // [variant] trim spaces from the input message
  19071. bool strip_message = tmpl == LLM_CHAT_TEMPLATE_LLAMA_2_SYS_STRIP;
  19072. // construct the prompt
  19073. bool is_inside_turn = true; // skip BOS at the beginning
  19074. ss << "[INST] ";
  19075. for (auto message : chat) {
  19076. std::string content = strip_message ? trim(message->content) : message->content;
  19077. std::string role(message->role);
  19078. if (!is_inside_turn) {
  19079. is_inside_turn = true;
  19080. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  19081. }
  19082. if (role == "system") {
  19083. if (support_system_message) {
  19084. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  19085. } else {
  19086. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  19087. ss << content << "\n";
  19088. }
  19089. } else if (role == "user") {
  19090. ss << content << " [/INST]";
  19091. } else {
  19092. ss << content << "</s>";
  19093. is_inside_turn = false;
  19094. }
  19095. }
  19096. } else if (tmpl == LLM_CHAT_TEMPLATE_PHI_3) {
  19097. // Phi 3
  19098. for (auto message : chat) {
  19099. std::string role(message->role);
  19100. ss << "<|" << role << "|>\n" << message->content << "<|end|>\n";
  19101. }
  19102. if (add_ass) {
  19103. ss << "<|assistant|>\n";
  19104. }
  19105. } else if (tmpl == LLM_CHAT_TEMPLATE_ZEPHYR) {
  19106. // zephyr template
  19107. for (auto message : chat) {
  19108. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  19109. }
  19110. if (add_ass) {
  19111. ss << "<|assistant|>\n";
  19112. }
  19113. } else if (tmpl == LLM_CHAT_TEMPLATE_MONARCH) {
  19114. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  19115. for (auto message : chat) {
  19116. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  19117. ss << bos << message->role << "\n" << message->content << "</s>\n";
  19118. }
  19119. if (add_ass) {
  19120. ss << "<s>assistant\n";
  19121. }
  19122. } else if (tmpl == LLM_CHAT_TEMPLATE_GEMMA) {
  19123. // google/gemma-7b-it
  19124. std::string system_prompt = "";
  19125. for (auto message : chat) {
  19126. std::string role(message->role);
  19127. if (role == "system") {
  19128. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  19129. system_prompt = trim(message->content);
  19130. continue;
  19131. }
  19132. // in gemma, "assistant" is "model"
  19133. role = role == "assistant" ? "model" : message->role;
  19134. ss << "<start_of_turn>" << role << "\n";
  19135. if (!system_prompt.empty() && role != "model") {
  19136. ss << system_prompt << "\n\n";
  19137. system_prompt = "";
  19138. }
  19139. ss << trim(message->content) << "<end_of_turn>\n";
  19140. }
  19141. if (add_ass) {
  19142. ss << "<start_of_turn>model\n";
  19143. }
  19144. } else if (tmpl == LLM_CHAT_TEMPLATE_ORION) {
  19145. // OrionStarAI/Orion-14B-Chat
  19146. std::string system_prompt = "";
  19147. for (auto message : chat) {
  19148. std::string role(message->role);
  19149. if (role == "system") {
  19150. // there is no system message support, we will merge it with user prompt
  19151. system_prompt = message->content;
  19152. continue;
  19153. } else if (role == "user") {
  19154. ss << "Human: ";
  19155. if (!system_prompt.empty()) {
  19156. ss << system_prompt << "\n\n";
  19157. system_prompt = "";
  19158. }
  19159. ss << message->content << "\n\nAssistant: </s>";
  19160. } else {
  19161. ss << message->content << "</s>";
  19162. }
  19163. }
  19164. } else if (tmpl == LLM_CHAT_TEMPLATE_OPENCHAT) {
  19165. // openchat/openchat-3.5-0106,
  19166. for (auto message : chat) {
  19167. std::string role(message->role);
  19168. if (role == "system") {
  19169. ss << message->content << "<|end_of_turn|>";
  19170. } else {
  19171. role[0] = toupper(role[0]);
  19172. ss << "GPT4 Correct " << role << ": " << message->content << "<|end_of_turn|>";
  19173. }
  19174. }
  19175. if (add_ass) {
  19176. ss << "GPT4 Correct Assistant:";
  19177. }
  19178. } else if (tmpl == LLM_CHAT_TEMPLATE_VICUNA || tmpl == LLM_CHAT_TEMPLATE_VICUNA_ORCA) {
  19179. // eachadea/vicuna-13b-1.1 (and Orca variant)
  19180. for (auto message : chat) {
  19181. std::string role(message->role);
  19182. if (role == "system") {
  19183. // Orca-Vicuna variant uses a system prefix
  19184. if (tmpl == LLM_CHAT_TEMPLATE_VICUNA_ORCA) {
  19185. ss << "SYSTEM: " << message->content << "\n";
  19186. } else {
  19187. ss << message->content << "\n\n";
  19188. }
  19189. } else if (role == "user") {
  19190. ss << "USER: " << message->content << "\n";
  19191. } else if (role == "assistant") {
  19192. ss << "ASSISTANT: " << message->content << "</s>\n";
  19193. }
  19194. }
  19195. if (add_ass) {
  19196. ss << "ASSISTANT:";
  19197. }
  19198. } else if (tmpl == LLM_CHAT_TEMPLATE_DEEPSEEK) {
  19199. // deepseek-ai/deepseek-coder-33b-instruct
  19200. for (auto message : chat) {
  19201. std::string role(message->role);
  19202. if (role == "system") {
  19203. ss << message->content;
  19204. } else if (role == "user") {
  19205. ss << "### Instruction:\n" << message->content << "\n";
  19206. } else if (role == "assistant") {
  19207. ss << "### Response:\n" << message->content << "\n<|EOT|>\n";
  19208. }
  19209. }
  19210. if (add_ass) {
  19211. ss << "### Response:\n";
  19212. }
  19213. } else if (tmpl == LLM_CHAT_TEMPLATE_COMMAND_R) {
  19214. // CohereForAI/c4ai-command-r-plus
  19215. for (auto message : chat) {
  19216. std::string role(message->role);
  19217. if (role == "system") {
  19218. ss << "<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  19219. } else if (role == "user") {
  19220. ss << "<|START_OF_TURN_TOKEN|><|USER_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  19221. } else if (role == "assistant") {
  19222. ss << "<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  19223. }
  19224. }
  19225. if (add_ass) {
  19226. ss << "<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>";
  19227. }
  19228. } else if (tmpl == LLM_CHAT_TEMPLATE_LLAMA_3) {
  19229. // Llama 3
  19230. for (auto message : chat) {
  19231. std::string role(message->role);
  19232. ss << "<|start_header_id|>" << role << "<|end_header_id|>\n\n" << trim(message->content) << "<|eot_id|>";
  19233. }
  19234. if (add_ass) {
  19235. ss << "<|start_header_id|>assistant<|end_header_id|>\n\n";
  19236. }
  19237. } else if (tmpl == LLM_CHAT_TEMPLATE_CHATGML_3) {
  19238. // chatglm3-6b
  19239. ss << "[gMASK]" << "sop";
  19240. for (auto message : chat) {
  19241. std::string role(message->role);
  19242. ss << "<|" << role << "|>" << "\n " << message->content;
  19243. }
  19244. if (add_ass) {
  19245. ss << "<|assistant|>";
  19246. }
  19247. } else if (tmpl == LLM_CHAT_TEMPLATE_CHATGML_4) {
  19248. ss << "[gMASK]" << "<sop>";
  19249. for (auto message : chat) {
  19250. std::string role(message->role);
  19251. ss << "<|" << role << "|>" << "\n" << message->content;
  19252. }
  19253. if (add_ass) {
  19254. ss << "<|assistant|>";
  19255. }
  19256. } else if (tmpl == LLM_CHAT_TEMPLATE_MINICPM) {
  19257. // MiniCPM-3B-OpenHermes-2.5-v2-GGUF
  19258. for (auto message : chat) {
  19259. std::string role(message->role);
  19260. if (role == "user") {
  19261. ss << LU8("<用户>");
  19262. ss << trim(message->content);
  19263. ss << "<AI>";
  19264. } else {
  19265. ss << trim(message->content);
  19266. }
  19267. }
  19268. } else if (tmpl == LLM_CHAT_TEMPLATE_DEEPSEEK_2) {
  19269. // DeepSeek-V2
  19270. for (auto message : chat) {
  19271. std::string role(message->role);
  19272. if (role == "system") {
  19273. ss << message->content << "\n\n";
  19274. } else if (role == "user") {
  19275. ss << "User: " << message->content << "\n\n";
  19276. } else if (role == "assistant") {
  19277. ss << "Assistant: " << message->content << LU8("<|end▁of▁sentence|>");
  19278. }
  19279. }
  19280. if (add_ass) {
  19281. ss << "Assistant:";
  19282. }
  19283. } else if (tmpl == LLM_CHAT_TEMPLATE_EXAONE_3) {
  19284. // ref: https://huggingface.co/LGAI-EXAONE/EXAONE-3.0-7.8B-Instruct/discussions/8#66bae61b1893d14ee8ed85bb
  19285. // EXAONE-3.0-7.8B-Instruct
  19286. for (auto message : chat) {
  19287. std::string role(message->role);
  19288. if (role == "system") {
  19289. ss << "[|system|]" << trim(message->content) << "[|endofturn|]\n";
  19290. } else if (role == "user") {
  19291. ss << "[|user|]" << trim(message->content) << "\n";
  19292. } else if (role == "assistant") {
  19293. ss << "[|assistant|]" << trim(message->content) << "[|endofturn|]\n";
  19294. }
  19295. }
  19296. if (add_ass) {
  19297. ss << "[|assistant|]";
  19298. }
  19299. } else if (tmpl == LLM_CHAT_TEMPLATE_RWKV_WORLD) {
  19300. // this template requires the model to have "\n\n" as EOT token
  19301. for (auto message : chat) {
  19302. std::string role(message->role);
  19303. if (role == "user") {
  19304. ss << "User: " << message->content << "\n\nAssistant:";
  19305. } else {
  19306. ss << message->content << "\n\n";
  19307. }
  19308. }
  19309. } else if (tmpl == LLM_CHAT_TEMPLATE_GRANITE) {
  19310. // IBM Granite template
  19311. for (const auto & message : chat) {
  19312. std::string role(message->role);
  19313. ss << "<|start_of_role|>" << role << "<|end_of_role|>";
  19314. if (role == "assistant_tool_call") {
  19315. ss << "<|tool_call|>";
  19316. }
  19317. ss << message->content << "<|end_of_text|>\n";
  19318. }
  19319. if (add_ass) {
  19320. ss << "<|start_of_role|>assistant<|end_of_role|>\n";
  19321. }
  19322. } else {
  19323. // template not supported
  19324. return -1;
  19325. }
  19326. dest = ss.str();
  19327. return dest.size();
  19328. }
  19329. int32_t llama_chat_apply_template(
  19330. const struct llama_model * model,
  19331. const char * tmpl,
  19332. const struct llama_chat_message * chat,
  19333. size_t n_msg,
  19334. bool add_ass,
  19335. char * buf,
  19336. int32_t length) {
  19337. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  19338. if (tmpl == nullptr) {
  19339. GGML_ASSERT(model != nullptr);
  19340. // load template from model
  19341. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  19342. std::string template_key = "tokenizer.chat_template";
  19343. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  19344. if (res < 0) {
  19345. // worst case: there is no information about template, we will use chatml by default
  19346. curr_tmpl = "chatml"; // see llama_chat_apply_template_internal
  19347. } else {
  19348. curr_tmpl = std::string(model_template.data(), model_template.size());
  19349. }
  19350. }
  19351. // format the chat to string
  19352. std::vector<const llama_chat_message *> chat_vec;
  19353. chat_vec.resize(n_msg);
  19354. for (size_t i = 0; i < n_msg; i++) {
  19355. chat_vec[i] = &chat[i];
  19356. }
  19357. std::string formatted_chat;
  19358. llm_chat_template detected_tmpl = llama_chat_detect_template(curr_tmpl);
  19359. if (detected_tmpl == LLM_CHAT_TEMPLATE_UNKNOWN) {
  19360. return -1;
  19361. }
  19362. int32_t res = llama_chat_apply_template_internal(detected_tmpl, chat_vec, formatted_chat, add_ass);
  19363. if (res < 0) {
  19364. return res;
  19365. }
  19366. if (buf && length > 0) {
  19367. strncpy(buf, formatted_chat.c_str(), length);
  19368. }
  19369. return res;
  19370. }
  19371. int32_t llama_chat_builtin_templates(const char ** output, size_t len) {
  19372. auto it = LLM_CHAT_TEMPLATES.begin();
  19373. for (size_t i = 0; i < std::min(len, LLM_CHAT_TEMPLATES.size()); i++) {
  19374. output[i] = it->first.c_str();
  19375. std::advance(it, 1);
  19376. }
  19377. return (int32_t) LLM_CHAT_TEMPLATES.size();
  19378. }
  19379. //
  19380. // sampling
  19381. //
  19382. // TODO: remove indirection when vocab becomes accesible in llama-sampling.cpp
  19383. struct llama_sampler * llama_sampler_init_grammar(const struct llama_model * model, const char * grammar_str, const char * grammar_root) {
  19384. return llama_sampler_init_grammar_impl(model->vocab, grammar_str, grammar_root);
  19385. }
  19386. struct llama_sampler * llama_sampler_init_infill(const struct llama_model * model) {
  19387. return llama_sampler_init_infill_impl(model->vocab);
  19388. }
  19389. struct llama_sampler * llama_sampler_init_dry(const struct llama_model * model, float dry_multiplier, float dry_base, int32_t dry_allowed_length, int32_t dry_penalty_last_n, const char** seq_breakers, size_t num_breakers) {
  19390. return llama_sampler_init_dry_impl(model->vocab, llama_n_ctx_train(model), dry_multiplier, dry_base, dry_allowed_length, dry_penalty_last_n, seq_breakers, num_breakers);
  19391. }
  19392. //
  19393. // model split
  19394. //
  19395. int llama_split_path(char * split_path, size_t maxlen, const char * path_prefix, int split_no, int split_count) {
  19396. static const char * const SPLIT_PATH_FORMAT = "%s-%05d-of-%05d.gguf";
  19397. if (snprintf(split_path, maxlen, SPLIT_PATH_FORMAT, path_prefix, split_no + 1, split_count)) {
  19398. return strlen(split_path);
  19399. }
  19400. return 0;
  19401. }
  19402. int llama_split_prefix(char * dest, size_t maxlen, const char * split_path, int split_no, int split_count) {
  19403. std::string str_split_path(split_path);
  19404. char postfix[32];
  19405. snprintf(postfix, 32, "-%05d-of-%05d.gguf", split_no + 1, split_count);
  19406. std::string str_postfix(postfix);
  19407. // check if dest ends with postfix
  19408. int size_prefix = str_split_path.size() - str_postfix.size();
  19409. if (size_prefix > 0 && str_split_path.find(str_postfix, size_prefix) != std::string::npos) {
  19410. snprintf(dest, std::min((size_t) size_prefix + 1, maxlen), "%s", split_path);
  19411. return size_prefix;
  19412. }
  19413. return 0;
  19414. }
  19415. const char * llama_print_system_info(void) {
  19416. static std::string s;
  19417. for (size_t i = 0; i < ggml_backend_reg_count(); i++) {
  19418. auto * reg = ggml_backend_reg_get(i);
  19419. auto * get_features_fn = (ggml_backend_get_features_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_get_features");
  19420. if (get_features_fn) {
  19421. ggml_backend_feature * features = get_features_fn(reg);
  19422. s += ggml_backend_reg_name(reg);
  19423. s += " : ";
  19424. for (; features->name; features++) {
  19425. s += features->name;
  19426. s += " = ";
  19427. s += features->value;
  19428. s += " | ";
  19429. }
  19430. }
  19431. }
  19432. return s.c_str();
  19433. }
  19434. struct llama_perf_context_data llama_perf_context(const struct llama_context * ctx) {
  19435. struct llama_perf_context_data data = {};
  19436. if (ctx == nullptr) {
  19437. return data;
  19438. }
  19439. data.t_start_ms = 1e-3 * ctx->t_start_us;
  19440. data.t_load_ms = 1e-3 * ctx->t_load_us;
  19441. data.t_p_eval_ms = 1e-3 * ctx->t_p_eval_us;
  19442. data.t_eval_ms = 1e-3 * ctx->t_eval_us;
  19443. data.n_p_eval = std::max(1, ctx->n_p_eval);
  19444. data.n_eval = std::max(1, ctx->n_eval);
  19445. return data;
  19446. }
  19447. void llama_perf_context_print(const struct llama_context * ctx) {
  19448. const auto data = llama_perf_context(ctx);
  19449. const double t_end_ms = 1e-3 * ggml_time_us();
  19450. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, data.t_load_ms);
  19451. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  19452. __func__, data.t_p_eval_ms, data.n_p_eval, data.t_p_eval_ms / data.n_p_eval, 1e3 / data.t_p_eval_ms * data.n_p_eval);
  19453. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  19454. __func__, data.t_eval_ms, data.n_eval, data.t_eval_ms / data.n_eval, 1e3 / data.t_eval_ms * data.n_eval);
  19455. LLAMA_LOG_INFO("%s: total time = %10.2f ms / %5d tokens\n", __func__, (t_end_ms - data.t_start_ms), (data.n_p_eval + data.n_eval));
  19456. }
  19457. void llama_perf_context_reset(struct llama_context * ctx) {
  19458. ctx->t_start_us = ggml_time_us();
  19459. ctx->t_eval_us = ctx->n_eval = 0;
  19460. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  19461. }
  19462. // For internal test use
  19463. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  19464. struct llama_context * ctx
  19465. ) {
  19466. return ctx->model.tensors_by_name;
  19467. }
  19468. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  19469. ggml_log_set(log_callback, user_data);
  19470. g_logger_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  19471. g_logger_state.log_callback_user_data = user_data;
  19472. }
  19473. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  19474. va_list args_copy;
  19475. va_copy(args_copy, args);
  19476. char buffer[128];
  19477. int len = vsnprintf(buffer, 128, format, args);
  19478. if (len < 128) {
  19479. g_logger_state.log_callback(level, buffer, g_logger_state.log_callback_user_data);
  19480. } else {
  19481. char * buffer2 = new char[len + 1];
  19482. vsnprintf(buffer2, len + 1, format, args_copy);
  19483. buffer2[len] = 0;
  19484. g_logger_state.log_callback(level, buffer2, g_logger_state.log_callback_user_data);
  19485. delete[] buffer2;
  19486. }
  19487. va_end(args_copy);
  19488. }
  19489. void llama_log_internal(ggml_log_level level, const char * format, ...) {
  19490. va_list args;
  19491. va_start(args, format);
  19492. llama_log_internal_v(level, format, args);
  19493. va_end(args);
  19494. }
  19495. void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  19496. (void) level;
  19497. (void) user_data;
  19498. fputs(text, stderr);
  19499. fflush(stderr);
  19500. }