llama.cpp 972 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229
  1. /**
  2. * llama.cpp - commit ba1cb19cdd0d92e012e0f6e009e0620f854b6afd - 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_QWEN2VL,
  174. LLM_ARCH_PHI2,
  175. LLM_ARCH_PHI3,
  176. LLM_ARCH_PLAMO,
  177. LLM_ARCH_CODESHELL,
  178. LLM_ARCH_ORION,
  179. LLM_ARCH_INTERNLM2,
  180. LLM_ARCH_MINICPM,
  181. LLM_ARCH_MINICPM3,
  182. LLM_ARCH_GEMMA,
  183. LLM_ARCH_GEMMA2,
  184. LLM_ARCH_STARCODER2,
  185. LLM_ARCH_MAMBA,
  186. LLM_ARCH_XVERSE,
  187. LLM_ARCH_COMMAND_R,
  188. LLM_ARCH_DBRX,
  189. LLM_ARCH_OLMO,
  190. LLM_ARCH_OLMO2,
  191. LLM_ARCH_OLMOE,
  192. LLM_ARCH_OPENELM,
  193. LLM_ARCH_ARCTIC,
  194. LLM_ARCH_DEEPSEEK2,
  195. LLM_ARCH_CHATGLM,
  196. LLM_ARCH_BITNET,
  197. LLM_ARCH_T5,
  198. LLM_ARCH_T5ENCODER,
  199. LLM_ARCH_JAIS,
  200. LLM_ARCH_NEMOTRON,
  201. LLM_ARCH_EXAONE,
  202. LLM_ARCH_RWKV6,
  203. LLM_ARCH_GRANITE,
  204. LLM_ARCH_GRANITE_MOE,
  205. LLM_ARCH_CHAMELEON,
  206. LLM_ARCH_SOLAR,
  207. LLM_ARCH_UNKNOWN,
  208. };
  209. static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  210. { LLM_ARCH_LLAMA, "llama" },
  211. { LLM_ARCH_MLLAMA, "mllama" },
  212. { LLM_ARCH_FALCON, "falcon" },
  213. { LLM_ARCH_GROK, "grok" },
  214. { LLM_ARCH_GPT2, "gpt2" },
  215. { LLM_ARCH_GPTJ, "gptj" },
  216. { LLM_ARCH_GPTNEOX, "gptneox" },
  217. { LLM_ARCH_MPT, "mpt" },
  218. { LLM_ARCH_BAICHUAN, "baichuan" },
  219. { LLM_ARCH_STARCODER, "starcoder" },
  220. { LLM_ARCH_REFACT, "refact" },
  221. { LLM_ARCH_BERT, "bert" },
  222. { LLM_ARCH_NOMIC_BERT, "nomic-bert" },
  223. { LLM_ARCH_JINA_BERT_V2, "jina-bert-v2" },
  224. { LLM_ARCH_BLOOM, "bloom" },
  225. { LLM_ARCH_STABLELM, "stablelm" },
  226. { LLM_ARCH_QWEN, "qwen" },
  227. { LLM_ARCH_QWEN2, "qwen2" },
  228. { LLM_ARCH_QWEN2MOE, "qwen2moe" },
  229. { LLM_ARCH_QWEN2VL, "qwen2vl" },
  230. { LLM_ARCH_PHI2, "phi2" },
  231. { LLM_ARCH_PHI3, "phi3" },
  232. { LLM_ARCH_PLAMO, "plamo" },
  233. { LLM_ARCH_CODESHELL, "codeshell" },
  234. { LLM_ARCH_ORION, "orion" },
  235. { LLM_ARCH_INTERNLM2, "internlm2" },
  236. { LLM_ARCH_MINICPM, "minicpm" },
  237. { LLM_ARCH_MINICPM3, "minicpm3" },
  238. { LLM_ARCH_GEMMA, "gemma" },
  239. { LLM_ARCH_GEMMA2, "gemma2" },
  240. { LLM_ARCH_STARCODER2, "starcoder2" },
  241. { LLM_ARCH_MAMBA, "mamba" },
  242. { LLM_ARCH_XVERSE, "xverse" },
  243. { LLM_ARCH_COMMAND_R, "command-r" },
  244. { LLM_ARCH_DBRX, "dbrx" },
  245. { LLM_ARCH_OLMO, "olmo" },
  246. { LLM_ARCH_OLMO2, "olmo2" },
  247. { LLM_ARCH_OLMOE, "olmoe" },
  248. { LLM_ARCH_OPENELM, "openelm" },
  249. { LLM_ARCH_ARCTIC, "arctic" },
  250. { LLM_ARCH_DEEPSEEK2, "deepseek2" },
  251. { LLM_ARCH_CHATGLM, "chatglm" },
  252. { LLM_ARCH_BITNET, "bitnet" },
  253. { LLM_ARCH_T5, "t5" },
  254. { LLM_ARCH_T5ENCODER, "t5encoder" },
  255. { LLM_ARCH_JAIS, "jais" },
  256. { LLM_ARCH_NEMOTRON, "nemotron" },
  257. { LLM_ARCH_EXAONE, "exaone" },
  258. { LLM_ARCH_RWKV6, "rwkv6" },
  259. { LLM_ARCH_GRANITE, "granite" },
  260. { LLM_ARCH_GRANITE_MOE, "granitemoe" },
  261. { LLM_ARCH_CHAMELEON, "chameleon" },
  262. { LLM_ARCH_SOLAR, "solar" },
  263. { LLM_ARCH_UNKNOWN, "(unknown)" },
  264. };
  265. enum llm_kv {
  266. LLM_KV_GENERAL_TYPE,
  267. LLM_KV_GENERAL_ARCHITECTURE,
  268. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  269. LLM_KV_GENERAL_ALIGNMENT,
  270. LLM_KV_GENERAL_NAME,
  271. LLM_KV_GENERAL_AUTHOR,
  272. LLM_KV_GENERAL_VERSION,
  273. LLM_KV_GENERAL_URL,
  274. LLM_KV_GENERAL_DESCRIPTION,
  275. LLM_KV_GENERAL_LICENSE,
  276. LLM_KV_GENERAL_SOURCE_URL,
  277. LLM_KV_GENERAL_SOURCE_HF_REPO,
  278. LLM_KV_VOCAB_SIZE,
  279. LLM_KV_CONTEXT_LENGTH,
  280. LLM_KV_EMBEDDING_LENGTH,
  281. LLM_KV_BLOCK_COUNT,
  282. LLM_KV_LEADING_DENSE_BLOCK_COUNT,
  283. LLM_KV_FEED_FORWARD_LENGTH,
  284. LLM_KV_EXPERT_FEED_FORWARD_LENGTH,
  285. LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH,
  286. LLM_KV_USE_PARALLEL_RESIDUAL,
  287. LLM_KV_TENSOR_DATA_LAYOUT,
  288. LLM_KV_EXPERT_COUNT,
  289. LLM_KV_EXPERT_USED_COUNT,
  290. LLM_KV_EXPERT_SHARED_COUNT,
  291. LLM_KV_EXPERT_WEIGHTS_SCALE,
  292. LLM_KV_POOLING_TYPE,
  293. LLM_KV_LOGIT_SCALE,
  294. LLM_KV_DECODER_START_TOKEN_ID,
  295. LLM_KV_ATTN_LOGIT_SOFTCAPPING,
  296. LLM_KV_FINAL_LOGIT_SOFTCAPPING,
  297. LLM_KV_SWIN_NORM,
  298. LLM_KV_RESCALE_EVERY_N_LAYERS,
  299. LLM_KV_TIME_MIX_EXTRA_DIM,
  300. LLM_KV_TIME_DECAY_EXTRA_DIM,
  301. LLM_KV_RESIDUAL_SCALE,
  302. LLM_KV_EMBEDDING_SCALE,
  303. LLM_KV_ATTENTION_HEAD_COUNT,
  304. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  305. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  306. LLM_KV_ATTENTION_CLAMP_KQV,
  307. LLM_KV_ATTENTION_KEY_LENGTH,
  308. LLM_KV_ATTENTION_VALUE_LENGTH,
  309. LLM_KV_ATTENTION_LAYERNORM_EPS,
  310. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  311. LLM_KV_ATTENTION_CAUSAL,
  312. LLM_KV_ATTENTION_Q_LORA_RANK,
  313. LLM_KV_ATTENTION_KV_LORA_RANK,
  314. LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT,
  315. LLM_KV_ATTENTION_SLIDING_WINDOW,
  316. LLM_KV_ATTENTION_SCALE,
  317. LLM_KV_ATTENTION_BLOCK_SKIP_CONNECTION,
  318. LLM_KV_ATTENTION_CROSS_ATTENTION_LAYERS,
  319. LLM_KV_ROPE_DIMENSION_COUNT,
  320. LLM_KV_ROPE_DIMENSION_SECTIONS,
  321. LLM_KV_ROPE_FREQ_BASE,
  322. LLM_KV_ROPE_SCALE_LINEAR,
  323. LLM_KV_ROPE_SCALING_TYPE,
  324. LLM_KV_ROPE_SCALING_FACTOR,
  325. LLM_KV_ROPE_SCALING_ATTN_FACTOR,
  326. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  327. LLM_KV_ROPE_SCALING_FINETUNED,
  328. LLM_KV_ROPE_SCALING_YARN_LOG_MUL,
  329. LLM_KV_SPLIT_NO,
  330. LLM_KV_SPLIT_COUNT,
  331. LLM_KV_SPLIT_TENSORS_COUNT,
  332. LLM_KV_SSM_INNER_SIZE,
  333. LLM_KV_SSM_CONV_KERNEL,
  334. LLM_KV_SSM_STATE_SIZE,
  335. LLM_KV_SSM_TIME_STEP_RANK,
  336. LLM_KV_SSM_DT_B_C_RMS,
  337. LLM_KV_WKV_HEAD_SIZE,
  338. LLM_KV_TOKENIZER_MODEL,
  339. LLM_KV_TOKENIZER_PRE,
  340. LLM_KV_TOKENIZER_LIST,
  341. LLM_KV_TOKENIZER_TOKEN_TYPE,
  342. LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT,
  343. LLM_KV_TOKENIZER_SCORES,
  344. LLM_KV_TOKENIZER_MERGES,
  345. LLM_KV_TOKENIZER_BOS_ID,
  346. LLM_KV_TOKENIZER_EOS_ID,
  347. LLM_KV_TOKENIZER_EOT_ID,
  348. LLM_KV_TOKENIZER_EOM_ID,
  349. LLM_KV_TOKENIZER_UNK_ID,
  350. LLM_KV_TOKENIZER_SEP_ID,
  351. LLM_KV_TOKENIZER_PAD_ID,
  352. LLM_KV_TOKENIZER_CLS_ID,
  353. LLM_KV_TOKENIZER_MASK_ID,
  354. LLM_KV_TOKENIZER_ADD_BOS,
  355. LLM_KV_TOKENIZER_ADD_EOS,
  356. LLM_KV_TOKENIZER_ADD_PREFIX,
  357. LLM_KV_TOKENIZER_REMOVE_EXTRA_WS,
  358. LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP,
  359. LLM_KV_TOKENIZER_HF_JSON,
  360. LLM_KV_TOKENIZER_RWKV,
  361. LLM_KV_TOKENIZER_FIM_PRE_ID,
  362. LLM_KV_TOKENIZER_FIM_SUF_ID,
  363. LLM_KV_TOKENIZER_FIM_MID_ID,
  364. LLM_KV_TOKENIZER_FIM_PAD_ID,
  365. LLM_KV_TOKENIZER_FIM_REP_ID,
  366. LLM_KV_TOKENIZER_FIM_SEP_ID,
  367. LLM_KV_ADAPTER_TYPE,
  368. LLM_KV_ADAPTER_LORA_ALPHA,
  369. // deprecated:
  370. LLM_KV_TOKENIZER_PREFIX_ID,
  371. LLM_KV_TOKENIZER_SUFFIX_ID,
  372. LLM_KV_TOKENIZER_MIDDLE_ID,
  373. };
  374. static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
  375. { LLM_KV_GENERAL_TYPE, "general.type" },
  376. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  377. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  378. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  379. { LLM_KV_GENERAL_NAME, "general.name" },
  380. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  381. { LLM_KV_GENERAL_VERSION, "general.version" },
  382. { LLM_KV_GENERAL_URL, "general.url" },
  383. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  384. { LLM_KV_GENERAL_LICENSE, "general.license" },
  385. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  386. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  387. { LLM_KV_VOCAB_SIZE, "%s.vocab_size" },
  388. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  389. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  390. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  391. { LLM_KV_LEADING_DENSE_BLOCK_COUNT, "%s.leading_dense_block_count" },
  392. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  393. { LLM_KV_EXPERT_FEED_FORWARD_LENGTH, "%s.expert_feed_forward_length" },
  394. { LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, "%s.expert_shared_feed_forward_length" },
  395. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  396. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  397. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  398. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  399. { LLM_KV_EXPERT_SHARED_COUNT, "%s.expert_shared_count" },
  400. { LLM_KV_EXPERT_WEIGHTS_SCALE, "%s.expert_weights_scale" },
  401. { LLM_KV_POOLING_TYPE, "%s.pooling_type" },
  402. { LLM_KV_LOGIT_SCALE, "%s.logit_scale" },
  403. { LLM_KV_DECODER_START_TOKEN_ID, "%s.decoder_start_token_id" },
  404. { LLM_KV_ATTN_LOGIT_SOFTCAPPING, "%s.attn_logit_softcapping" },
  405. { LLM_KV_FINAL_LOGIT_SOFTCAPPING, "%s.final_logit_softcapping" },
  406. { LLM_KV_SWIN_NORM, "%s.swin_norm" },
  407. { LLM_KV_RESCALE_EVERY_N_LAYERS, "%s.rescale_every_n_layers" },
  408. { LLM_KV_TIME_MIX_EXTRA_DIM, "%s.time_mix_extra_dim" },
  409. { LLM_KV_TIME_DECAY_EXTRA_DIM, "%s.time_decay_extra_dim" },
  410. { LLM_KV_RESIDUAL_SCALE, "%s.residual_scale" },
  411. { LLM_KV_EMBEDDING_SCALE, "%s.embedding_scale" },
  412. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  413. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  414. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  415. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  416. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  417. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  418. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  419. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  420. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  421. { LLM_KV_ATTENTION_Q_LORA_RANK, "%s.attention.q_lora_rank" },
  422. { LLM_KV_ATTENTION_KV_LORA_RANK, "%s.attention.kv_lora_rank" },
  423. { LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, "%s.attention.relative_buckets_count" },
  424. { LLM_KV_ATTENTION_SLIDING_WINDOW, "%s.attention.sliding_window" },
  425. { LLM_KV_ATTENTION_SCALE, "%s.attention.scale" },
  426. { LLM_KV_ATTENTION_BLOCK_SKIP_CONNECTION, "%s.attention.block_skip_connection.%d" },
  427. { LLM_KV_ATTENTION_CROSS_ATTENTION_LAYERS, "%s.attention.cross_attention_layers" },
  428. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  429. { LLM_KV_ROPE_DIMENSION_SECTIONS, "%s.rope.dimension_sections" },
  430. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  431. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  432. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  433. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  434. { LLM_KV_ROPE_SCALING_ATTN_FACTOR, "%s.rope.scaling.attn_factor" },
  435. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  436. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  437. { LLM_KV_ROPE_SCALING_YARN_LOG_MUL, "%s.rope.scaling.yarn_log_multiplier" },
  438. { LLM_KV_SPLIT_NO, "split.no" },
  439. { LLM_KV_SPLIT_COUNT, "split.count" },
  440. { LLM_KV_SPLIT_TENSORS_COUNT, "split.tensors.count" },
  441. { LLM_KV_SSM_CONV_KERNEL, "%s.ssm.conv_kernel" },
  442. { LLM_KV_SSM_INNER_SIZE, "%s.ssm.inner_size" },
  443. { LLM_KV_SSM_STATE_SIZE, "%s.ssm.state_size" },
  444. { LLM_KV_SSM_TIME_STEP_RANK, "%s.ssm.time_step_rank" },
  445. { LLM_KV_SSM_DT_B_C_RMS, "%s.ssm.dt_b_c_rms" },
  446. { LLM_KV_WKV_HEAD_SIZE, "%s.wkv.head_size" },
  447. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  448. { LLM_KV_TOKENIZER_PRE, "tokenizer.ggml.pre" },
  449. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  450. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  451. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  452. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  453. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  454. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  455. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  456. { LLM_KV_TOKENIZER_EOT_ID, "tokenizer.ggml.eot_token_id" },
  457. { LLM_KV_TOKENIZER_EOM_ID, "tokenizer.ggml.eom_token_id" },
  458. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  459. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  460. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  461. { LLM_KV_TOKENIZER_CLS_ID, "tokenizer.ggml.cls_token_id" },
  462. { LLM_KV_TOKENIZER_MASK_ID, "tokenizer.ggml.mask_token_id" },
  463. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  464. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  465. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  466. { LLM_KV_TOKENIZER_REMOVE_EXTRA_WS, "tokenizer.ggml.remove_extra_whitespaces" },
  467. { LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP, "tokenizer.ggml.precompiled_charsmap" },
  468. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  469. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  470. { LLM_KV_TOKENIZER_FIM_PRE_ID, "tokenizer.ggml.fim_pre_token_id" },
  471. { LLM_KV_TOKENIZER_FIM_SUF_ID, "tokenizer.ggml.fim_suf_token_id" },
  472. { LLM_KV_TOKENIZER_FIM_MID_ID, "tokenizer.ggml.fim_mid_token_id" },
  473. { LLM_KV_TOKENIZER_FIM_PAD_ID, "tokenizer.ggml.fim_pad_token_id" },
  474. { LLM_KV_TOKENIZER_FIM_REP_ID, "tokenizer.ggml.fim_rep_token_id" },
  475. { LLM_KV_TOKENIZER_FIM_SEP_ID, "tokenizer.ggml.fim_sep_token_id" },
  476. { LLM_KV_ADAPTER_TYPE, "adapter.type" },
  477. { LLM_KV_ADAPTER_LORA_ALPHA, "adapter.lora.alpha" },
  478. // deprecated
  479. { LLM_KV_TOKENIZER_PREFIX_ID, "tokenizer.ggml.prefix_token_id" },
  480. { LLM_KV_TOKENIZER_SUFFIX_ID, "tokenizer.ggml.suffix_token_id" },
  481. { LLM_KV_TOKENIZER_MIDDLE_ID, "tokenizer.ggml.middle_token_id" },
  482. };
  483. struct LLM_KV {
  484. LLM_KV(llm_arch arch) : arch(arch) {}
  485. llm_arch arch;
  486. std::string operator()(llm_kv kv) const {
  487. return ::format(LLM_KV_NAMES.at(kv), LLM_ARCH_NAMES.at(arch));
  488. }
  489. };
  490. enum llm_tensor {
  491. LLM_TENSOR_TOKEN_EMBD,
  492. LLM_TENSOR_TOKEN_EMBD_NORM,
  493. LLM_TENSOR_TOKEN_TYPES,
  494. LLM_TENSOR_POS_EMBD,
  495. LLM_TENSOR_OUTPUT,
  496. LLM_TENSOR_OUTPUT_NORM,
  497. LLM_TENSOR_ROPE_FREQS,
  498. LLM_TENSOR_ROPE_FACTORS_LONG,
  499. LLM_TENSOR_ROPE_FACTORS_SHORT,
  500. LLM_TENSOR_ATTN_Q,
  501. LLM_TENSOR_ATTN_K,
  502. LLM_TENSOR_ATTN_V,
  503. LLM_TENSOR_ATTN_QKV,
  504. LLM_TENSOR_ATTN_OUT,
  505. LLM_TENSOR_ATTN_NORM,
  506. LLM_TENSOR_ATTN_NORM_2,
  507. LLM_TENSOR_ATTN_OUT_NORM,
  508. LLM_TENSOR_ATTN_POST_NORM,
  509. LLM_TENSOR_ATTN_ROT_EMBD,
  510. LLM_TENSOR_FFN_GATE_INP,
  511. LLM_TENSOR_FFN_GATE_INP_SHEXP,
  512. LLM_TENSOR_FFN_NORM,
  513. LLM_TENSOR_FFN_POST_NORM,
  514. LLM_TENSOR_FFN_GATE,
  515. LLM_TENSOR_FFN_DOWN,
  516. LLM_TENSOR_FFN_UP,
  517. LLM_TENSOR_FFN_ACT,
  518. LLM_TENSOR_FFN_DOWN_EXP, // split experts for backward compatibility
  519. LLM_TENSOR_FFN_GATE_EXP,
  520. LLM_TENSOR_FFN_UP_EXP,
  521. LLM_TENSOR_FFN_NORM_EXPS,
  522. LLM_TENSOR_FFN_DOWN_EXPS, // merged experts
  523. LLM_TENSOR_FFN_GATE_EXPS,
  524. LLM_TENSOR_FFN_UP_EXPS,
  525. LLM_TENSOR_FFN_DOWN_SHEXP,
  526. LLM_TENSOR_FFN_GATE_SHEXP,
  527. LLM_TENSOR_FFN_UP_SHEXP,
  528. LLM_TENSOR_ATTN_Q_NORM,
  529. LLM_TENSOR_ATTN_K_NORM,
  530. LLM_TENSOR_LAYER_OUT_NORM,
  531. LLM_TENSOR_SSM_IN,
  532. LLM_TENSOR_SSM_CONV1D,
  533. LLM_TENSOR_SSM_X,
  534. LLM_TENSOR_SSM_DT,
  535. LLM_TENSOR_SSM_A,
  536. LLM_TENSOR_SSM_D,
  537. LLM_TENSOR_SSM_OUT,
  538. LLM_TENSOR_TIME_MIX_W1,
  539. LLM_TENSOR_TIME_MIX_W2,
  540. LLM_TENSOR_TIME_MIX_LERP_X,
  541. LLM_TENSOR_TIME_MIX_LERP_W,
  542. LLM_TENSOR_TIME_MIX_LERP_K,
  543. LLM_TENSOR_TIME_MIX_LERP_V,
  544. LLM_TENSOR_TIME_MIX_LERP_R,
  545. LLM_TENSOR_TIME_MIX_LERP_G,
  546. LLM_TENSOR_TIME_MIX_FIRST,
  547. LLM_TENSOR_TIME_MIX_DECAY,
  548. LLM_TENSOR_TIME_MIX_DECAY_W1,
  549. LLM_TENSOR_TIME_MIX_DECAY_W2,
  550. LLM_TENSOR_TIME_MIX_KEY,
  551. LLM_TENSOR_TIME_MIX_VALUE,
  552. LLM_TENSOR_TIME_MIX_RECEPTANCE,
  553. LLM_TENSOR_TIME_MIX_GATE,
  554. LLM_TENSOR_TIME_MIX_LN,
  555. LLM_TENSOR_TIME_MIX_OUTPUT,
  556. LLM_TENSOR_CHANNEL_MIX_LERP_K,
  557. LLM_TENSOR_CHANNEL_MIX_LERP_R,
  558. LLM_TENSOR_CHANNEL_MIX_KEY,
  559. LLM_TENSOR_CHANNEL_MIX_RECEPTANCE,
  560. LLM_TENSOR_CHANNEL_MIX_VALUE,
  561. LLM_TENSOR_ATTN_Q_A,
  562. LLM_TENSOR_ATTN_Q_B,
  563. LLM_TENSOR_ATTN_KV_A_MQA,
  564. LLM_TENSOR_ATTN_KV_B,
  565. LLM_TENSOR_ATTN_Q_A_NORM,
  566. LLM_TENSOR_ATTN_KV_A_NORM,
  567. LLM_TENSOR_ATTN_SUB_NORM,
  568. LLM_TENSOR_FFN_SUB_NORM,
  569. LLM_TENSOR_DEC_ATTN_NORM,
  570. LLM_TENSOR_DEC_ATTN_Q,
  571. LLM_TENSOR_DEC_ATTN_K,
  572. LLM_TENSOR_DEC_ATTN_V,
  573. LLM_TENSOR_DEC_ATTN_OUT,
  574. LLM_TENSOR_DEC_ATTN_REL_B,
  575. LLM_TENSOR_DEC_CROSS_ATTN_NORM,
  576. LLM_TENSOR_DEC_CROSS_ATTN_Q,
  577. LLM_TENSOR_DEC_CROSS_ATTN_K,
  578. LLM_TENSOR_DEC_CROSS_ATTN_V,
  579. LLM_TENSOR_DEC_CROSS_ATTN_OUT,
  580. LLM_TENSOR_DEC_CROSS_ATTN_REL_B,
  581. LLM_TENSOR_DEC_FFN_NORM,
  582. LLM_TENSOR_DEC_FFN_GATE,
  583. LLM_TENSOR_DEC_FFN_DOWN,
  584. LLM_TENSOR_DEC_FFN_UP,
  585. LLM_TENSOR_DEC_OUTPUT_NORM,
  586. LLM_TENSOR_ENC_ATTN_NORM,
  587. LLM_TENSOR_ENC_ATTN_Q,
  588. LLM_TENSOR_ENC_ATTN_K,
  589. LLM_TENSOR_ENC_ATTN_V,
  590. LLM_TENSOR_ENC_ATTN_OUT,
  591. LLM_TENSOR_ENC_ATTN_REL_B,
  592. LLM_TENSOR_ENC_FFN_NORM,
  593. LLM_TENSOR_ENC_FFN_GATE,
  594. LLM_TENSOR_ENC_FFN_DOWN,
  595. LLM_TENSOR_ENC_FFN_UP,
  596. LLM_TENSOR_ENC_OUTPUT_NORM,
  597. LLM_TENSOR_CLS,
  598. LLM_TENSOR_CLS_OUT,
  599. LLM_TENSOR_BSKCN_TV,
  600. LLM_TENSOR_CROSS_ATTN_K_NORM,
  601. LLM_TENSOR_CROSS_ATTN_K_PROJ,
  602. LLM_TENSOR_CROSS_ATTN_O_PROJ,
  603. LLM_TENSOR_CROSS_ATTN_Q_NORM,
  604. LLM_TENSOR_CROSS_ATTN_Q_PROJ,
  605. LLM_TENSOR_CROSS_ATTN_V_PROJ,
  606. LLM_TENSOR_CROSS_ATTN_ATTN_GATE,
  607. LLM_TENSOR_CROSS_ATTN_MLP_GATE,
  608. };
  609. static const std::map<llm_arch, std::map<llm_tensor, const char *>> LLM_TENSOR_NAMES = {
  610. {
  611. LLM_ARCH_LLAMA,
  612. {
  613. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  614. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  615. { LLM_TENSOR_OUTPUT, "output" },
  616. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  617. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  618. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  619. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  620. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  621. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  622. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  623. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  624. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  625. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  626. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  627. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  628. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  629. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  630. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  631. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  632. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  633. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  634. },
  635. },
  636. {
  637. LLM_ARCH_MLLAMA,
  638. {
  639. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  640. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  641. { LLM_TENSOR_OUTPUT, "output" },
  642. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  643. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  644. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  645. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  646. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  647. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  648. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  649. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  650. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  651. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  652. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  653. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  654. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  655. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  656. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  657. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  658. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  659. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  660. { LLM_TENSOR_CROSS_ATTN_K_NORM, "blk.%d.cross_attn_k_norm" },
  661. { LLM_TENSOR_CROSS_ATTN_K_PROJ, "blk.%d.cross_attn_k_proj" },
  662. { LLM_TENSOR_CROSS_ATTN_O_PROJ, "blk.%d.cross_attn_o_proj" },
  663. { LLM_TENSOR_CROSS_ATTN_Q_NORM, "blk.%d.cross_attn_q_norm" },
  664. { LLM_TENSOR_CROSS_ATTN_Q_PROJ, "blk.%d.cross_attn_q_proj" },
  665. { LLM_TENSOR_CROSS_ATTN_V_PROJ, "blk.%d.cross_attn_v_proj" },
  666. { LLM_TENSOR_CROSS_ATTN_ATTN_GATE, "blk.%d.cross_attn_attn_gate" },
  667. { LLM_TENSOR_CROSS_ATTN_MLP_GATE, "blk.%d.cross_attn_mlp_gate" },
  668. },
  669. },
  670. {
  671. LLM_ARCH_BAICHUAN,
  672. {
  673. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  674. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  675. { LLM_TENSOR_OUTPUT, "output" },
  676. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  677. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  678. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  679. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  680. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  681. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  682. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  683. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  684. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  685. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  686. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  687. },
  688. },
  689. {
  690. LLM_ARCH_FALCON,
  691. {
  692. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  693. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  694. { LLM_TENSOR_OUTPUT, "output" },
  695. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  696. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  697. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  698. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  699. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  700. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  701. },
  702. },
  703. {
  704. LLM_ARCH_GROK,
  705. {
  706. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  707. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  708. { LLM_TENSOR_OUTPUT, "output" },
  709. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  710. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  711. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  712. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  713. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  714. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  715. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  716. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  717. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  718. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  719. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  720. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  721. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  722. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  723. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  724. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  725. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  726. },
  727. },
  728. {
  729. LLM_ARCH_GPT2,
  730. {
  731. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  732. { LLM_TENSOR_POS_EMBD, "position_embd" },
  733. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  734. { LLM_TENSOR_OUTPUT, "output" },
  735. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  736. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  737. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  738. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  739. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  740. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  741. },
  742. },
  743. {
  744. LLM_ARCH_GPTJ,
  745. {
  746. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  747. },
  748. },
  749. {
  750. LLM_ARCH_GPTNEOX,
  751. {
  752. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  753. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  754. { LLM_TENSOR_OUTPUT, "output" },
  755. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  756. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  757. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  758. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  759. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  760. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  761. },
  762. },
  763. {
  764. LLM_ARCH_MPT,
  765. {
  766. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  767. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  768. { LLM_TENSOR_OUTPUT, "output"},
  769. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  770. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  771. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  772. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  773. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  774. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  775. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  776. { LLM_TENSOR_POS_EMBD, "position_embd" },
  777. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  778. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  779. },
  780. },
  781. {
  782. LLM_ARCH_STARCODER,
  783. {
  784. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  785. { LLM_TENSOR_POS_EMBD, "position_embd" },
  786. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  787. { LLM_TENSOR_OUTPUT, "output" },
  788. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  789. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  790. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  791. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  792. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  793. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  794. },
  795. },
  796. {
  797. LLM_ARCH_REFACT,
  798. {
  799. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  800. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  801. { LLM_TENSOR_OUTPUT, "output" },
  802. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  803. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  804. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  805. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  806. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  807. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  808. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  809. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  810. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  811. },
  812. },
  813. {
  814. LLM_ARCH_BERT,
  815. {
  816. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  817. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  818. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  819. { LLM_TENSOR_POS_EMBD, "position_embd" },
  820. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  821. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  822. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  823. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  824. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  825. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  826. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  827. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  828. { LLM_TENSOR_CLS, "cls" },
  829. { LLM_TENSOR_CLS_OUT, "cls.output" },
  830. },
  831. },
  832. {
  833. LLM_ARCH_NOMIC_BERT,
  834. {
  835. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  836. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  837. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  838. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  839. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  840. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  841. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  842. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  843. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  844. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  845. },
  846. },
  847. {
  848. LLM_ARCH_JINA_BERT_V2,
  849. {
  850. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  851. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  852. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  853. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  854. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  855. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  856. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  857. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  858. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  859. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  860. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  861. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  862. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  863. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  864. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  865. { LLM_TENSOR_CLS, "cls" },
  866. },
  867. },
  868. {
  869. LLM_ARCH_BLOOM,
  870. {
  871. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  872. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  873. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  874. { LLM_TENSOR_OUTPUT, "output" },
  875. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  876. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  877. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  878. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  879. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  880. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  881. },
  882. },
  883. {
  884. LLM_ARCH_STABLELM,
  885. {
  886. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  887. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  888. { LLM_TENSOR_OUTPUT, "output" },
  889. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  890. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  891. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  892. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  893. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  894. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  895. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  896. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  897. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  898. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  899. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  900. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  901. },
  902. },
  903. {
  904. LLM_ARCH_QWEN,
  905. {
  906. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  907. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  908. { LLM_TENSOR_OUTPUT, "output" },
  909. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  910. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  911. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  912. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  913. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  914. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  915. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  916. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  917. },
  918. },
  919. {
  920. LLM_ARCH_QWEN2,
  921. {
  922. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  923. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  924. { LLM_TENSOR_OUTPUT, "output" },
  925. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  926. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  927. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  928. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  929. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  930. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  931. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  932. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  933. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  934. },
  935. },
  936. {
  937. LLM_ARCH_QWEN2VL,
  938. {
  939. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  940. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  941. { LLM_TENSOR_OUTPUT, "output" },
  942. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  943. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  944. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  945. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  946. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  947. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  948. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  949. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  950. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  951. },
  952. },
  953. {
  954. LLM_ARCH_QWEN2MOE,
  955. {
  956. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  957. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  958. { LLM_TENSOR_OUTPUT, "output" },
  959. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  960. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  961. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  962. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  963. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  964. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  965. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  966. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  967. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  968. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  969. { LLM_TENSOR_FFN_GATE_INP_SHEXP, "blk.%d.ffn_gate_inp_shexp" },
  970. { LLM_TENSOR_FFN_GATE_SHEXP, "blk.%d.ffn_gate_shexp" },
  971. { LLM_TENSOR_FFN_DOWN_SHEXP, "blk.%d.ffn_down_shexp" },
  972. { LLM_TENSOR_FFN_UP_SHEXP, "blk.%d.ffn_up_shexp" },
  973. },
  974. },
  975. {
  976. LLM_ARCH_PHI2,
  977. {
  978. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  979. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  980. { LLM_TENSOR_OUTPUT, "output" },
  981. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  982. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  983. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  984. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  985. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  986. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  987. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  988. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  989. },
  990. },
  991. {
  992. LLM_ARCH_PHI3,
  993. {
  994. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  995. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  996. { LLM_TENSOR_OUTPUT, "output" },
  997. { LLM_TENSOR_ROPE_FACTORS_LONG, "rope_factors_long" },
  998. { LLM_TENSOR_ROPE_FACTORS_SHORT, "rope_factors_short" },
  999. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1000. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1001. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1002. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1003. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1004. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1005. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1006. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1007. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1008. },
  1009. },
  1010. {
  1011. LLM_ARCH_PLAMO,
  1012. {
  1013. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1014. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1015. { LLM_TENSOR_OUTPUT, "output" },
  1016. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1017. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1018. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1019. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1020. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1021. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1022. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1023. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1024. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1025. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1026. },
  1027. },
  1028. {
  1029. LLM_ARCH_CODESHELL,
  1030. {
  1031. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1032. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1033. { LLM_TENSOR_OUTPUT, "output" },
  1034. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1035. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1036. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1037. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1038. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1039. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1040. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1041. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1042. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1043. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1044. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1045. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1046. },
  1047. },
  1048. {
  1049. LLM_ARCH_ORION,
  1050. {
  1051. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1052. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1053. { LLM_TENSOR_OUTPUT, "output" },
  1054. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1055. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1056. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1057. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1058. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1059. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1060. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1061. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1062. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1063. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1064. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1065. },
  1066. },
  1067. {
  1068. LLM_ARCH_INTERNLM2,
  1069. {
  1070. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1071. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1072. { LLM_TENSOR_OUTPUT, "output" },
  1073. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1074. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1075. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1076. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1077. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1078. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1079. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1080. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1081. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1082. },
  1083. },
  1084. {
  1085. LLM_ARCH_MINICPM,
  1086. {
  1087. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1088. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1089. { LLM_TENSOR_OUTPUT, "output" },
  1090. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1091. { LLM_TENSOR_ROPE_FACTORS_LONG, "rope_factors_long" },
  1092. { LLM_TENSOR_ROPE_FACTORS_SHORT, "rope_factors_short" },
  1093. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1094. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1095. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1096. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1097. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1098. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1099. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1100. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1101. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1102. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1103. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1104. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  1105. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  1106. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  1107. },
  1108. },
  1109. {
  1110. LLM_ARCH_MINICPM3,
  1111. {
  1112. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1113. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1114. { LLM_TENSOR_OUTPUT, "output" },
  1115. { LLM_TENSOR_ROPE_FACTORS_LONG, "rope_factors_long" },
  1116. { LLM_TENSOR_ROPE_FACTORS_SHORT, "rope_factors_short" },
  1117. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1118. { LLM_TENSOR_ATTN_Q_A_NORM, "blk.%d.attn_q_a_norm" },
  1119. { LLM_TENSOR_ATTN_KV_A_NORM, "blk.%d.attn_kv_a_norm" },
  1120. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1121. { LLM_TENSOR_ATTN_Q_A, "blk.%d.attn_q_a" },
  1122. { LLM_TENSOR_ATTN_Q_B, "blk.%d.attn_q_b" },
  1123. { LLM_TENSOR_ATTN_KV_A_MQA, "blk.%d.attn_kv_a_mqa" },
  1124. { LLM_TENSOR_ATTN_KV_B, "blk.%d.attn_kv_b" },
  1125. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1126. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1127. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1128. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1129. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1130. },
  1131. },
  1132. {
  1133. LLM_ARCH_GEMMA,
  1134. {
  1135. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1136. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1137. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1138. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1139. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1140. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1141. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1142. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1143. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1144. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1145. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1146. },
  1147. },
  1148. {
  1149. LLM_ARCH_GEMMA2,
  1150. {
  1151. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1152. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1153. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1154. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1155. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1156. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1157. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1158. { LLM_TENSOR_ATTN_POST_NORM, "blk.%d.post_attention_norm" },
  1159. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1160. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1161. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1162. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1163. { LLM_TENSOR_FFN_POST_NORM, "blk.%d.post_ffw_norm" },
  1164. },
  1165. },
  1166. {
  1167. LLM_ARCH_STARCODER2,
  1168. {
  1169. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1170. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1171. { LLM_TENSOR_OUTPUT, "output" },
  1172. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1173. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1174. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1175. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1176. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1177. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1178. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1179. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1180. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1181. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1182. },
  1183. },
  1184. {
  1185. LLM_ARCH_MAMBA,
  1186. {
  1187. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1188. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1189. { LLM_TENSOR_OUTPUT, "output" },
  1190. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1191. { LLM_TENSOR_SSM_IN, "blk.%d.ssm_in" },
  1192. { LLM_TENSOR_SSM_CONV1D, "blk.%d.ssm_conv1d" },
  1193. { LLM_TENSOR_SSM_X, "blk.%d.ssm_x" },
  1194. { LLM_TENSOR_SSM_DT, "blk.%d.ssm_dt" },
  1195. { LLM_TENSOR_SSM_A, "blk.%d.ssm_a" },
  1196. { LLM_TENSOR_SSM_D, "blk.%d.ssm_d" },
  1197. { LLM_TENSOR_SSM_OUT, "blk.%d.ssm_out" },
  1198. },
  1199. },
  1200. {
  1201. LLM_ARCH_XVERSE,
  1202. {
  1203. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1204. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1205. { LLM_TENSOR_OUTPUT, "output" },
  1206. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1207. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1208. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1209. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1210. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1211. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1212. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1213. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1214. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1215. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1216. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1217. },
  1218. },
  1219. {
  1220. LLM_ARCH_COMMAND_R,
  1221. {
  1222. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1223. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1224. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1225. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1226. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1227. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1228. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1229. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1230. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1231. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1232. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  1233. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  1234. },
  1235. },
  1236. {
  1237. LLM_ARCH_DBRX,
  1238. {
  1239. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1240. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1241. { LLM_TENSOR_OUTPUT, "output" },
  1242. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1243. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1244. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1245. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  1246. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1247. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1248. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1249. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1250. },
  1251. },
  1252. {
  1253. LLM_ARCH_OLMO,
  1254. {
  1255. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1256. { LLM_TENSOR_OUTPUT, "output" },
  1257. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1258. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1259. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1260. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1261. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1262. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1263. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1264. },
  1265. },
  1266. {
  1267. LLM_ARCH_OLMO2,
  1268. {
  1269. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1270. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1271. { LLM_TENSOR_OUTPUT, "output" },
  1272. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1273. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1274. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1275. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1276. { LLM_TENSOR_ATTN_POST_NORM, "blk.%d.post_attention_norm" },
  1277. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  1278. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  1279. { LLM_TENSOR_FFN_POST_NORM, "blk.%d.post_ffw_norm" },
  1280. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1281. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1282. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1283. },
  1284. },
  1285. {
  1286. LLM_ARCH_OLMOE,
  1287. {
  1288. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1289. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1290. { LLM_TENSOR_OUTPUT, "output" },
  1291. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1292. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1293. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1294. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1295. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1296. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  1297. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  1298. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1299. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1300. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1301. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1302. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1303. },
  1304. },
  1305. {
  1306. LLM_ARCH_OPENELM,
  1307. {
  1308. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1309. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1310. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1311. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1312. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  1313. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  1314. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1315. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1316. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1317. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1318. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1319. },
  1320. },
  1321. {
  1322. LLM_ARCH_ARCTIC,
  1323. {
  1324. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1325. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1326. { LLM_TENSOR_OUTPUT, "output" },
  1327. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1328. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1329. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1330. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1331. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1332. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1333. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1334. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1335. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1336. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1337. { LLM_TENSOR_FFN_NORM_EXPS, "blk.%d.ffn_norm_exps" },
  1338. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1339. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1340. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1341. },
  1342. },
  1343. {
  1344. LLM_ARCH_DEEPSEEK2,
  1345. {
  1346. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1347. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1348. { LLM_TENSOR_OUTPUT, "output" },
  1349. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1350. { LLM_TENSOR_ATTN_Q_A_NORM, "blk.%d.attn_q_a_norm" },
  1351. { LLM_TENSOR_ATTN_KV_A_NORM, "blk.%d.attn_kv_a_norm" },
  1352. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1353. { LLM_TENSOR_ATTN_Q_A, "blk.%d.attn_q_a" },
  1354. { LLM_TENSOR_ATTN_Q_B, "blk.%d.attn_q_b" },
  1355. { LLM_TENSOR_ATTN_KV_A_MQA, "blk.%d.attn_kv_a_mqa" },
  1356. { LLM_TENSOR_ATTN_KV_B, "blk.%d.attn_kv_b" },
  1357. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1358. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1359. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1360. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1361. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1362. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1363. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1364. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1365. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1366. { LLM_TENSOR_FFN_GATE_INP_SHEXP, "blk.%d.ffn_gate_inp_shexp" },
  1367. { LLM_TENSOR_FFN_GATE_SHEXP, "blk.%d.ffn_gate_shexp" },
  1368. { LLM_TENSOR_FFN_DOWN_SHEXP, "blk.%d.ffn_down_shexp" },
  1369. { LLM_TENSOR_FFN_UP_SHEXP, "blk.%d.ffn_up_shexp" },
  1370. },
  1371. },
  1372. {
  1373. LLM_ARCH_CHATGLM,
  1374. {
  1375. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1376. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1377. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1378. { LLM_TENSOR_OUTPUT, "output" },
  1379. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1380. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1381. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1382. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1383. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1384. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1385. },
  1386. },
  1387. {
  1388. LLM_ARCH_BITNET,
  1389. {
  1390. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1391. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1392. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1393. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1394. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1395. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1396. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1397. { LLM_TENSOR_ATTN_SUB_NORM, "blk.%d.attn_sub_norm" },
  1398. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1399. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1400. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1401. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1402. { LLM_TENSOR_FFN_SUB_NORM, "blk.%d.ffn_sub_norm" },
  1403. },
  1404. },
  1405. {
  1406. LLM_ARCH_T5,
  1407. {
  1408. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1409. { LLM_TENSOR_OUTPUT, "output" },
  1410. { LLM_TENSOR_DEC_OUTPUT_NORM, "dec.output_norm" },
  1411. { LLM_TENSOR_DEC_ATTN_NORM, "dec.blk.%d.attn_norm" },
  1412. { LLM_TENSOR_DEC_ATTN_Q, "dec.blk.%d.attn_q" },
  1413. { LLM_TENSOR_DEC_ATTN_K, "dec.blk.%d.attn_k" },
  1414. { LLM_TENSOR_DEC_ATTN_V, "dec.blk.%d.attn_v" },
  1415. { LLM_TENSOR_DEC_ATTN_OUT, "dec.blk.%d.attn_o" },
  1416. { LLM_TENSOR_DEC_ATTN_REL_B, "dec.blk.%d.attn_rel_b" },
  1417. { LLM_TENSOR_DEC_CROSS_ATTN_NORM, "dec.blk.%d.cross_attn_norm" },
  1418. { LLM_TENSOR_DEC_CROSS_ATTN_Q, "dec.blk.%d.cross_attn_q" },
  1419. { LLM_TENSOR_DEC_CROSS_ATTN_K, "dec.blk.%d.cross_attn_k" },
  1420. { LLM_TENSOR_DEC_CROSS_ATTN_V, "dec.blk.%d.cross_attn_v" },
  1421. { LLM_TENSOR_DEC_CROSS_ATTN_OUT, "dec.blk.%d.cross_attn_o" },
  1422. { LLM_TENSOR_DEC_CROSS_ATTN_REL_B, "dec.blk.%d.cross_attn_rel_b" },
  1423. { LLM_TENSOR_DEC_FFN_NORM, "dec.blk.%d.ffn_norm" },
  1424. { LLM_TENSOR_DEC_FFN_GATE, "dec.blk.%d.ffn_gate" },
  1425. { LLM_TENSOR_DEC_FFN_DOWN, "dec.blk.%d.ffn_down" },
  1426. { LLM_TENSOR_DEC_FFN_UP, "dec.blk.%d.ffn_up" },
  1427. { LLM_TENSOR_ENC_OUTPUT_NORM, "enc.output_norm" },
  1428. { LLM_TENSOR_ENC_ATTN_NORM, "enc.blk.%d.attn_norm" },
  1429. { LLM_TENSOR_ENC_ATTN_Q, "enc.blk.%d.attn_q" },
  1430. { LLM_TENSOR_ENC_ATTN_K, "enc.blk.%d.attn_k" },
  1431. { LLM_TENSOR_ENC_ATTN_V, "enc.blk.%d.attn_v" },
  1432. { LLM_TENSOR_ENC_ATTN_OUT, "enc.blk.%d.attn_o" },
  1433. { LLM_TENSOR_ENC_ATTN_REL_B, "enc.blk.%d.attn_rel_b" },
  1434. { LLM_TENSOR_ENC_FFN_NORM, "enc.blk.%d.ffn_norm" },
  1435. { LLM_TENSOR_ENC_FFN_GATE, "enc.blk.%d.ffn_gate" },
  1436. { LLM_TENSOR_ENC_FFN_DOWN, "enc.blk.%d.ffn_down" },
  1437. { LLM_TENSOR_ENC_FFN_UP, "enc.blk.%d.ffn_up" },
  1438. },
  1439. },
  1440. {
  1441. LLM_ARCH_T5ENCODER,
  1442. {
  1443. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1444. { LLM_TENSOR_OUTPUT, "output" },
  1445. { LLM_TENSOR_ENC_OUTPUT_NORM, "enc.output_norm" },
  1446. { LLM_TENSOR_ENC_ATTN_NORM, "enc.blk.%d.attn_norm" },
  1447. { LLM_TENSOR_ENC_ATTN_Q, "enc.blk.%d.attn_q" },
  1448. { LLM_TENSOR_ENC_ATTN_K, "enc.blk.%d.attn_k" },
  1449. { LLM_TENSOR_ENC_ATTN_V, "enc.blk.%d.attn_v" },
  1450. { LLM_TENSOR_ENC_ATTN_OUT, "enc.blk.%d.attn_o" },
  1451. { LLM_TENSOR_ENC_ATTN_REL_B, "enc.blk.%d.attn_rel_b" },
  1452. { LLM_TENSOR_ENC_FFN_NORM, "enc.blk.%d.ffn_norm" },
  1453. { LLM_TENSOR_ENC_FFN_GATE, "enc.blk.%d.ffn_gate" },
  1454. { LLM_TENSOR_ENC_FFN_DOWN, "enc.blk.%d.ffn_down" },
  1455. { LLM_TENSOR_ENC_FFN_UP, "enc.blk.%d.ffn_up" },
  1456. },
  1457. },
  1458. {
  1459. LLM_ARCH_JAIS,
  1460. {
  1461. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1462. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1463. { LLM_TENSOR_OUTPUT, "output" },
  1464. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1465. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1466. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1467. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1468. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1469. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1470. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1471. },
  1472. },
  1473. {
  1474. LLM_ARCH_NEMOTRON,
  1475. {
  1476. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1477. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1478. { LLM_TENSOR_OUTPUT, "output" },
  1479. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1480. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1481. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1482. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1483. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1484. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1485. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1486. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1487. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1488. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1489. },
  1490. },
  1491. {
  1492. LLM_ARCH_EXAONE,
  1493. {
  1494. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1495. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1496. { LLM_TENSOR_OUTPUT, "output" },
  1497. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1498. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1499. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1500. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1501. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1502. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1503. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1504. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1505. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1506. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1507. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1508. },
  1509. },
  1510. {
  1511. LLM_ARCH_RWKV6,
  1512. {
  1513. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1514. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  1515. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1516. { LLM_TENSOR_OUTPUT, "output" },
  1517. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1518. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  1519. { LLM_TENSOR_TIME_MIX_W1, "blk.%d.time_mix_w1" },
  1520. { LLM_TENSOR_TIME_MIX_W2, "blk.%d.time_mix_w2" },
  1521. { LLM_TENSOR_TIME_MIX_LERP_X, "blk.%d.time_mix_lerp_x" },
  1522. { LLM_TENSOR_TIME_MIX_LERP_W, "blk.%d.time_mix_lerp_w" },
  1523. { LLM_TENSOR_TIME_MIX_LERP_K, "blk.%d.time_mix_lerp_k" },
  1524. { LLM_TENSOR_TIME_MIX_LERP_V, "blk.%d.time_mix_lerp_v" },
  1525. { LLM_TENSOR_TIME_MIX_LERP_R, "blk.%d.time_mix_lerp_r" },
  1526. { LLM_TENSOR_TIME_MIX_LERP_G, "blk.%d.time_mix_lerp_g" },
  1527. { LLM_TENSOR_TIME_MIX_FIRST, "blk.%d.time_mix_first" },
  1528. { LLM_TENSOR_TIME_MIX_DECAY, "blk.%d.time_mix_decay" },
  1529. { LLM_TENSOR_TIME_MIX_DECAY_W1, "blk.%d.time_mix_decay_w1" },
  1530. { LLM_TENSOR_TIME_MIX_DECAY_W2, "blk.%d.time_mix_decay_w2" },
  1531. { LLM_TENSOR_TIME_MIX_KEY, "blk.%d.time_mix_key" },
  1532. { LLM_TENSOR_TIME_MIX_VALUE, "blk.%d.time_mix_value" },
  1533. { LLM_TENSOR_TIME_MIX_RECEPTANCE, "blk.%d.time_mix_receptance" },
  1534. { LLM_TENSOR_TIME_MIX_GATE, "blk.%d.time_mix_gate" },
  1535. { LLM_TENSOR_TIME_MIX_LN, "blk.%d.time_mix_ln" },
  1536. { LLM_TENSOR_TIME_MIX_OUTPUT, "blk.%d.time_mix_output" },
  1537. { LLM_TENSOR_CHANNEL_MIX_LERP_K, "blk.%d.channel_mix_lerp_k" },
  1538. { LLM_TENSOR_CHANNEL_MIX_LERP_R, "blk.%d.channel_mix_lerp_r" },
  1539. { LLM_TENSOR_CHANNEL_MIX_KEY, "blk.%d.channel_mix_key" },
  1540. { LLM_TENSOR_CHANNEL_MIX_VALUE, "blk.%d.channel_mix_value" },
  1541. { LLM_TENSOR_CHANNEL_MIX_RECEPTANCE, "blk.%d.channel_mix_receptance" },
  1542. },
  1543. },
  1544. {
  1545. LLM_ARCH_GRANITE,
  1546. {
  1547. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1548. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1549. { LLM_TENSOR_OUTPUT, "output" },
  1550. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1551. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1552. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1553. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1554. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1555. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1556. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1557. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1558. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1559. },
  1560. },
  1561. {
  1562. LLM_ARCH_GRANITE_MOE,
  1563. {
  1564. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1565. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1566. { LLM_TENSOR_OUTPUT, "output" },
  1567. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1568. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1569. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1570. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1571. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1572. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1573. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1574. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1575. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1576. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1577. },
  1578. },
  1579. {
  1580. LLM_ARCH_CHAMELEON,
  1581. {
  1582. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1583. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1584. { LLM_TENSOR_OUTPUT, "output" },
  1585. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1586. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1587. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1588. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1589. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1590. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1591. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1592. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1593. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1594. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  1595. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  1596. },
  1597. },
  1598. {
  1599. LLM_ARCH_SOLAR,
  1600. {
  1601. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1602. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1603. { LLM_TENSOR_OUTPUT, "output" },
  1604. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1605. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1606. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1607. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1608. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1609. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1610. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1611. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1612. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1613. { LLM_TENSOR_BSKCN_TV, "bskcn_tv" },
  1614. },
  1615. },
  1616. {
  1617. LLM_ARCH_UNKNOWN,
  1618. {
  1619. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1620. },
  1621. },
  1622. };
  1623. enum llm_chat_template {
  1624. LLM_CHAT_TEMPLATE_CHATML,
  1625. LLM_CHAT_TEMPLATE_LLAMA_2,
  1626. LLM_CHAT_TEMPLATE_LLAMA_2_SYS,
  1627. LLM_CHAT_TEMPLATE_LLAMA_2_SYS_BOS,
  1628. LLM_CHAT_TEMPLATE_LLAMA_2_SYS_STRIP,
  1629. LLM_CHAT_TEMPLATE_MISTRAL_V1,
  1630. LLM_CHAT_TEMPLATE_MISTRAL_V3,
  1631. LLM_CHAT_TEMPLATE_MISTRAL_V3_TEKKEN,
  1632. LLM_CHAT_TEMPLATE_MISTRAL_V7,
  1633. LLM_CHAT_TEMPLATE_PHI_3,
  1634. LLM_CHAT_TEMPLATE_ZEPHYR,
  1635. LLM_CHAT_TEMPLATE_MONARCH,
  1636. LLM_CHAT_TEMPLATE_GEMMA,
  1637. LLM_CHAT_TEMPLATE_ORION,
  1638. LLM_CHAT_TEMPLATE_OPENCHAT,
  1639. LLM_CHAT_TEMPLATE_VICUNA,
  1640. LLM_CHAT_TEMPLATE_VICUNA_ORCA,
  1641. LLM_CHAT_TEMPLATE_DEEPSEEK,
  1642. LLM_CHAT_TEMPLATE_DEEPSEEK_2,
  1643. LLM_CHAT_TEMPLATE_COMMAND_R,
  1644. LLM_CHAT_TEMPLATE_LLAMA_3,
  1645. LLM_CHAT_TEMPLATE_CHATGML_3,
  1646. LLM_CHAT_TEMPLATE_CHATGML_4,
  1647. LLM_CHAT_TEMPLATE_MINICPM,
  1648. LLM_CHAT_TEMPLATE_EXAONE_3,
  1649. LLM_CHAT_TEMPLATE_RWKV_WORLD,
  1650. LLM_CHAT_TEMPLATE_GRANITE,
  1651. LLM_CHAT_TEMPLATE_UNKNOWN,
  1652. };
  1653. static const std::map<std::string, llm_chat_template> LLM_CHAT_TEMPLATES = {
  1654. { "chatml", LLM_CHAT_TEMPLATE_CHATML },
  1655. { "llama2", LLM_CHAT_TEMPLATE_LLAMA_2 },
  1656. { "llama2-sys", LLM_CHAT_TEMPLATE_LLAMA_2_SYS },
  1657. { "llama2-sys-bos", LLM_CHAT_TEMPLATE_LLAMA_2_SYS_BOS },
  1658. { "llama2-sys-strip", LLM_CHAT_TEMPLATE_LLAMA_2_SYS_STRIP },
  1659. { "mistral-v1", LLM_CHAT_TEMPLATE_MISTRAL_V1 },
  1660. { "mistral-v3", LLM_CHAT_TEMPLATE_MISTRAL_V3 },
  1661. { "mistral-v3-tekken", LLM_CHAT_TEMPLATE_MISTRAL_V3_TEKKEN },
  1662. { "mistral-v7", LLM_CHAT_TEMPLATE_MISTRAL_V7 },
  1663. { "phi3", LLM_CHAT_TEMPLATE_PHI_3 },
  1664. { "zephyr", LLM_CHAT_TEMPLATE_ZEPHYR },
  1665. { "monarch", LLM_CHAT_TEMPLATE_MONARCH },
  1666. { "gemma", LLM_CHAT_TEMPLATE_GEMMA },
  1667. { "orion", LLM_CHAT_TEMPLATE_ORION },
  1668. { "openchat", LLM_CHAT_TEMPLATE_OPENCHAT },
  1669. { "vicuna", LLM_CHAT_TEMPLATE_VICUNA },
  1670. { "vicuna-orca", LLM_CHAT_TEMPLATE_VICUNA_ORCA },
  1671. { "deepseek", LLM_CHAT_TEMPLATE_DEEPSEEK },
  1672. { "deepseek2", LLM_CHAT_TEMPLATE_DEEPSEEK_2 },
  1673. { "command-r", LLM_CHAT_TEMPLATE_COMMAND_R },
  1674. { "llama3", LLM_CHAT_TEMPLATE_LLAMA_3 },
  1675. { "chatglm3", LLM_CHAT_TEMPLATE_CHATGML_3 },
  1676. { "chatglm4", LLM_CHAT_TEMPLATE_CHATGML_4 },
  1677. { "minicpm", LLM_CHAT_TEMPLATE_MINICPM },
  1678. { "exaone3", LLM_CHAT_TEMPLATE_EXAONE_3 },
  1679. { "rwkv-world", LLM_CHAT_TEMPLATE_RWKV_WORLD },
  1680. { "granite", LLM_CHAT_TEMPLATE_GRANITE },
  1681. };
  1682. static llm_arch llm_arch_from_string(const std::string & name) {
  1683. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  1684. if (kv.second == name) {
  1685. return kv.first;
  1686. }
  1687. }
  1688. return LLM_ARCH_UNKNOWN;
  1689. }
  1690. // helper to handle gguf constants
  1691. // usage:
  1692. //
  1693. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  1694. //
  1695. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  1696. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  1697. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  1698. //
  1699. struct LLM_TN_IMPL {
  1700. const llm_arch arch;
  1701. const llm_tensor tensor;
  1702. const char * const suffix;
  1703. const int bid;
  1704. const int xid;
  1705. std::string str() const {
  1706. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1707. return "__missing__";
  1708. }
  1709. std::string name = ::format(LLM_TENSOR_NAMES.at(arch).at(tensor), bid, xid);
  1710. if (suffix != nullptr) {
  1711. name += ".";
  1712. name += suffix;
  1713. }
  1714. return name;
  1715. }
  1716. operator std::string() const {
  1717. return str();
  1718. }
  1719. friend bool operator==(const std::string & str, const LLM_TN_IMPL & tn) {
  1720. return str == tn.str();
  1721. }
  1722. friend bool operator!=(const std::string & str, const LLM_TN_IMPL & tn) {
  1723. return str != tn.str();
  1724. }
  1725. };
  1726. struct LLM_TN {
  1727. LLM_TN(llm_arch arch) : arch(arch) {}
  1728. llm_arch arch;
  1729. LLM_TN_IMPL operator()(llm_tensor tensor, const char * suffix, int bid = -1, int xid = -1) const {
  1730. return { arch, tensor, suffix, bid, xid };
  1731. }
  1732. LLM_TN_IMPL operator()(llm_tensor tensor, int bid = -1, int xid = -1) const {
  1733. return { arch, tensor, nullptr, bid, xid };
  1734. }
  1735. };
  1736. //
  1737. // gguf helpers
  1738. //
  1739. static const std::map<llama_rope_scaling_type, const char *> LLAMA_ROPE_SCALING_TYPES = {
  1740. { LLAMA_ROPE_SCALING_TYPE_NONE, "none" },
  1741. { LLAMA_ROPE_SCALING_TYPE_LINEAR, "linear" },
  1742. { LLAMA_ROPE_SCALING_TYPE_YARN, "yarn" },
  1743. { LLAMA_ROPE_SCALING_TYPE_LONGROPE, "longrope" },
  1744. };
  1745. static llama_rope_scaling_type llama_rope_scaling_type_from_string(const std::string & name) {
  1746. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  1747. if (kv.second == name) {
  1748. return (llama_rope_scaling_type) kv.first;
  1749. }
  1750. }
  1751. return LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
  1752. }
  1753. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  1754. switch (type) {
  1755. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  1756. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  1757. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  1758. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  1759. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  1760. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  1761. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  1762. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  1763. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  1764. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  1765. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  1766. default: return format("unknown type %d", type);
  1767. }
  1768. }
  1769. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  1770. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  1771. switch (type) {
  1772. case GGUF_TYPE_STRING:
  1773. return gguf_get_val_str(ctx_gguf, i);
  1774. case GGUF_TYPE_ARRAY:
  1775. {
  1776. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  1777. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  1778. const void * data = gguf_get_arr_data(ctx_gguf, i);
  1779. std::stringstream ss;
  1780. ss << "[";
  1781. for (int j = 0; j < arr_n; j++) {
  1782. if (arr_type == GGUF_TYPE_STRING) {
  1783. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  1784. // escape quotes
  1785. replace_all(val, "\\", "\\\\");
  1786. replace_all(val, "\"", "\\\"");
  1787. ss << '"' << val << '"';
  1788. } else if (arr_type == GGUF_TYPE_ARRAY) {
  1789. ss << "???";
  1790. } else {
  1791. ss << gguf_data_to_str(arr_type, data, j);
  1792. }
  1793. if (j < arr_n - 1) {
  1794. ss << ", ";
  1795. }
  1796. }
  1797. ss << "]";
  1798. return ss.str();
  1799. }
  1800. default:
  1801. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  1802. }
  1803. }
  1804. //
  1805. // llama helpers
  1806. //
  1807. #if defined(_WIN32)
  1808. static std::string llama_format_win_err(DWORD err) {
  1809. LPSTR buf;
  1810. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1811. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  1812. if (!size) {
  1813. return "FormatMessageA failed";
  1814. }
  1815. std::string ret(buf, size);
  1816. LocalFree(buf);
  1817. return ret;
  1818. }
  1819. #endif
  1820. template <typename T>
  1821. struct no_init {
  1822. T value;
  1823. no_init() { /* do nothing */ }
  1824. };
  1825. struct llama_file {
  1826. #if defined(_WIN32)
  1827. // use FILE * so we don't have to re-open the file to mmap
  1828. FILE * fp;
  1829. HANDLE fp_win32;
  1830. size_t size;
  1831. private:
  1832. std::string GetErrorMessageWin32(DWORD error_code) const {
  1833. std::string ret;
  1834. LPSTR lpMsgBuf = NULL;
  1835. DWORD bufLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1836. NULL, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lpMsgBuf, 0, NULL);
  1837. if (!bufLen) {
  1838. ret = format("Win32 error code: %lx", error_code);
  1839. } else {
  1840. ret = lpMsgBuf;
  1841. LocalFree(lpMsgBuf);
  1842. }
  1843. return ret;
  1844. }
  1845. public:
  1846. llama_file(const char * fname, const char * mode) {
  1847. fp = ggml_fopen(fname, mode);
  1848. if (fp == NULL) {
  1849. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  1850. }
  1851. fp_win32 = (HANDLE) _get_osfhandle(_fileno(fp));
  1852. seek(0, SEEK_END);
  1853. size = tell();
  1854. seek(0, SEEK_SET);
  1855. }
  1856. size_t tell() const {
  1857. // SetFilePointerEx returns the current position when seeking relative 0 bytes
  1858. LARGE_INTEGER li;
  1859. li.QuadPart = 0;
  1860. BOOL ret = SetFilePointerEx(fp_win32, li, &li, FILE_CURRENT);
  1861. if (!ret) {
  1862. throw std::runtime_error(format("read error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1863. }
  1864. return li.QuadPart;
  1865. }
  1866. void seek(size_t offset, int whence) const {
  1867. // no need to convert SEEK_* to FILE_*. The enums are the same.
  1868. // Still, keep static asserts to avoid failures in the future.
  1869. static_assert(SEEK_SET == FILE_BEGIN, "SEEK_SET != FILE_BEGIN");
  1870. static_assert(SEEK_CUR == FILE_CURRENT, "SEEK_CUR != FILE_CURRENT");
  1871. static_assert(SEEK_END == FILE_END, "SEEK_END != FILE_END");
  1872. LARGE_INTEGER li;
  1873. li.QuadPart = offset;
  1874. BOOL ret = SetFilePointerEx(fp_win32, li, NULL, whence);
  1875. if (!ret) {
  1876. throw std::runtime_error(format("read error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1877. }
  1878. }
  1879. void read_raw(void * ptr, size_t len) const {
  1880. // On Win32 ReadFile is significant faster than fread which is again significant faster than std::fstream. Thus
  1881. // use the Win32 API to do file io instead of the C/C++ library functions.
  1882. // There are conditions under which ReadFile cannot read chunks >64MB.
  1883. // Thus split the operation into smaller chunks if len exceeds this limit.
  1884. size_t bytes_read = 0;
  1885. while (bytes_read < len) {
  1886. size_t chunk_size = std::min<size_t>(len - bytes_read, 64*1024*1024);
  1887. DWORD chunk_read = 0;
  1888. BOOL result = ReadFile(fp_win32, reinterpret_cast<char*>(ptr) + bytes_read, chunk_size, &chunk_read, NULL);
  1889. if (!result) {
  1890. throw std::runtime_error(format("read error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1891. }
  1892. if (chunk_read < chunk_size || chunk_read == 0) {
  1893. throw std::runtime_error("unexpectedly reached end of file");
  1894. }
  1895. bytes_read += chunk_read;
  1896. } ;
  1897. }
  1898. uint32_t read_u32() const {
  1899. uint32_t val;
  1900. read_raw(&val, sizeof(val));
  1901. return val;
  1902. }
  1903. void write_raw(const void * ptr, size_t len) const {
  1904. // There are conditions under which WriteFile cannot write chunks >64MB.
  1905. // Thus split the operation into smaller chunks if len exceeds this limit.
  1906. size_t bytes_written = 0;
  1907. while (bytes_written < len) {
  1908. size_t chunk_size = std::min<size_t>(len - bytes_written, 64*1024*1024);
  1909. DWORD chunk_written = 0;
  1910. BOOL result = WriteFile(fp_win32, reinterpret_cast<char const*>(ptr) + bytes_written, chunk_size, &chunk_written, NULL);
  1911. if (!result) {
  1912. throw std::runtime_error(format("write error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1913. }
  1914. if (chunk_written < chunk_size || chunk_written == 0) {
  1915. throw std::runtime_error("unexpectedly failed to write bytes");
  1916. }
  1917. bytes_written += chunk_written;
  1918. }
  1919. }
  1920. void write_u32(std::uint32_t val) const {
  1921. write_raw(&val, sizeof(val));
  1922. }
  1923. ~llama_file() {
  1924. if (fp) {
  1925. std::fclose(fp);
  1926. }
  1927. }
  1928. #else
  1929. // use FILE * so we don't have to re-open the file to mmap
  1930. FILE * fp;
  1931. size_t size;
  1932. llama_file(const char * fname, const char * mode) {
  1933. fp = ggml_fopen(fname, mode);
  1934. if (fp == NULL) {
  1935. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  1936. }
  1937. seek(0, SEEK_END);
  1938. size = tell();
  1939. seek(0, SEEK_SET);
  1940. }
  1941. size_t tell() const {
  1942. #ifdef _WIN32
  1943. __int64 ret = _ftelli64(fp);
  1944. #else
  1945. long ret = std::ftell(fp);
  1946. #endif
  1947. if (ret == -1) {
  1948. throw std::runtime_error(format("ftell error: %s", strerror(errno)));
  1949. }
  1950. return (size_t) ret;
  1951. }
  1952. void seek(size_t offset, int whence) const {
  1953. #ifdef _WIN32
  1954. int ret = _fseeki64(fp, (__int64) offset, whence);
  1955. #else
  1956. int ret = std::fseek(fp, (long) offset, whence);
  1957. #endif
  1958. if (ret != 0) {
  1959. throw std::runtime_error(format("seek error: %s", strerror(errno)));
  1960. }
  1961. }
  1962. void read_raw(void * ptr, size_t len) const {
  1963. if (len == 0) {
  1964. return;
  1965. }
  1966. errno = 0;
  1967. std::size_t ret = std::fread(ptr, len, 1, fp);
  1968. if (ferror(fp)) {
  1969. throw std::runtime_error(format("read error: %s", strerror(errno)));
  1970. }
  1971. if (ret != 1) {
  1972. throw std::runtime_error("unexpectedly reached end of file");
  1973. }
  1974. }
  1975. uint32_t read_u32() const {
  1976. uint32_t ret;
  1977. read_raw(&ret, sizeof(ret));
  1978. return ret;
  1979. }
  1980. void write_raw(const void * ptr, size_t len) const {
  1981. if (len == 0) {
  1982. return;
  1983. }
  1984. errno = 0;
  1985. size_t ret = std::fwrite(ptr, len, 1, fp);
  1986. if (ret != 1) {
  1987. throw std::runtime_error(format("write error: %s", strerror(errno)));
  1988. }
  1989. }
  1990. void write_u32(std::uint32_t val) const {
  1991. write_raw(&val, sizeof(val));
  1992. }
  1993. ~llama_file() {
  1994. if (fp) {
  1995. std::fclose(fp);
  1996. }
  1997. }
  1998. #endif
  1999. };
  2000. using llama_files = std::vector<std::unique_ptr<llama_file>>;
  2001. struct llama_mmap {
  2002. void * addr;
  2003. size_t size;
  2004. llama_mmap(const llama_mmap &) = delete;
  2005. #ifdef _POSIX_MAPPED_FILES
  2006. static constexpr bool SUPPORTED = true;
  2007. // list of mapped fragments (first_offset, last_offset)
  2008. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  2009. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  2010. size = file->size;
  2011. int fd = fileno(file->fp);
  2012. int flags = MAP_SHARED;
  2013. // prefetch/readahead impairs performance on NUMA systems
  2014. if (numa) { prefetch = 0; }
  2015. #ifdef __linux__
  2016. // advise the kernel to read the file sequentially (increases readahead)
  2017. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  2018. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  2019. strerror(errno));
  2020. }
  2021. if (prefetch) { flags |= MAP_POPULATE; }
  2022. #endif
  2023. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  2024. if (addr == MAP_FAILED) { // NOLINT
  2025. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  2026. }
  2027. if (prefetch > 0) {
  2028. // advise the kernel to preload the mapped memory
  2029. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  2030. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  2031. strerror(errno));
  2032. }
  2033. }
  2034. if (numa) {
  2035. // advise the kernel not to use readahead
  2036. // (because the next page might not belong on the same node)
  2037. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  2038. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  2039. strerror(errno));
  2040. }
  2041. }
  2042. // initialize list of mapped_fragments
  2043. mapped_fragments.emplace_back(0, file->size);
  2044. }
  2045. static void align_range(size_t * first, size_t * last, size_t page_size) {
  2046. // align first to the next page
  2047. size_t offset_in_page = *first & (page_size - 1);
  2048. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  2049. *first += offset_to_page;
  2050. // align last to the previous page
  2051. *last = *last & ~(page_size - 1);
  2052. if (*last <= *first) {
  2053. *last = *first;
  2054. }
  2055. }
  2056. // partially unmap the file in the range [first, last)
  2057. void unmap_fragment(size_t first, size_t last) {
  2058. // note: this function must not be called multiple times with overlapping ranges
  2059. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  2060. int page_size = sysconf(_SC_PAGESIZE);
  2061. align_range(&first, &last, page_size);
  2062. size_t len = last - first;
  2063. if (len == 0) {
  2064. return;
  2065. }
  2066. GGML_ASSERT(first % page_size == 0);
  2067. GGML_ASSERT(last % page_size == 0);
  2068. GGML_ASSERT(last > first);
  2069. void * next_page_start = (uint8_t *) addr + first;
  2070. // unmap the range
  2071. if (munmap(next_page_start, len)) {
  2072. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  2073. }
  2074. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  2075. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  2076. for (const auto & frag : mapped_fragments) {
  2077. if (frag.first < first && frag.second > last) {
  2078. // the range is in the middle of the fragment, split it
  2079. new_mapped_fragments.emplace_back(frag.first, first);
  2080. new_mapped_fragments.emplace_back(last, frag.second);
  2081. } else if (frag.first < first && frag.second > first) {
  2082. // the range starts in the middle of the fragment
  2083. new_mapped_fragments.emplace_back(frag.first, first);
  2084. } else if (frag.first < last && frag.second > last) {
  2085. // the range ends in the middle of the fragment
  2086. new_mapped_fragments.emplace_back(last, frag.second);
  2087. } else if (frag.first >= first && frag.second <= last) {
  2088. // the range covers the entire fragment
  2089. } else {
  2090. // the range is outside the fragment
  2091. new_mapped_fragments.push_back(frag);
  2092. }
  2093. }
  2094. mapped_fragments = std::move(new_mapped_fragments);
  2095. }
  2096. ~llama_mmap() {
  2097. for (const auto & frag : mapped_fragments) {
  2098. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  2099. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  2100. }
  2101. }
  2102. }
  2103. #elif defined(_WIN32)
  2104. static constexpr bool SUPPORTED = true;
  2105. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  2106. GGML_UNUSED(numa);
  2107. size = file->size;
  2108. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  2109. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  2110. if (hMapping == NULL) {
  2111. DWORD error = GetLastError();
  2112. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  2113. }
  2114. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  2115. DWORD error = GetLastError();
  2116. CloseHandle(hMapping);
  2117. if (addr == NULL) {
  2118. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  2119. }
  2120. if (prefetch > 0) {
  2121. #if _WIN32_WINNT >= 0x602
  2122. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  2123. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  2124. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  2125. // may fail on pre-Windows 8 systems
  2126. pPrefetchVirtualMemory = (decltype(pPrefetchVirtualMemory))(void *) GetProcAddress(hKernel32, "PrefetchVirtualMemory");
  2127. if (pPrefetchVirtualMemory) {
  2128. // advise the kernel to preload the mapped memory
  2129. WIN32_MEMORY_RANGE_ENTRY range;
  2130. range.VirtualAddress = addr;
  2131. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  2132. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  2133. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  2134. llama_format_win_err(GetLastError()).c_str());
  2135. }
  2136. }
  2137. #else
  2138. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  2139. #endif
  2140. }
  2141. }
  2142. void unmap_fragment(size_t first, size_t last) {
  2143. // not supported
  2144. GGML_UNUSED(first);
  2145. GGML_UNUSED(last);
  2146. }
  2147. ~llama_mmap() {
  2148. if (!UnmapViewOfFile(addr)) {
  2149. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  2150. llama_format_win_err(GetLastError()).c_str());
  2151. }
  2152. }
  2153. #else
  2154. static constexpr bool SUPPORTED = false;
  2155. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  2156. GGML_UNUSED(file);
  2157. GGML_UNUSED(prefetch);
  2158. GGML_UNUSED(numa);
  2159. throw std::runtime_error("mmap not supported");
  2160. }
  2161. void unmap_fragment(size_t first, size_t last) {
  2162. GGML_UNUSED(first);
  2163. GGML_UNUSED(last);
  2164. throw std::runtime_error("mmap not supported");
  2165. }
  2166. #endif
  2167. };
  2168. using llama_mmaps = std::vector<std::unique_ptr<llama_mmap>>;
  2169. // Represents some region of memory being locked using mlock or VirtualLock;
  2170. // will automatically unlock on destruction.
  2171. struct llama_mlock {
  2172. void * addr = NULL;
  2173. size_t size = 0;
  2174. bool failed_already = false;
  2175. llama_mlock() {}
  2176. llama_mlock(const llama_mlock &) = delete;
  2177. ~llama_mlock() {
  2178. if (size) {
  2179. raw_unlock(addr, size);
  2180. }
  2181. }
  2182. void init(void * ptr) {
  2183. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  2184. addr = ptr;
  2185. }
  2186. void grow_to(size_t target_size) {
  2187. GGML_ASSERT(addr);
  2188. if (failed_already) {
  2189. return;
  2190. }
  2191. size_t granularity = lock_granularity();
  2192. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  2193. if (target_size > size) {
  2194. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  2195. size = target_size;
  2196. } else {
  2197. failed_already = true;
  2198. }
  2199. }
  2200. }
  2201. #ifdef _POSIX_MEMLOCK_RANGE
  2202. static constexpr bool SUPPORTED = true;
  2203. static size_t lock_granularity() {
  2204. return (size_t) sysconf(_SC_PAGESIZE);
  2205. }
  2206. #ifdef __APPLE__
  2207. #define MLOCK_SUGGESTION \
  2208. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  2209. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  2210. #else
  2211. #define MLOCK_SUGGESTION \
  2212. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  2213. #endif
  2214. bool raw_lock(const void * addr, size_t size) const {
  2215. if (!mlock(addr, size)) {
  2216. return true;
  2217. }
  2218. char* errmsg = std::strerror(errno);
  2219. bool suggest = (errno == ENOMEM);
  2220. // Check if the resource limit is fine after all
  2221. struct rlimit lock_limit;
  2222. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  2223. suggest = false;
  2224. }
  2225. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  2226. suggest = false;
  2227. }
  2228. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  2229. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  2230. return false;
  2231. }
  2232. #undef MLOCK_SUGGESTION
  2233. static void raw_unlock(void * addr, size_t size) {
  2234. if (munlock(addr, size)) {
  2235. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  2236. }
  2237. }
  2238. #elif defined(_WIN32)
  2239. static constexpr bool SUPPORTED = true;
  2240. static size_t lock_granularity() {
  2241. SYSTEM_INFO si;
  2242. GetSystemInfo(&si);
  2243. return (size_t) si.dwPageSize;
  2244. }
  2245. bool raw_lock(void * ptr, size_t len) const {
  2246. for (int tries = 1; ; tries++) {
  2247. if (VirtualLock(ptr, len)) {
  2248. return true;
  2249. }
  2250. if (tries == 2) {
  2251. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  2252. len, size, llama_format_win_err(GetLastError()).c_str());
  2253. return false;
  2254. }
  2255. // It failed but this was only the first try; increase the working
  2256. // set size and try again.
  2257. SIZE_T min_ws_size, max_ws_size;
  2258. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  2259. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  2260. llama_format_win_err(GetLastError()).c_str());
  2261. return false;
  2262. }
  2263. // Per MSDN: "The maximum number of pages that a process can lock
  2264. // is equal to the number of pages in its minimum working set minus
  2265. // a small overhead."
  2266. // Hopefully a megabyte is enough overhead:
  2267. size_t increment = len + 1048576;
  2268. // The minimum must be <= the maximum, so we need to increase both:
  2269. min_ws_size += increment;
  2270. max_ws_size += increment;
  2271. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  2272. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  2273. llama_format_win_err(GetLastError()).c_str());
  2274. return false;
  2275. }
  2276. }
  2277. }
  2278. static void raw_unlock(void * ptr, size_t len) {
  2279. if (!VirtualUnlock(ptr, len)) {
  2280. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  2281. llama_format_win_err(GetLastError()).c_str());
  2282. }
  2283. }
  2284. #else
  2285. static constexpr bool SUPPORTED = false;
  2286. static size_t lock_granularity() {
  2287. return (size_t) 65536;
  2288. }
  2289. bool raw_lock(const void * addr, size_t len) const {
  2290. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  2291. return false;
  2292. }
  2293. static void raw_unlock(const void * addr, size_t len) {}
  2294. #endif
  2295. };
  2296. using llama_mlocks = std::vector<std::unique_ptr<llama_mlock>>;
  2297. // NOTE: avoid ever using this except for building the token_to_piece caches
  2298. static std::string llama_token_to_piece(const struct llama_model * model, llama_token token, bool special) {
  2299. std::string piece;
  2300. piece.resize(piece.capacity()); // using string internal cache
  2301. const int n_chars = llama_token_to_piece(model, token, &piece[0], piece.size(), 0, special);
  2302. if (n_chars < 0) {
  2303. piece.resize(-n_chars);
  2304. int check = llama_token_to_piece(model, token, &piece[0], piece.size(), 0, special);
  2305. GGML_ASSERT(check == -n_chars);
  2306. }
  2307. else {
  2308. piece.resize(n_chars);
  2309. }
  2310. return piece;
  2311. }
  2312. //
  2313. // globals
  2314. //
  2315. struct llama_logger_state {
  2316. ggml_log_callback log_callback = llama_log_callback_default;
  2317. void * log_callback_user_data = nullptr;
  2318. };
  2319. static llama_logger_state g_logger_state;
  2320. // available llama models
  2321. enum e_model {
  2322. MODEL_UNKNOWN,
  2323. MODEL_14M,
  2324. MODEL_17M,
  2325. MODEL_22M,
  2326. MODEL_33M,
  2327. MODEL_60M,
  2328. MODEL_70M,
  2329. MODEL_80M,
  2330. MODEL_109M,
  2331. MODEL_137M,
  2332. MODEL_160M,
  2333. MODEL_220M,
  2334. MODEL_250M,
  2335. MODEL_270M,
  2336. MODEL_335M,
  2337. MODEL_410M,
  2338. MODEL_450M,
  2339. MODEL_770M,
  2340. MODEL_780M,
  2341. MODEL_0_5B,
  2342. MODEL_1B,
  2343. MODEL_1_3B,
  2344. MODEL_1_4B,
  2345. MODEL_1_5B,
  2346. MODEL_1_6B,
  2347. MODEL_2B,
  2348. MODEL_2_8B,
  2349. MODEL_3B,
  2350. MODEL_4B,
  2351. MODEL_6B,
  2352. MODEL_6_9B,
  2353. MODEL_7B,
  2354. MODEL_8B,
  2355. MODEL_9B,
  2356. MODEL_11B,
  2357. MODEL_12B,
  2358. MODEL_13B,
  2359. MODEL_14B,
  2360. MODEL_15B,
  2361. MODEL_16B,
  2362. MODEL_20B,
  2363. MODEL_22B,
  2364. MODEL_30B,
  2365. MODEL_32B,
  2366. MODEL_34B,
  2367. MODEL_35B,
  2368. MODEL_40B,
  2369. MODEL_65B,
  2370. MODEL_70B,
  2371. MODEL_90B,
  2372. MODEL_236B,
  2373. MODEL_314B,
  2374. MODEL_SMALL,
  2375. MODEL_MEDIUM,
  2376. MODEL_LARGE,
  2377. MODEL_XL,
  2378. MODEL_A1_7B,
  2379. MODEL_A2_7B,
  2380. MODEL_8x7B,
  2381. MODEL_8x22B,
  2382. MODEL_16x12B,
  2383. MODEL_10B_128x3_66B,
  2384. MODEL_57B_A14B,
  2385. MODEL_27B,
  2386. };
  2387. static const size_t kiB = 1024;
  2388. static const size_t MiB = 1024*kiB;
  2389. static const size_t GiB = 1024*MiB;
  2390. struct llama_hparams {
  2391. bool vocab_only;
  2392. bool rope_finetuned;
  2393. bool use_par_res;
  2394. bool swin_norm;
  2395. uint32_t n_vocab;
  2396. uint32_t n_ctx_train; // context size the model was trained on
  2397. uint32_t n_embd;
  2398. uint32_t n_layer;
  2399. uint32_t n_rot;
  2400. uint32_t n_swa = 0; // sliding window attention (SWA)
  2401. 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
  2402. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  2403. uint32_t n_expert = 0;
  2404. uint32_t n_expert_used = 0;
  2405. uint32_t n_vocab_type = 0; // for BERT-style token types
  2406. uint32_t n_rel_attn_bkts = 0;
  2407. std::array<uint32_t, LLAMA_MAX_LAYERS> n_head_arr;
  2408. std::array<uint32_t, LLAMA_MAX_LAYERS> n_head_kv_arr;
  2409. std::array<uint32_t, LLAMA_MAX_LAYERS> n_ff_arr;
  2410. std::array<std::array<uint32_t, LLAMA_MAX_LAYERS>, 4> n_bskcn_arr;
  2411. std::array<uint32_t, LLAMA_MAX_LAYERS> cross_attn_layers;
  2412. uint32_t n_layer_dense_lead = 0;
  2413. uint32_t n_lora_q = 0;
  2414. uint32_t n_lora_kv = 0;
  2415. uint32_t n_ff_exp = 0;
  2416. uint32_t n_ff_shexp = 0;
  2417. uint32_t n_expert_shared = 0;
  2418. float expert_weights_scale = 0.0;
  2419. float f_norm_eps;
  2420. float f_norm_rms_eps;
  2421. float f_attn_logit_softcapping = 50.0f;
  2422. float f_final_logit_softcapping = 30.0f;
  2423. // for RWKV
  2424. uint32_t rescale_every_n_layers = 0;
  2425. uint32_t time_mix_extra_dim = 0;
  2426. uint32_t time_decay_extra_dim = 0;
  2427. uint32_t wkv_head_size = 0;
  2428. float rope_attn_factor = 1.0f;
  2429. float rope_freq_base_train;
  2430. float rope_freq_scale_train;
  2431. uint32_t n_ctx_orig_yarn;
  2432. float rope_yarn_log_mul;
  2433. int rope_sections[4];
  2434. // for State Space Models
  2435. uint32_t ssm_d_conv = 0;
  2436. uint32_t ssm_d_inner = 0;
  2437. uint32_t ssm_d_state = 0;
  2438. uint32_t ssm_dt_rank = 0;
  2439. bool ssm_dt_b_c_rms = false;
  2440. float f_clamp_kqv = 0.0f;
  2441. float f_max_alibi_bias = 0.0f;
  2442. float f_logit_scale = 0.0f;
  2443. // Additional scale factors (Granite/Granite MoE)
  2444. float f_residual_scale = 0.0f;
  2445. float f_embedding_scale = 0.0f;
  2446. float f_attention_scale = 0.0f;
  2447. bool causal_attn = true;
  2448. bool use_alibi = false;
  2449. bool attn_soft_cap = false;
  2450. // needed by encoder-decoder models (e.g. T5, FLAN-T5)
  2451. // ref: https://github.com/ggerganov/llama.cpp/pull/8141
  2452. llama_token dec_start_token_id = LLAMA_TOKEN_NULL;
  2453. enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_NONE;
  2454. enum llama_rope_type rope_type = LLAMA_ROPE_TYPE_NONE;
  2455. enum llama_rope_scaling_type rope_scaling_type_train = LLAMA_ROPE_SCALING_TYPE_NONE;
  2456. bool operator!=(const llama_hparams & other) const {
  2457. if (this->vocab_only != other.vocab_only) return true;
  2458. if (this->n_vocab != other.n_vocab) return true;
  2459. if (this->n_ctx_train != other.n_ctx_train) return true;
  2460. if (this->n_embd != other.n_embd) return true;
  2461. if (this->n_layer != other.n_layer) return true;
  2462. if (this->n_rot != other.n_rot) return true;
  2463. if (this->n_swa != other.n_swa) return true;
  2464. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  2465. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  2466. if (this->n_expert != other.n_expert) return true;
  2467. if (this->n_expert_used != other.n_expert_used) return true;
  2468. if (this->n_head_arr != other.n_head_arr) return true;
  2469. if (this->n_head_kv_arr != other.n_head_kv_arr) return true;
  2470. if (this->n_ff_arr != other.n_ff_arr) return true;
  2471. if (this->n_bskcn_arr != other.n_bskcn_arr) return true;
  2472. if (this->cross_attn_layers != other.cross_attn_layers) return true;
  2473. if (this->n_rel_attn_bkts != other.n_rel_attn_bkts) return true;
  2474. if (this->n_layer_dense_lead != other.n_layer_dense_lead) return true;
  2475. if (this->n_lora_q != other.n_lora_q) return true;
  2476. if (this->n_lora_kv != other.n_lora_kv) return true;
  2477. if (this->n_ff_exp != other.n_ff_exp) return true;
  2478. if (this->n_ff_shexp != other.n_ff_shexp) return true;
  2479. if (this->n_expert_shared != other.n_expert_shared) return true;
  2480. if (this->rope_finetuned != other.rope_finetuned) return true;
  2481. if (this->n_ctx_orig_yarn != other.n_ctx_orig_yarn) return true;
  2482. if (std::equal(std::begin(this->rope_sections),
  2483. std::end(this->rope_sections),
  2484. std::begin(other.rope_sections))) return true;
  2485. if (this->ssm_d_conv != other.ssm_d_conv) return true;
  2486. if (this->ssm_d_inner != other.ssm_d_inner) return true;
  2487. if (this->ssm_d_state != other.ssm_d_state) return true;
  2488. if (this->ssm_dt_rank != other.ssm_dt_rank) return true;
  2489. if (this->ssm_dt_b_c_rms != other.ssm_dt_b_c_rms) return true;
  2490. if (this->rescale_every_n_layers != other.rescale_every_n_layers) return true;
  2491. if (this->time_mix_extra_dim != other.time_mix_extra_dim) return true;
  2492. if (this->time_decay_extra_dim != other.time_decay_extra_dim) return true;
  2493. if (this->wkv_head_size != other.wkv_head_size) return true;
  2494. if (this->dec_start_token_id != other.dec_start_token_id) return true;
  2495. const float EPSILON = 1e-9f;
  2496. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  2497. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  2498. if (!is_float_close(this->rope_attn_factor, other.rope_attn_factor, EPSILON)) return true;
  2499. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  2500. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  2501. if (!is_float_close(this->expert_weights_scale, other.expert_weights_scale, EPSILON)) return true;
  2502. if (!is_float_close(this->rope_yarn_log_mul, other.rope_yarn_log_mul, EPSILON)) return true;
  2503. if (!is_float_close(this->f_residual_scale, other.f_residual_scale, EPSILON)) return true;
  2504. if (!is_float_close(this->f_embedding_scale, other.f_embedding_scale, EPSILON)) return true;
  2505. if (!is_float_close(this->f_attention_scale, other.f_attention_scale, EPSILON)) return true;
  2506. return false;
  2507. }
  2508. uint32_t n_head(uint32_t il = 0) const {
  2509. if (il < n_layer) {
  2510. return n_head_arr[il];
  2511. }
  2512. GGML_ABORT("fatal error");
  2513. }
  2514. uint32_t n_head_kv(uint32_t il = 0) const {
  2515. if (il < n_layer) {
  2516. return n_head_kv_arr[il];
  2517. }
  2518. GGML_ABORT("fatal error");
  2519. }
  2520. uint32_t n_ff(uint32_t il = 0) const {
  2521. if (il < n_layer) {
  2522. return n_ff_arr[il];
  2523. }
  2524. GGML_ABORT("fatal error");
  2525. }
  2526. uint32_t n_gqa(uint32_t il = 0) const {
  2527. const uint32_t n_head = this->n_head(il);
  2528. const uint32_t n_head_kv = this->n_head_kv(il);
  2529. if (n_head_kv == 0) {
  2530. return 0;
  2531. }
  2532. return n_head/n_head_kv;
  2533. }
  2534. uint32_t n_embd_k_gqa(uint32_t il = 0) const { // dimension of key embeddings across all k-v heads
  2535. const uint32_t n_head_kv = this->n_head_kv(il);
  2536. return n_embd_head_k * n_head_kv;
  2537. }
  2538. uint32_t n_embd_v_gqa(uint32_t il = 0) const { // dimension of value embeddings across all k-v heads
  2539. const uint32_t n_head_kv = this->n_head_kv(il);
  2540. return n_embd_head_v * n_head_kv;
  2541. }
  2542. uint32_t n_embd_k_s() const { // dimension of the rolling state embeddings
  2543. // corresponds to Mamba's conv_states size or RWKV's token_shift states size
  2544. if (wkv_head_size != 0) {
  2545. // for RWKV models
  2546. return 2 * n_embd;
  2547. } else {
  2548. // TODO: maybe support other convolution strides than 1
  2549. // NOTE: since the first column of the conv_state is shifted out each time, it's not actually needed
  2550. return (ssm_d_conv > 0 ? ssm_d_conv - 1 : 0) * ssm_d_inner;
  2551. }
  2552. }
  2553. uint32_t n_embd_v_s() const { // dimension of the recurrent state embeddings
  2554. if (wkv_head_size != 0) {
  2555. // corresponds to RWKV's wkv_states size
  2556. return n_embd * wkv_head_size;
  2557. } else {
  2558. // corresponds to Mamba's ssm_states size
  2559. return ssm_d_state * ssm_d_inner;
  2560. }
  2561. }
  2562. bool n_bskcn(uint32_t n, uint32_t il = 0) const {
  2563. if (il < n_layer) {
  2564. return n_bskcn_arr[n][il] > 0;
  2565. }
  2566. GGML_ABORT("fatal error");
  2567. }
  2568. bool cross_attention_layers(uint32_t il) const {
  2569. return std::find(cross_attn_layers.begin(), cross_attn_layers.end(), il) != cross_attn_layers.end();
  2570. }
  2571. };
  2572. static_assert(std::is_trivially_copyable<llama_hparams>::value, "llama_hparams must be trivially copyable");
  2573. struct llama_cparams {
  2574. uint32_t n_ctx; // context size used during inference
  2575. uint32_t n_batch;
  2576. uint32_t n_ubatch;
  2577. uint32_t n_seq_max;
  2578. int n_threads; // number of threads to use for generation
  2579. int n_threads_batch; // number of threads to use for batch processing
  2580. float rope_freq_base;
  2581. float rope_freq_scale;
  2582. uint32_t n_ctx_orig_yarn;
  2583. // These hyperparameters are not exposed in GGUF, because all
  2584. // existing YaRN models use the same values for them.
  2585. float yarn_ext_factor;
  2586. float yarn_attn_factor;
  2587. float yarn_beta_fast;
  2588. float yarn_beta_slow;
  2589. float defrag_thold;
  2590. bool embeddings;
  2591. bool causal_attn;
  2592. bool offload_kqv;
  2593. bool flash_attn;
  2594. bool no_perf;
  2595. // TODO (jmorganca): this should most likely be passed in as part of a batch
  2596. // and not set on the context for all batches.
  2597. bool cross_attn = false;
  2598. enum llama_pooling_type pooling_type;
  2599. ggml_backend_sched_eval_callback cb_eval;
  2600. void * cb_eval_user_data;
  2601. };
  2602. // TODO: separate into "llama_layer_enc" and "llama_layer_dec"
  2603. struct llama_layer {
  2604. llama_layer() {
  2605. // initialize all pointers to NULL
  2606. std::memset(this, 0, sizeof(*this));
  2607. }
  2608. // normalization
  2609. struct ggml_tensor * attn_norm;
  2610. struct ggml_tensor * attn_norm_b;
  2611. struct ggml_tensor * attn_norm_2;
  2612. struct ggml_tensor * attn_norm_2_b;
  2613. struct ggml_tensor * attn_q_norm;
  2614. struct ggml_tensor * attn_q_norm_b;
  2615. struct ggml_tensor * attn_k_norm;
  2616. struct ggml_tensor * attn_k_norm_b;
  2617. struct ggml_tensor * attn_out_norm;
  2618. struct ggml_tensor * attn_out_norm_b;
  2619. struct ggml_tensor * attn_q_a_norm;
  2620. struct ggml_tensor * attn_kv_a_norm;
  2621. struct ggml_tensor * attn_sub_norm;
  2622. struct ggml_tensor * attn_post_norm;
  2623. struct ggml_tensor * ffn_sub_norm;
  2624. struct ggml_tensor * attn_norm_cross;
  2625. struct ggml_tensor * attn_norm_enc;
  2626. // attention
  2627. struct ggml_tensor * wq;
  2628. struct ggml_tensor * wk;
  2629. struct ggml_tensor * wv;
  2630. struct ggml_tensor * wo;
  2631. struct ggml_tensor * wqkv;
  2632. struct ggml_tensor * wq_a;
  2633. struct ggml_tensor * wq_b;
  2634. struct ggml_tensor * wkv_a_mqa;
  2635. struct ggml_tensor * wkv_b;
  2636. struct ggml_tensor * wq_cross;
  2637. struct ggml_tensor * wk_cross;
  2638. struct ggml_tensor * wv_cross;
  2639. struct ggml_tensor * wo_cross;
  2640. struct ggml_tensor * wq_enc;
  2641. struct ggml_tensor * wk_enc;
  2642. struct ggml_tensor * wv_enc;
  2643. struct ggml_tensor * wo_enc;
  2644. // attention bias
  2645. struct ggml_tensor * bq;
  2646. struct ggml_tensor * bk;
  2647. struct ggml_tensor * bv;
  2648. struct ggml_tensor * bo;
  2649. struct ggml_tensor * bqkv;
  2650. // relative position bias
  2651. struct ggml_tensor * attn_rel_b;
  2652. struct ggml_tensor * attn_rel_b_enc;
  2653. struct ggml_tensor * attn_rel_b_cross;
  2654. // normalization
  2655. struct ggml_tensor * ffn_norm;
  2656. struct ggml_tensor * ffn_norm_b;
  2657. struct ggml_tensor * ffn_post_norm;
  2658. struct ggml_tensor * layer_out_norm;
  2659. struct ggml_tensor * layer_out_norm_b;
  2660. struct ggml_tensor * ffn_norm_exps;
  2661. struct ggml_tensor * ffn_norm_enc;
  2662. // ff
  2663. struct ggml_tensor * ffn_gate; // w1
  2664. struct ggml_tensor * ffn_down; // w2
  2665. struct ggml_tensor * ffn_up; // w3
  2666. struct ggml_tensor * ffn_gate_enc;
  2667. struct ggml_tensor * ffn_down_enc;
  2668. struct ggml_tensor * ffn_up_enc;
  2669. // ff MoE
  2670. struct ggml_tensor * ffn_gate_inp;
  2671. struct ggml_tensor * ffn_gate_exps;
  2672. struct ggml_tensor * ffn_down_exps;
  2673. struct ggml_tensor * ffn_up_exps ;
  2674. // ff shared expert (shexp)
  2675. struct ggml_tensor * ffn_gate_inp_shexp;
  2676. struct ggml_tensor * ffn_gate_shexp;
  2677. struct ggml_tensor * ffn_down_shexp;
  2678. struct ggml_tensor * ffn_up_shexp;
  2679. // ff bias
  2680. struct ggml_tensor * ffn_gate_b;
  2681. struct ggml_tensor * ffn_down_b; // b2
  2682. struct ggml_tensor * ffn_up_b; // b3
  2683. struct ggml_tensor * ffn_act;
  2684. // mamba proj
  2685. struct ggml_tensor * ssm_in;
  2686. struct ggml_tensor * ssm_x;
  2687. struct ggml_tensor * ssm_dt;
  2688. struct ggml_tensor * ssm_out;
  2689. // mamba
  2690. struct ggml_tensor * ssm_conv1d;
  2691. struct ggml_tensor * ssm_a;
  2692. struct ggml_tensor * ssm_d;
  2693. // mamba bias
  2694. struct ggml_tensor * ssm_conv1d_b;
  2695. struct ggml_tensor * ssm_dt_b;
  2696. // rwkv
  2697. struct ggml_tensor * time_mix_w1;
  2698. struct ggml_tensor * time_mix_w2;
  2699. struct ggml_tensor * time_mix_lerp_x;
  2700. struct ggml_tensor * time_mix_lerp_w;
  2701. struct ggml_tensor * time_mix_lerp_k;
  2702. struct ggml_tensor * time_mix_lerp_v;
  2703. struct ggml_tensor * time_mix_lerp_r;
  2704. struct ggml_tensor * time_mix_lerp_g;
  2705. struct ggml_tensor * time_mix_first;
  2706. struct ggml_tensor * time_mix_decay;
  2707. struct ggml_tensor * time_mix_decay_w1;
  2708. struct ggml_tensor * time_mix_decay_w2;
  2709. struct ggml_tensor * time_mix_key;
  2710. struct ggml_tensor * time_mix_value;
  2711. struct ggml_tensor * time_mix_receptance;
  2712. struct ggml_tensor * time_mix_gate;
  2713. struct ggml_tensor * time_mix_ln;
  2714. struct ggml_tensor * time_mix_ln_b;
  2715. struct ggml_tensor * time_mix_output;
  2716. struct ggml_tensor * channel_mix_lerp_k;
  2717. struct ggml_tensor * channel_mix_lerp_r;
  2718. struct ggml_tensor * channel_mix_key;
  2719. struct ggml_tensor * channel_mix_receptance;
  2720. struct ggml_tensor * channel_mix_value;
  2721. // long rope factors
  2722. struct ggml_tensor * rope_long = nullptr;
  2723. struct ggml_tensor * rope_short = nullptr;
  2724. struct ggml_tensor * rope_freqs = nullptr;
  2725. // bitnet scale
  2726. struct ggml_tensor * wq_scale;
  2727. struct ggml_tensor * wk_scale;
  2728. struct ggml_tensor * wv_scale;
  2729. struct ggml_tensor * wo_scale;
  2730. struct ggml_tensor * ffn_gate_scale;
  2731. struct ggml_tensor * ffn_up_scale;
  2732. struct ggml_tensor * ffn_down_scale;
  2733. struct ggml_tensor * bskcn_tv;
  2734. // cross attention
  2735. struct ggml_tensor * cross_attn_k_norm;
  2736. struct ggml_tensor * cross_attn_k_proj;
  2737. struct ggml_tensor * cross_attn_o_proj;
  2738. struct ggml_tensor * cross_attn_q_norm;
  2739. struct ggml_tensor * cross_attn_q_proj;
  2740. struct ggml_tensor * cross_attn_v_proj;
  2741. struct ggml_tensor * cross_attn_attn_gate;
  2742. struct ggml_tensor * cross_attn_mlp_gate;
  2743. };
  2744. // very similar to llama_batch,
  2745. // but has more metadata about sequences
  2746. struct llama_ubatch {
  2747. bool equal_seqs;
  2748. // TODO: whole_seqs for embeddings?
  2749. uint32_t n_tokens; // total tokens (n_seq_tokens * n_seqs)
  2750. uint32_t n_seq_tokens; // tokens per sequence
  2751. uint32_t n_seqs;
  2752. llama_token * token; // [n_tokens]
  2753. float * embd; // [n_embd, n_tokens]
  2754. llama_pos * pos; // [n_tokens]
  2755. int32_t * n_seq_id; // [n_seqs]
  2756. llama_seq_id ** seq_id; // [n_seqs]
  2757. int8_t * output; // [n_tokens]
  2758. };
  2759. struct llama_kv_cell {
  2760. llama_pos pos = -1;
  2761. llama_pos delta = 0;
  2762. int32_t src = -1; // used by recurrent state models to copy states
  2763. int32_t tail = -1;
  2764. std::set<llama_seq_id> seq_id;
  2765. bool has_seq_id(const llama_seq_id & id) const {
  2766. return seq_id.find(id) != seq_id.end();
  2767. }
  2768. bool is_empty() const {
  2769. return seq_id.empty();
  2770. }
  2771. bool is_same_seq(const llama_kv_cell & other) const {
  2772. return seq_id == other.seq_id;
  2773. }
  2774. };
  2775. // ring-buffer of cached KV data
  2776. struct llama_kv_cache {
  2777. bool has_shift = false;
  2778. bool do_defrag = false;
  2779. bool recurrent = false; // with recurrent state models, a cell can hold the state for more than one past token
  2780. bool v_trans = true; // the value tensor is transposed
  2781. // Note: The value of head isn't only used to optimize searching
  2782. // for a free KV slot. llama_decode_internal also uses it, so it
  2783. // cannot be freely changed after a slot has been allocated.
  2784. uint32_t head = 0;
  2785. uint32_t size = 0;
  2786. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  2787. // computed before each graph build
  2788. uint32_t n = 0;
  2789. ggml_type type_k = GGML_TYPE_F16;
  2790. ggml_type type_v = GGML_TYPE_F16;
  2791. std::vector<llama_kv_cell> cells;
  2792. std::vector<struct ggml_tensor *> k_l; // per layer
  2793. std::vector<struct ggml_tensor *> v_l;
  2794. std::vector<ggml_context_ptr> ctxs;
  2795. std::vector<ggml_backend_buffer_ptr> bufs;
  2796. size_t total_size() {
  2797. size_t size = 0;
  2798. for (auto & buf : bufs) {
  2799. size += ggml_backend_buffer_get_size(buf.get());
  2800. }
  2801. return size;
  2802. }
  2803. };
  2804. // block of KV slots to move when defragging
  2805. struct llama_kv_defrag_move {
  2806. uint32_t src;
  2807. uint32_t dst;
  2808. uint32_t len;
  2809. };
  2810. struct llama_control_vector {
  2811. std::vector<struct ggml_tensor *> tensors; // per layer
  2812. std::vector<ggml_context_ptr> ctxs;
  2813. std::vector<ggml_backend_buffer_ptr> bufs;
  2814. int32_t layer_start = -1;
  2815. int32_t layer_end = -1;
  2816. struct ggml_tensor * tensor_for(int il) const {
  2817. if (il < 0 || il < layer_start || il > layer_end || (size_t) il >= tensors.size()) {
  2818. return nullptr;
  2819. }
  2820. return tensors[il];
  2821. }
  2822. struct ggml_tensor * apply_to(struct ggml_context * ctx, struct ggml_tensor * cur, int il) const {
  2823. ggml_tensor * layer_dir = tensor_for(il);
  2824. if (layer_dir != nullptr) {
  2825. cur = ggml_add(ctx, cur, layer_dir);
  2826. }
  2827. return cur;
  2828. }
  2829. };
  2830. struct llama_model {
  2831. e_model type = MODEL_UNKNOWN;
  2832. llm_arch arch = LLM_ARCH_UNKNOWN;
  2833. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  2834. std::string name = "n/a";
  2835. llama_hparams hparams = {};
  2836. llama_vocab vocab;
  2837. struct ggml_tensor * tok_embd = nullptr;
  2838. struct ggml_tensor * type_embd = nullptr;
  2839. struct ggml_tensor * pos_embd = nullptr;
  2840. struct ggml_tensor * tok_norm = nullptr;
  2841. struct ggml_tensor * tok_norm_b = nullptr;
  2842. struct ggml_tensor * output_norm = nullptr;
  2843. struct ggml_tensor * output_norm_b = nullptr;
  2844. struct ggml_tensor * output = nullptr;
  2845. struct ggml_tensor * output_b = nullptr;
  2846. struct ggml_tensor * output_norm_enc = nullptr;
  2847. // classifier
  2848. struct ggml_tensor * cls = nullptr;
  2849. struct ggml_tensor * cls_b = nullptr;
  2850. struct ggml_tensor * cls_out = nullptr;
  2851. struct ggml_tensor * cls_out_b = nullptr;
  2852. std::vector<llama_layer> layers;
  2853. // gguf metadata
  2854. std::unordered_map<std::string, std::string> gguf_kv;
  2855. llama_split_mode split_mode;
  2856. int main_gpu;
  2857. int n_gpu_layers;
  2858. std::vector<std::string> rpc_servers;
  2859. // list of devices used in this model
  2860. std::vector<ggml_backend_dev_t> devices;
  2861. // lists of buffer types used for each layer
  2862. using buft_list_t = std::vector<std::pair<ggml_backend_dev_t, ggml_backend_buffer_type_t>>;
  2863. buft_list_t cpu_buft_list;
  2864. std::map<ggml_backend_dev_t, buft_list_t> gpu_buft_list;
  2865. struct layer_dev {
  2866. ggml_backend_dev_t dev;
  2867. buft_list_t * buft_list;
  2868. };
  2869. layer_dev dev_input = {};
  2870. layer_dev dev_output = {};
  2871. std::vector<layer_dev> dev_layer;
  2872. // contexts where the model tensors metadata is stored
  2873. std::vector<ggml_context_ptr> ctxs;
  2874. // the model memory buffers for the tensor data
  2875. std::vector<ggml_backend_buffer_ptr> bufs;
  2876. // model memory mapped files
  2877. llama_mmaps mappings;
  2878. // objects representing data potentially being locked in memory
  2879. llama_mlocks mlock_bufs;
  2880. llama_mlocks mlock_mmaps;
  2881. // for quantize-stats only
  2882. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  2883. int64_t t_load_us = 0;
  2884. int64_t t_start_us = 0;
  2885. // total number of parameters in the model
  2886. uint64_t n_elements = 0;
  2887. // total size of all the tensors in the model in bytes
  2888. size_t n_bytes = 0;
  2889. // keep track of loaded lora adapters
  2890. std::set<struct llama_lora_adapter *> lora_adapters;
  2891. ~llama_model() {
  2892. while (!lora_adapters.empty()) {
  2893. llama_lora_adapter_free(*lora_adapters.begin());
  2894. }
  2895. }
  2896. };
  2897. struct llama_sbatch_seq {
  2898. int32_t n_seq_id;
  2899. llama_seq_id * seq_id;
  2900. size_t offset;
  2901. size_t length;
  2902. };
  2903. // sequence-length-aware batch splitting
  2904. struct llama_sbatch {
  2905. // tokens left in this batch
  2906. size_t n_tokens;
  2907. size_t n_embd;
  2908. bool logits_all; // TODO: remove once lctx.logits_all is removed too
  2909. // sorted indices into the batch
  2910. std::vector<size_t> ids;
  2911. // batch indices of the output
  2912. std::vector<size_t> out_ids;
  2913. std::vector<llama_sbatch_seq> seq;
  2914. const llama_batch * batch = nullptr;
  2915. // buffers for the ubatch
  2916. std::vector<llama_token> ubatch_token;
  2917. std::vector<float> ubatch_embd;
  2918. std::vector<llama_pos> ubatch_pos;
  2919. std::vector<int32_t> ubatch_n_seq_id;
  2920. std::vector<llama_seq_id *> ubatch_seq_id;
  2921. std::vector<int8_t> ubatch_output;
  2922. llama_ubatch reserve_ubatch(size_t n_ubatch, bool has_embd = false) {
  2923. // clear empty sequences
  2924. // the previous ubatch is assumed to be gone,
  2925. // so nothing should refer to values in these sequences anymore.
  2926. for (size_t i = seq.size(); i-- > 0;) {
  2927. if (seq[i].length == 0) {
  2928. seq.pop_back();
  2929. } else {
  2930. break;
  2931. }
  2932. }
  2933. ubatch_token.resize(!has_embd ? n_ubatch : 0);
  2934. ubatch_embd.resize(has_embd ? n_embd * n_ubatch : 0);
  2935. ubatch_pos.resize(n_ubatch);
  2936. ubatch_n_seq_id.resize(n_ubatch);
  2937. ubatch_seq_id.resize(n_ubatch);
  2938. ubatch_output.resize(n_ubatch);
  2939. llama_ubatch ubatch = {
  2940. /*equal_seqs =*/ true,
  2941. /*n_tokens =*/ 0,
  2942. /*n_seq_tokens =*/ 0,
  2943. /*n_seqs =*/ 0,
  2944. /*token =*/ !has_embd ? ubatch_token.data() : nullptr,
  2945. /*embd =*/ has_embd ? ubatch_embd.data() : nullptr,
  2946. /*pos =*/ ubatch_pos.data(),
  2947. /*n_seq_id =*/ ubatch_n_seq_id.data(),
  2948. /*seq_id =*/ ubatch_seq_id.data(),
  2949. /*output =*/ ubatch_output.data(),
  2950. };
  2951. return ubatch;
  2952. }
  2953. void add_seq_to_ubatch(llama_ubatch & ubatch, llama_sbatch_seq & seq, size_t length) {
  2954. GGML_ASSERT(batch != nullptr);
  2955. GGML_ASSERT(length <= seq.length);
  2956. // Can only add sequences of equal lengths to a batch,
  2957. // otherwise it isn't clear to which sequence a token belongs
  2958. GGML_ASSERT(seq.n_seq_id == 0 || ubatch.n_seqs == 0 || length == (size_t) ubatch.n_tokens / ubatch.n_seqs);
  2959. GGML_ASSERT((seq.n_seq_id != 0) == ubatch.equal_seqs);
  2960. // NOTE: loops are separated for cache-friendliness
  2961. if (batch->token) {
  2962. if (ubatch.equal_seqs) {
  2963. for (size_t i = 0; i < length; ++i) {
  2964. ubatch.token[ubatch.n_tokens + i] = batch->token[ids[seq.offset + i]];
  2965. }
  2966. } else {
  2967. // simple split
  2968. ubatch.token = batch->token + seq.offset;
  2969. }
  2970. } else {
  2971. ubatch.token = nullptr;
  2972. }
  2973. if (batch->embd) {
  2974. if (ubatch.equal_seqs) {
  2975. for (size_t i = 0; i < length; ++i) {
  2976. memcpy(
  2977. ubatch.embd + n_embd * (ubatch.n_tokens + i),
  2978. batch->embd + n_embd * ids[seq.offset + i],
  2979. n_embd * sizeof(float)
  2980. );
  2981. }
  2982. } else {
  2983. // simple split
  2984. ubatch.embd = batch->embd + (n_embd * seq.offset);
  2985. }
  2986. } else {
  2987. ubatch.embd = nullptr;
  2988. }
  2989. if (ubatch.equal_seqs) {
  2990. for (size_t i = 0; i < length; ++i) {
  2991. ubatch.pos[ubatch.n_tokens + i] = batch->pos[ids[seq.offset + i]];
  2992. }
  2993. } else {
  2994. // simple split
  2995. ubatch.pos = batch->pos + seq.offset;
  2996. }
  2997. if (ubatch.equal_seqs) {
  2998. ubatch.n_seq_id[ubatch.n_seqs] = seq.n_seq_id;
  2999. if (seq.seq_id) {
  3000. ubatch.seq_id[ubatch.n_seqs] = seq.seq_id;
  3001. }
  3002. } else {
  3003. // simple split
  3004. if (batch->n_seq_id) {
  3005. ubatch.n_seq_id = batch->n_seq_id + seq.offset;
  3006. } else {
  3007. for (size_t i = 0; i < length; ++i) {
  3008. ubatch.n_seq_id[ubatch.n_seqs + i] = 1;
  3009. }
  3010. }
  3011. if (batch->seq_id) {
  3012. ubatch.seq_id = batch->seq_id + seq.offset;
  3013. }
  3014. }
  3015. if (logits_all) {
  3016. for (size_t i = 0; i < length; ++i) {
  3017. ubatch.output[ubatch.n_tokens + i] = 1;
  3018. out_ids.push_back(ids[seq.offset + i]);
  3019. }
  3020. } else if (batch->logits) {
  3021. if (ubatch.equal_seqs) {
  3022. for (size_t i = 0; i < length; ++i) {
  3023. size_t id = ids[seq.offset + i];
  3024. int8_t is_output = batch->logits[id];
  3025. ubatch.output[ubatch.n_tokens + i] = is_output;
  3026. if (is_output) { out_ids.push_back(id); }
  3027. }
  3028. } else {
  3029. // simple split
  3030. ubatch.output = batch->logits + seq.offset;
  3031. for (size_t i = 0; i < length; ++i) {
  3032. if (ubatch.output[i] != 0) { out_ids.push_back(seq.offset + i); }
  3033. }
  3034. }
  3035. } else {
  3036. // only get last output
  3037. for (size_t i = 0; i < length; ++i) {
  3038. size_t id = ids[seq.offset + i];
  3039. int8_t is_last = id == ids.size() - 1;
  3040. ubatch.output[ubatch.n_tokens + i] = is_last;
  3041. if (is_last) { out_ids.push_back(id); }
  3042. }
  3043. }
  3044. if (ubatch.n_tokens == 0 && ubatch.n_seqs == 0) {
  3045. ubatch.n_seq_tokens = ubatch.equal_seqs ? length : 1;
  3046. }
  3047. ubatch.n_tokens += length;
  3048. ubatch.n_seqs += ubatch.equal_seqs ? 1 : length; // virtual sequences for simple splits
  3049. seq.offset += length;
  3050. seq.length -= length;
  3051. n_tokens -= length;
  3052. GGML_ASSERT(ubatch.n_tokens == ubatch.n_seq_tokens * ubatch.n_seqs);
  3053. }
  3054. // simple split, unknown number of sequences of unequal lengths
  3055. llama_ubatch split_simple(size_t n_ubatch) {
  3056. n_ubatch = n_tokens < n_ubatch ? n_tokens : n_ubatch;
  3057. llama_ubatch ubatch = reserve_ubatch(n_ubatch, /* has_embd */ batch->embd != nullptr);
  3058. ubatch.equal_seqs = false;
  3059. if (!seq.empty()) {
  3060. llama_sbatch_seq & s = seq[0];
  3061. size_t length = s.length < n_ubatch ? s.length : n_ubatch;
  3062. GGML_ASSERT(seq.size() == 1 && s.n_seq_id == 0); // don't mix with other splits
  3063. add_seq_to_ubatch(ubatch, s, length);
  3064. }
  3065. return ubatch;
  3066. }
  3067. // make batches of equal-length sequences
  3068. llama_ubatch split_equal(size_t n_ubatch) {
  3069. n_ubatch = n_tokens < n_ubatch ? n_tokens : n_ubatch;
  3070. llama_ubatch ubatch = reserve_ubatch(n_ubatch, /* has_embd */ batch->embd != nullptr);
  3071. if (!seq.empty()) {
  3072. size_t length = 0;
  3073. size_t n_tokens_in_ubatch = 0;
  3074. GGML_ASSERT(seq[0].n_seq_id > 0); // should not be mixed with simple splits
  3075. // smallest first, because it's easier to split this way;
  3076. // starting from the end to pop in constant time.
  3077. for (size_t i = seq.size(); i-- > 0;) {
  3078. llama_sbatch_seq & s = seq[i];
  3079. GGML_ASSERT(s.length > 0);
  3080. if (length == 0) {
  3081. length = s.length < n_ubatch ? s.length : n_ubatch;
  3082. }
  3083. add_seq_to_ubatch(ubatch, s, length);
  3084. n_tokens_in_ubatch += length;
  3085. // shared prompts can't be mixed with any of their sequences,
  3086. // so it's safer to compute them in their own ubatch
  3087. if (s.n_seq_id > 1) { break; }
  3088. // stop when there isn't enough space for another sequence
  3089. if (length + n_tokens_in_ubatch > n_ubatch) { break; }
  3090. }
  3091. }
  3092. return ubatch;
  3093. }
  3094. // sequence-wise split
  3095. llama_ubatch split_seq(size_t n_ubatch) {
  3096. n_ubatch = n_tokens < n_ubatch ? n_tokens : n_ubatch;
  3097. llama_ubatch ubatch = reserve_ubatch(n_ubatch, /* has_embd */ batch->embd != nullptr);
  3098. if (!seq.empty()) {
  3099. llama_sbatch_seq & s = seq[seq.size() - 1];
  3100. size_t length = s.length < n_ubatch ? s.length : n_ubatch;
  3101. GGML_ASSERT(s.n_seq_id > 0); // should not be mixed with simple splits
  3102. add_seq_to_ubatch(ubatch, s, length);
  3103. }
  3104. return ubatch;
  3105. }
  3106. void from_batch(const llama_batch & batch, const size_t n_embd, const bool simple_split = false, const bool logits_all = false) {
  3107. GGML_ASSERT(batch.n_tokens >= 0);
  3108. this->batch = &batch;
  3109. this->n_embd = n_embd;
  3110. this->logits_all = logits_all;
  3111. n_tokens = batch.n_tokens;
  3112. ids.resize(n_tokens);
  3113. out_ids.clear();
  3114. // TODO: reserve out_ids and seq
  3115. for (size_t i = 0; i < n_tokens; ++i) {
  3116. ids[i] = i;
  3117. }
  3118. if (simple_split) {
  3119. seq.resize(1);
  3120. llama_sbatch_seq & s = seq[0];
  3121. s.n_seq_id = 0;
  3122. s.seq_id = nullptr;
  3123. s.offset = 0;
  3124. s.length = n_tokens;
  3125. return;
  3126. }
  3127. std::sort(ids.begin(), ids.end(),
  3128. [&batch](size_t a, size_t b) {
  3129. int32_t n_seq_a = batch.n_seq_id ? batch.n_seq_id[a] : 1;
  3130. int32_t n_seq_b = batch.n_seq_id ? batch.n_seq_id[b] : 1;
  3131. // sort by seq_id, then by pos
  3132. if (n_seq_a == n_seq_b) {
  3133. if (batch.seq_id) {
  3134. for (int32_t i = 0; i < n_seq_a; ++i) {
  3135. llama_seq_id seq_id_a = batch.seq_id[a][i];
  3136. llama_seq_id seq_id_b = batch.seq_id[b][i];
  3137. // smaller seq_ids go first
  3138. if (seq_id_a != seq_id_b) {
  3139. return seq_id_a < seq_id_b;
  3140. }
  3141. }
  3142. }
  3143. // when all else is equal, sort by pos
  3144. if (batch.pos) {
  3145. return batch.pos[a] < batch.pos[b];
  3146. }
  3147. // no pos, sort by id
  3148. return a < b;
  3149. }
  3150. // shared prompts go first
  3151. return n_seq_a > n_seq_b;
  3152. }
  3153. );
  3154. // init seq
  3155. llama_sbatch_seq * last_seq = nullptr;
  3156. for (size_t i = 0; i < n_tokens; ++i) {
  3157. const size_t bi = ids[i];
  3158. const int32_t n_seqs = batch.n_seq_id[bi];
  3159. llama_seq_id * seq_ids = batch.seq_id[bi];
  3160. if (last_seq != nullptr) {
  3161. bool same = n_seqs == last_seq->n_seq_id;
  3162. for (int32_t j = 0; same && j < n_seqs; ++j) {
  3163. if (seq_ids[j] != last_seq->seq_id[j]) {
  3164. same = false;
  3165. }
  3166. }
  3167. if (same) {
  3168. last_seq->length += 1;
  3169. continue;
  3170. }
  3171. }
  3172. llama_sbatch_seq new_seq = {n_seqs, seq_ids, i, 1};
  3173. seq.push_back(new_seq);
  3174. last_seq = &seq.back();
  3175. }
  3176. // keep shared prompts first at the end, then sort by length descending.
  3177. std::sort(seq.begin(), seq.end(),
  3178. [](llama_sbatch_seq & a, llama_sbatch_seq & b) {
  3179. if (a.n_seq_id == b.n_seq_id) {
  3180. return a.length > b.length;
  3181. }
  3182. return a.n_seq_id < b.n_seq_id;
  3183. }
  3184. );
  3185. }
  3186. };
  3187. struct llama_context {
  3188. llama_context(const llama_model & model)
  3189. : model(model)
  3190. , t_start_us(model.t_start_us)
  3191. , t_load_us(model.t_load_us) {}
  3192. const struct llama_model & model;
  3193. struct llama_cparams cparams;
  3194. struct llama_sbatch sbatch;
  3195. struct llama_kv_cache kv_self;
  3196. struct llama_control_vector cvec;
  3197. std::unordered_map<struct llama_lora_adapter *, float> lora_adapters;
  3198. std::vector<ggml_backend_ptr> backends;
  3199. std::vector<std::pair<ggml_backend_t, ggml_backend_set_n_threads_t>> set_n_threads_fns;
  3200. ggml_backend_t backend_cpu = nullptr;
  3201. ggml_threadpool_t threadpool = nullptr;
  3202. ggml_threadpool_t threadpool_batch = nullptr;
  3203. bool has_evaluated_once = false;
  3204. mutable int64_t t_start_us;
  3205. mutable int64_t t_load_us;
  3206. mutable int64_t t_p_eval_us = 0;
  3207. mutable int64_t t_eval_us = 0;
  3208. mutable int64_t t_compute_start_us = 0;
  3209. mutable int64_t n_queued_tokens = 0;
  3210. mutable int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  3211. mutable int32_t n_eval = 0; // number of eval calls
  3212. // host buffer for the model output (logits and embeddings)
  3213. ggml_backend_buffer_ptr buf_output;
  3214. // decode output (2-dimensional array: [n_outputs][n_vocab])
  3215. size_t logits_size = 0; // capacity (of floats) for logits
  3216. float * logits = nullptr;
  3217. std::vector<int32_t> output_ids; // map batch token positions to ids of the logits and embd buffers
  3218. size_t output_size = 0; // capacity (of tokens positions) for the output buffers
  3219. int32_t n_outputs = 0; // number of actually-used outputs in the current ubatch or last logical batch
  3220. bool logits_all = false;
  3221. // embeddings output (2-dimensional array: [n_outputs][n_embd])
  3222. // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE
  3223. size_t embd_size = 0; // capacity (of floats) for embeddings
  3224. float * embd = nullptr;
  3225. // sequence embeddings output (map of [n_embd] vectors)
  3226. // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE
  3227. std::map<llama_seq_id, std::vector<float>> embd_seq;
  3228. // whether we are computing encoder output or decoder output
  3229. bool is_encoding = false;
  3230. // TODO: find a better way to accommodate mutli-dimension position encoding methods
  3231. // number of position id each token get, 1 for each token in most cases.
  3232. // when using m-rope, it will be 3 position ids per token to representing 3 dimension coordinate.
  3233. int n_pos_per_token = 1;
  3234. // output of the encoder part of the encoder-decoder models
  3235. std::vector<float> embd_enc;
  3236. std::vector<std::set<llama_seq_id>> seq_ids_enc;
  3237. // memory buffers used to evaluate the model
  3238. std::vector<uint8_t> buf_compute_meta;
  3239. ggml_backend_sched_ptr sched;
  3240. ggml_abort_callback abort_callback = nullptr;
  3241. void * abort_callback_data = nullptr;
  3242. // input tensors
  3243. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  3244. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  3245. struct ggml_tensor * inp_pos; // I32 [n_batch]
  3246. struct ggml_tensor * inp_out_ids; // I32 [n_outputs]
  3247. struct ggml_tensor * inp_KQ_mask; // F32 [kv_size, n_batch]
  3248. struct ggml_tensor * inp_KQ_mask_swa; // F32 [kv_size, n_batch]
  3249. struct ggml_tensor * inp_K_shift; // I32 [kv_size]
  3250. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  3251. struct ggml_tensor * inp_cls; // I32 [n_batch]
  3252. struct ggml_tensor * inp_s_copy; // I32 [kv_size]
  3253. struct ggml_tensor * inp_s_mask; // F32 [1, n_kv]
  3254. struct ggml_tensor * inp_s_seq; // I32 [n_kv, n_batch]
  3255. struct ggml_tensor * inp_pos_bucket; // I32 [n_batch|n_kv, n_batch]
  3256. struct ggml_tensor * inp_embd_enc; // F32 [n_embd, n_outputs_enc]
  3257. struct ggml_tensor * inp_KQ_mask_cross; // F32 [n_outputs_enc, n_batch]
  3258. struct ggml_tensor * inp_cross_attn_state; // F32 [4, n_embd, 1061]
  3259. };
  3260. struct llama_lora_weight {
  3261. struct ggml_tensor * a = nullptr;
  3262. struct ggml_tensor * b = nullptr;
  3263. llama_lora_weight() = default;
  3264. llama_lora_weight(struct ggml_tensor * a, struct ggml_tensor * b): a(a), b(b) {}
  3265. };
  3266. struct llama_lora_adapter {
  3267. struct llama_model * base_model;
  3268. // map tensor name to lora_a_b
  3269. std::unordered_map<std::string, struct llama_lora_weight> ab_map;
  3270. std::vector<ggml_context_ptr> ctxs;
  3271. std::vector<ggml_backend_buffer_ptr> bufs;
  3272. float alpha;
  3273. llama_lora_adapter(struct llama_model * base_model): base_model(base_model) {
  3274. base_model->lora_adapters.insert(this);
  3275. }
  3276. llama_lora_weight * get_weight(struct ggml_tensor * w) {
  3277. std::string name(w->name);
  3278. auto pos = ab_map.find(name);
  3279. if (ab_map.find(name) != ab_map.end()) {
  3280. return &pos->second;
  3281. }
  3282. return nullptr;
  3283. }
  3284. ~llama_lora_adapter() {
  3285. auto pos = base_model->lora_adapters.find(this);
  3286. if (pos != base_model->lora_adapters.end()) {
  3287. base_model->lora_adapters.erase(pos);
  3288. }
  3289. }
  3290. };
  3291. static int llama_get_device_count(const llama_model & model) {
  3292. return (int) model.devices.size();
  3293. }
  3294. template<typename F>
  3295. static bool buft_supported(ggml_backend_buffer_type_t buft, ggml_backend_dev_t dev, F & fn) {
  3296. ggml_init_params params = {
  3297. /*.mem_size =*/ ggml_tensor_overhead()*8,
  3298. /*.mem_buffer =*/ NULL,
  3299. /*.no_alloc =*/ true,
  3300. };
  3301. ggml_context_ptr ctx { ggml_init(params) };
  3302. if (!ctx) {
  3303. throw std::runtime_error(format("failed to create ggml context"));
  3304. }
  3305. ggml_backend_buffer_ptr buf { ggml_backend_buft_alloc_buffer(buft, 0) };
  3306. ggml_tensor * op_tensor = fn(ctx.get());
  3307. for (int i = 0; i < GGML_MAX_SRC; i++) {
  3308. if (op_tensor->src[i] != nullptr) {
  3309. assert(op_tensor->src[i]->buffer == nullptr);
  3310. op_tensor->src[i]->buffer = buf.get();
  3311. }
  3312. }
  3313. bool op_supported = ggml_backend_dev_supports_op(dev, op_tensor);
  3314. return op_supported;
  3315. }
  3316. template<typename F>
  3317. static ggml_backend_buffer_type_t select_buft(const llama_model::buft_list_t & buft_list, const F & fn) {
  3318. for (const auto & cur : buft_list) {
  3319. ggml_backend_dev_t cur_dev = cur.first;
  3320. ggml_backend_buffer_type_t cur_buft = cur.second;
  3321. if (buft_supported(cur_buft, cur_dev, fn)) {
  3322. return cur_buft;
  3323. }
  3324. }
  3325. throw std::runtime_error(format("no suitable buffer type found"));
  3326. }
  3327. //
  3328. // kv cache helpers
  3329. //
  3330. static bool llama_kv_cache_init(
  3331. struct llama_kv_cache & cache,
  3332. const llama_context * ctx,
  3333. ggml_type type_k,
  3334. ggml_type type_v,
  3335. uint32_t kv_size,
  3336. bool offload) {
  3337. const llama_model & model = ctx->model;
  3338. const llama_cparams & cparams = ctx->cparams;
  3339. const struct llama_hparams & hparams = model.hparams;
  3340. const int64_t n_layer = hparams.n_layer;
  3341. cache.has_shift = false;
  3342. cache.recurrent = llama_model_is_recurrent(&model);
  3343. cache.v_trans = !cache.recurrent && !cparams.flash_attn;
  3344. cache.head = 0;
  3345. cache.size = kv_size;
  3346. cache.used = 0;
  3347. cache.type_k = type_k;
  3348. cache.type_v = type_v;
  3349. cache.cells.clear();
  3350. cache.cells.resize(kv_size);
  3351. // create a context for each buffer type
  3352. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3353. auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
  3354. auto it = ctx_map.find(buft);
  3355. if (it == ctx_map.end()) {
  3356. struct ggml_init_params params = {
  3357. /*.mem_size =*/ size_t(2u*n_layer*ggml_tensor_overhead()),
  3358. /*.mem_buffer =*/ NULL,
  3359. /*.no_alloc =*/ true,
  3360. };
  3361. ggml_context * ctx = ggml_init(params);
  3362. if (!ctx) {
  3363. return nullptr;
  3364. }
  3365. ctx_map[buft] = ctx;
  3366. cache.ctxs.emplace_back(ctx);
  3367. return ctx;
  3368. }
  3369. return it->second;
  3370. };
  3371. cache.k_l.reserve(n_layer);
  3372. cache.v_l.reserve(n_layer);
  3373. for (int i = 0; i < (int) n_layer; i++) {
  3374. // for cross attention layers
  3375. if (model.arch == LLM_ARCH_MLLAMA && hparams.cross_attention_layers(i)) {
  3376. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(i) + hparams.n_embd_k_s();
  3377. const llama_model::buft_list_t * buft_list;
  3378. if (offload) {
  3379. buft_list = model.dev_layer.at(i).buft_list;
  3380. } else {
  3381. buft_list = &model.cpu_buft_list;
  3382. }
  3383. ggml_backend_buffer_type_t buft = select_buft(*buft_list,
  3384. [&](ggml_context * ctx) {
  3385. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  3386. if (hparams.rope_type == LLAMA_ROPE_TYPE_NONE) {
  3387. return k;
  3388. }
  3389. ggml_tensor * p = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 1);
  3390. return ggml_rope(ctx, k, p, hparams.n_rot, hparams.rope_type);
  3391. });
  3392. ggml_context * ctx = ctx_for_buft(buft);
  3393. if (!ctx) {
  3394. LLAMA_LOG_ERROR("%s: failed to create ggml context for kv cache\n", __func__);
  3395. return false;
  3396. }
  3397. ggml_tensor * k = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, hparams.n_embd_head_k, 6404, hparams.n_head_kv(i));
  3398. ggml_tensor * v = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, hparams.n_embd_head_v, 6404, hparams.n_head_kv(i));
  3399. ggml_format_name(k, "cache_k_l%d", i);
  3400. ggml_format_name(v, "cache_v_l%d", i);
  3401. cache.k_l.push_back(k);
  3402. cache.v_l.push_back(v);
  3403. continue;
  3404. }
  3405. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(i) + hparams.n_embd_k_s();
  3406. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(i) + hparams.n_embd_v_s();
  3407. ggml_backend_buffer_type_t buft;
  3408. if (offload) {
  3409. auto * dev = model.dev_layer.at(i).dev;
  3410. buft = ggml_backend_dev_buffer_type(dev);
  3411. } else {
  3412. buft = ggml_backend_cpu_buffer_type();
  3413. }
  3414. ggml_context * ctx = ctx_for_buft(buft);
  3415. if (!ctx) {
  3416. LLAMA_LOG_ERROR("%s: failed to create ggml context for kv cache\n", __func__);
  3417. return false;
  3418. }
  3419. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  3420. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*kv_size);
  3421. ggml_format_name(k, "cache_k_l%d", i);
  3422. ggml_format_name(v, "cache_v_l%d", i);
  3423. cache.k_l.push_back(k);
  3424. cache.v_l.push_back(v);
  3425. }
  3426. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  3427. for (auto it : ctx_map) {
  3428. auto * buft = it.first;
  3429. auto * ctx = it.second;
  3430. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  3431. if (!buf) {
  3432. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  3433. return false;
  3434. }
  3435. ggml_backend_buffer_clear(buf, 0);
  3436. 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);
  3437. cache.bufs.emplace_back(buf);
  3438. }
  3439. return true;
  3440. }
  3441. // a structure holds information about the slot found in llama_kv_cache_find_slot
  3442. struct llama_kv_cache_slot_info {
  3443. std::pair<uint32_t, uint32_t> boundaries; // slot boundaries [begin, end)
  3444. bool found = false; // the slot was found
  3445. explicit llama_kv_cache_slot_info(bool found_) : found{found_} {}
  3446. llama_kv_cache_slot_info(uint32_t begin, uint32_t end) : boundaries{begin, end}, found{true} {}
  3447. operator bool() const { return found; }
  3448. };
  3449. static const llama_kv_cache_slot_info llama_kv_cache_slot_info_failed{false};
  3450. // find an empty slot of size "n_tokens" in the cache
  3451. // updates the cache head
  3452. // returns a structure holding information about the slot found
  3453. // Note: On success, it's important that cache.head points
  3454. // to the first cell of the slot.
  3455. static struct llama_kv_cache_slot_info llama_kv_cache_find_slot(
  3456. struct llama_kv_cache & cache,
  3457. const struct llama_ubatch & batch) {
  3458. const uint32_t n_tokens = batch.n_tokens;
  3459. const uint32_t n_seqs = batch.n_seqs;
  3460. const uint32_t n_seq_tokens = batch.n_seq_tokens;
  3461. if (cache.recurrent) {
  3462. // For recurrent state architectures (like Mamba or RWKV),
  3463. // each cache cell can store the state for a whole sequence.
  3464. // A slot should be always be contiguous.
  3465. // can only process batches with an equal number of new tokens in each sequence
  3466. GGML_ASSERT(batch.equal_seqs);
  3467. int32_t min = cache.size - 1;
  3468. int32_t max = 0;
  3469. // everything should fit if all seq_ids are smaller than the max
  3470. for (uint32_t s = 0; s < n_seqs; ++s) {
  3471. const uint32_t n_seq_id = batch.n_seq_id[s];
  3472. for (uint32_t j = 0; j < n_seq_id; ++j) {
  3473. const llama_seq_id seq_id = batch.seq_id[s][j];
  3474. if (seq_id < 0 || (uint32_t) seq_id >= cache.size) {
  3475. // too big seq_id
  3476. // TODO: would it be possible to resize the cache instead?
  3477. LLAMA_LOG_ERROR("%s: seq_id=%d >= n_seq_max=%d Try using a bigger --parallel value\n", __func__, seq_id, cache.size);
  3478. return llama_kv_cache_slot_info_failed;
  3479. }
  3480. if (j > 0) {
  3481. llama_kv_cell & seq = cache.cells[seq_id];
  3482. if (seq.tail >= 0) {
  3483. llama_kv_cell & cell = cache.cells[seq.tail];
  3484. // clear cells from seq_ids that become shared
  3485. // (should not normally happen, but let's handle it anyway)
  3486. cell.seq_id.erase(seq_id);
  3487. seq.tail = -1;
  3488. if (cell.seq_id.empty()) {
  3489. cell.pos = -1;
  3490. cell.src = -1;
  3491. cache.used -= 1;
  3492. }
  3493. }
  3494. }
  3495. }
  3496. }
  3497. #ifndef NDEBUG
  3498. {
  3499. std::vector<int32_t> tails_verif;
  3500. tails_verif.assign(cache.size, -1);
  3501. for (uint32_t i = 0; i < cache.size; ++i) {
  3502. llama_kv_cell & cell = cache.cells[i];
  3503. for (llama_seq_id seq_id : cell.seq_id) {
  3504. if (tails_verif[seq_id] != -1) {
  3505. LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tails_verif[seq_id]);
  3506. }
  3507. tails_verif[seq_id] = i;
  3508. }
  3509. }
  3510. for (uint32_t i = 0; i < cache.size; ++i) {
  3511. if (tails_verif[i] != cache.cells[i].tail) {
  3512. LLAMA_LOG_ERROR("%s: wrong tail for seq_id %d, (%d instead of %d)\n", __func__, i, cache.cells[i].tail, tails_verif[i]);
  3513. }
  3514. }
  3515. }
  3516. #endif
  3517. // find next empty cell
  3518. uint32_t next_empty_cell = cache.head;
  3519. for (uint32_t i = 0; i < cache.size; ++i) {
  3520. if (next_empty_cell >= cache.size) { next_empty_cell -= cache.size; }
  3521. llama_kv_cell & cell = cache.cells[next_empty_cell];
  3522. if (cell.is_empty()) { break; }
  3523. next_empty_cell += 1;
  3524. }
  3525. // find usable cell range
  3526. for (uint32_t s = 0; s < n_seqs; ++s) {
  3527. const llama_seq_id seq_id = batch.seq_id[s][0];
  3528. llama_kv_cell & seq_meta = cache.cells[seq_id];
  3529. bool has_cell = false;
  3530. if (seq_meta.tail >= 0) {
  3531. llama_kv_cell & cell = cache.cells[seq_meta.tail];
  3532. GGML_ASSERT(cell.has_seq_id(seq_id));
  3533. // does this seq_id "own" the cell?
  3534. if (cell.seq_id.size() == 1) { has_cell = true; }
  3535. }
  3536. if (!has_cell) {
  3537. llama_kv_cell & empty_cell = cache.cells[next_empty_cell];
  3538. GGML_ASSERT(empty_cell.is_empty());
  3539. // copy old tail into the empty cell
  3540. if (seq_meta.tail >= 0) {
  3541. llama_kv_cell & orig_cell = cache.cells[seq_meta.tail];
  3542. empty_cell.pos = orig_cell.pos;
  3543. empty_cell.src = orig_cell.src;
  3544. orig_cell.seq_id.erase(seq_id);
  3545. empty_cell.seq_id.insert(seq_id); // will be overwritten
  3546. }
  3547. seq_meta.tail = next_empty_cell;
  3548. // find next empty cell
  3549. if (s + 1 < n_seqs) {
  3550. next_empty_cell += 1;
  3551. for (uint32_t i = 0; i < cache.size; ++i) {
  3552. if (next_empty_cell >= cache.size) { next_empty_cell -= cache.size; }
  3553. llama_kv_cell & cell = cache.cells[next_empty_cell];
  3554. if (cell.is_empty()) { break; }
  3555. next_empty_cell += 1;
  3556. }
  3557. }
  3558. }
  3559. if (min > seq_meta.tail) { min = seq_meta.tail; }
  3560. if (max < seq_meta.tail) { max = seq_meta.tail; }
  3561. }
  3562. // gather and re-order
  3563. for (uint32_t s = 0; s < n_seqs; ++s) {
  3564. int32_t dst_id = s + min;
  3565. int32_t src_id = cache.cells[batch.seq_id[s][0]].tail;
  3566. if (dst_id != src_id) {
  3567. llama_kv_cell & dst_cell = cache.cells[dst_id];
  3568. llama_kv_cell & src_cell = cache.cells[src_id];
  3569. std::swap(dst_cell.pos, src_cell.pos);
  3570. std::swap(dst_cell.src, src_cell.src);
  3571. std::swap(dst_cell.seq_id, src_cell.seq_id);
  3572. // swap tails (assuming they NEVER overlap)
  3573. for (const llama_seq_id seq_id : src_cell.seq_id) {
  3574. cache.cells[seq_id].tail = src_id;
  3575. }
  3576. for (const llama_seq_id seq_id : dst_cell.seq_id) {
  3577. cache.cells[seq_id].tail = dst_id;
  3578. }
  3579. }
  3580. }
  3581. // update the pos of the used seqs
  3582. for (uint32_t s = 0; s < n_seqs; ++s) {
  3583. const llama_pos last_pos = batch.pos[n_seq_tokens * s + n_seq_tokens - 1];
  3584. int32_t cell_id = s + min;
  3585. llama_kv_cell & cell = cache.cells[cell_id];
  3586. if (cell.pos >= 0 && last_pos != cell.pos + (llama_pos) n_seq_tokens) {
  3587. // What should happen when the pos backtracks or skips a value?
  3588. // Clearing the state mid-batch would require special-casing which isn't done.
  3589. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d with %u new tokens\n",
  3590. __func__, last_pos, cell.pos, batch.seq_id[s][0], n_seq_tokens);
  3591. }
  3592. cell.pos = last_pos;
  3593. cell.seq_id.clear();
  3594. for (int32_t j = 0; j < batch.n_seq_id[s]; ++j) {
  3595. const llama_seq_id seq_id = batch.seq_id[s][j];
  3596. cell.seq_id.insert(seq_id);
  3597. cache.cells[seq_id].tail = cell_id;
  3598. }
  3599. }
  3600. // allow getting the range of used cells, from head to head + n
  3601. cache.head = min;
  3602. cache.n = max - min + 1;
  3603. cache.used = std::count_if(cache.cells.begin(), cache.cells.end(),
  3604. [](const llama_kv_cell& cell){ return !cell.is_empty(); });
  3605. // sanity check
  3606. return llama_kv_cache_slot_info(cache.n >= n_seqs);
  3607. }
  3608. // otherwise, one cell per token.
  3609. if (n_tokens > cache.size) {
  3610. LLAMA_LOG_ERROR("%s: n_tokens=%d > cache.size=%d\n", __func__, n_tokens, cache.size);
  3611. return llama_kv_cache_slot_info_failed;
  3612. }
  3613. uint32_t n_tested = 0;
  3614. while (true) {
  3615. if (cache.head + n_tokens > cache.size) {
  3616. n_tested += cache.size - cache.head;
  3617. cache.head = 0;
  3618. continue;
  3619. }
  3620. bool found = true;
  3621. for (uint32_t i = 0; i < n_tokens; i++) {
  3622. if (cache.cells[cache.head + i].pos >= 0) {
  3623. found = false;
  3624. cache.head += i + 1;
  3625. n_tested += i + 1;
  3626. break;
  3627. }
  3628. }
  3629. if (found) {
  3630. break;
  3631. }
  3632. if (n_tested >= cache.size) {
  3633. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  3634. return llama_kv_cache_slot_info_failed;
  3635. }
  3636. }
  3637. for (uint32_t s = 0; s < n_seqs; s++) {
  3638. for (uint32_t i = 0; i < n_seq_tokens; ++i) {
  3639. uint32_t k = s*n_seq_tokens + i;
  3640. cache.cells[cache.head + k].pos = batch.pos[k];
  3641. for (int32_t j = 0; j < batch.n_seq_id[s]; j++) {
  3642. cache.cells[cache.head + k].seq_id.insert(batch.seq_id[s][j]);
  3643. }
  3644. }
  3645. }
  3646. cache.used += n_tokens;
  3647. return llama_kv_cache_slot_info(cache.head, cache.head + n_tokens);
  3648. }
  3649. // find how many cells are currently in use
  3650. static uint32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  3651. for (uint32_t i = cache.size; i > 0; --i) {
  3652. const llama_kv_cell & cell = cache.cells[i - 1];
  3653. if (cell.pos >= 0 && !cell.is_empty()) {
  3654. return i;
  3655. }
  3656. }
  3657. return 0;
  3658. }
  3659. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  3660. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  3661. cache.cells[i].pos = -1;
  3662. cache.cells[i].seq_id.clear();
  3663. cache.cells[i].src = -1;
  3664. cache.cells[i].tail = -1;
  3665. }
  3666. cache.head = 0;
  3667. cache.used = 0;
  3668. for (auto & buf : cache.bufs) {
  3669. ggml_backend_buffer_clear(buf.get(), 0);
  3670. }
  3671. }
  3672. static bool llama_kv_cache_seq_rm(
  3673. struct llama_kv_cache & cache,
  3674. llama_seq_id seq_id,
  3675. llama_pos p0,
  3676. llama_pos p1) {
  3677. uint32_t new_head = cache.size;
  3678. if (p0 < 0) p0 = 0;
  3679. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3680. // models like Mamba or RWKV can't have a state partially erased
  3681. if (cache.recurrent) {
  3682. if (seq_id >= (int64_t) cache.size) {
  3683. // could be fatal
  3684. return false;
  3685. }
  3686. if (0 <= seq_id) {
  3687. int32_t & tail_id = cache.cells[seq_id].tail;
  3688. if (tail_id >= 0) {
  3689. const llama_kv_cell & cell = cache.cells[tail_id];
  3690. // partial intersection is invalid
  3691. if ((0 < p0 && p0 <= cell.pos) || (0 < p1 && p1 <= cell.pos)) {
  3692. return false;
  3693. }
  3694. // invalidate tails which will be cleared
  3695. if (p0 <= cell.pos && cell.pos < p1) {
  3696. tail_id = -1;
  3697. }
  3698. }
  3699. } else {
  3700. // seq_id is negative, then the range should include everything or nothing
  3701. if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
  3702. return false;
  3703. }
  3704. }
  3705. }
  3706. for (uint32_t i = 0; i < cache.size; ++i) {
  3707. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3708. if (seq_id < 0) {
  3709. cache.cells[i].seq_id.clear();
  3710. } else if (cache.cells[i].has_seq_id(seq_id)) {
  3711. cache.cells[i].seq_id.erase(seq_id);
  3712. } else {
  3713. continue;
  3714. }
  3715. if (cache.cells[i].is_empty()) {
  3716. // keep count of the number of used cells
  3717. if (cache.cells[i].pos >= 0) cache.used--;
  3718. cache.cells[i].pos = -1;
  3719. cache.cells[i].src = -1;
  3720. if (new_head == cache.size) new_head = i;
  3721. }
  3722. }
  3723. }
  3724. // If we freed up a slot, set head to it so searching can start there.
  3725. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  3726. return true;
  3727. }
  3728. static void llama_kv_cache_seq_cp(
  3729. struct llama_kv_cache & cache,
  3730. llama_seq_id seq_id_src,
  3731. llama_seq_id seq_id_dst,
  3732. llama_pos p0,
  3733. llama_pos p1) {
  3734. if (p0 < 0) p0 = 0;
  3735. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3736. if (cache.recurrent) {
  3737. if ((uint32_t) seq_id_dst < cache.size && (uint32_t) seq_id_src < cache.size) {
  3738. llama_kv_cell & tail_src = cache.cells[seq_id_src];
  3739. llama_kv_cell & tail_dst = cache.cells[seq_id_dst];
  3740. if (tail_dst.tail >= 0) {
  3741. // clear destination seq_id if it wasn't empty
  3742. llama_kv_cell & cell_dst = cache.cells[tail_dst.tail];
  3743. cell_dst.seq_id.erase(seq_id_dst);
  3744. tail_dst.tail = -1;
  3745. if (cell_dst.seq_id.empty()) {
  3746. cell_dst.pos = -1;
  3747. cell_dst.delta = -1;
  3748. cell_dst.src = -1;
  3749. cache.used -= 1;
  3750. }
  3751. }
  3752. if (tail_src.tail >= 0) {
  3753. llama_kv_cell & cell_src = cache.cells[tail_src.tail];
  3754. cell_src.seq_id.insert(seq_id_dst);
  3755. tail_dst.tail = tail_src.tail;
  3756. }
  3757. }
  3758. return;
  3759. }
  3760. // otherwise, this is the KV cache of a Transformer-like model
  3761. cache.head = 0;
  3762. for (uint32_t i = 0; i < cache.size; ++i) {
  3763. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3764. cache.cells[i].seq_id.insert(seq_id_dst);
  3765. }
  3766. }
  3767. }
  3768. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  3769. uint32_t new_head = cache.size;
  3770. for (uint32_t i = 0; i < cache.size; ++i) {
  3771. if (cache.recurrent && (llama_seq_id) i != seq_id) {
  3772. cache.cells[i].tail = -1;
  3773. }
  3774. if (!cache.cells[i].has_seq_id(seq_id)) {
  3775. if (cache.cells[i].pos >= 0) cache.used--;
  3776. cache.cells[i].pos = -1;
  3777. cache.cells[i].src = -1;
  3778. cache.cells[i].seq_id.clear();
  3779. if (new_head == cache.size) new_head = i;
  3780. } else {
  3781. cache.cells[i].seq_id.clear();
  3782. cache.cells[i].seq_id.insert(seq_id);
  3783. }
  3784. }
  3785. // If we freed up a slot, set head to it so searching can start there.
  3786. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  3787. }
  3788. static void llama_kv_cache_seq_add(
  3789. struct llama_kv_cache & cache,
  3790. llama_seq_id seq_id,
  3791. llama_pos p0,
  3792. llama_pos p1,
  3793. llama_pos delta) {
  3794. uint32_t new_head = cache.size;
  3795. if (p0 < 0) p0 = 0;
  3796. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3797. // If there is no range then return early to avoid looping over the cache.
  3798. if (p0 == p1) return;
  3799. if (cache.recurrent) {
  3800. // for Mamba-like or RWKV models, only the pos needs to be shifted
  3801. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  3802. const int32_t tail_id = cache.cells[seq_id].tail;
  3803. if (tail_id >= 0) {
  3804. llama_kv_cell & cell = cache.cells[tail_id];
  3805. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  3806. cell.pos += delta;
  3807. }
  3808. }
  3809. }
  3810. return;
  3811. }
  3812. for (uint32_t i = 0; i < cache.size; ++i) {
  3813. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3814. cache.has_shift = true;
  3815. cache.cells[i].pos += delta;
  3816. cache.cells[i].delta += delta;
  3817. if (cache.cells[i].pos < 0) {
  3818. if (!cache.cells[i].is_empty()) {
  3819. cache.used--;
  3820. }
  3821. cache.cells[i].pos = -1;
  3822. cache.cells[i].seq_id.clear();
  3823. if (new_head == cache.size) {
  3824. new_head = i;
  3825. }
  3826. }
  3827. }
  3828. }
  3829. // If we freed up a slot, set head to it so searching can start there.
  3830. // Otherwise we just start the next search from the beginning.
  3831. cache.head = new_head != cache.size ? new_head : 0;
  3832. }
  3833. static void llama_kv_cache_seq_div(
  3834. struct llama_kv_cache & cache,
  3835. llama_seq_id seq_id,
  3836. llama_pos p0,
  3837. llama_pos p1,
  3838. int d) {
  3839. if (p0 < 0) p0 = 0;
  3840. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3841. // If there is no range then return early to avoid looping over the cache.
  3842. if (p0 == p1) return;
  3843. if (cache.recurrent) {
  3844. // for Mamba-like or RWKV models, only the pos needs to be changed
  3845. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  3846. const int32_t tail_id = cache.cells[seq_id].tail;
  3847. if (tail_id >= 0) {
  3848. llama_kv_cell & cell = cache.cells[tail_id];
  3849. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  3850. cell.pos /= d;
  3851. }
  3852. }
  3853. }
  3854. return;
  3855. }
  3856. for (uint32_t i = 0; i < cache.size; ++i) {
  3857. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3858. cache.has_shift = true;
  3859. {
  3860. llama_pos p_old = cache.cells[i].pos;
  3861. cache.cells[i].pos /= d;
  3862. cache.cells[i].delta += cache.cells[i].pos - p_old;
  3863. }
  3864. }
  3865. }
  3866. }
  3867. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  3868. llama_pos result = 0;
  3869. for (uint32_t i = 0; i < cache.size; ++i) {
  3870. if (cache.cells[i].has_seq_id(seq_id)) {
  3871. result = std::max(result, cache.cells[i].pos);
  3872. }
  3873. }
  3874. return result;
  3875. }
  3876. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  3877. if (!cache.recurrent) {
  3878. cache.do_defrag = true;
  3879. }
  3880. }
  3881. static uint32_t llama_kv_cache_get_padding(const struct llama_cparams & cparams) {
  3882. // the FA kernels require padding to avoid extra runtime boundary checks
  3883. return cparams.flash_attn ? 256u : 32u;
  3884. }
  3885. // saves the kv_cache state for future recovery.
  3886. // used to rollback llama_kv_cache_find_slot changes.
  3887. struct llama_kv_slot_restorer {
  3888. struct llama_kv_cache_state {
  3889. uint32_t head = 0;
  3890. uint32_t n = 0;
  3891. } old_state;
  3892. // for non-recurrent models only
  3893. // list of slots to restore
  3894. std::vector<std::pair<uint32_t, uint32_t>> slot_boundaries;
  3895. bool do_restore = false;
  3896. explicit llama_kv_slot_restorer(const struct llama_kv_cache & cache) {
  3897. old_state.head = cache.head;
  3898. old_state.n = cache.n;
  3899. }
  3900. // saves a slot information for future restoration
  3901. void save(const struct llama_kv_cache_slot_info & slot) {
  3902. if (slot) {
  3903. do_restore = true;
  3904. if (slot.boundaries.first != slot.boundaries.second) {
  3905. slot_boundaries.push_back(slot.boundaries);
  3906. }
  3907. }
  3908. }
  3909. // must be explicitly called to restore the kv_cache state
  3910. // and rollback changes from all llama_kv_cache_find_slot calls
  3911. void restore(struct llama_kv_cache & cache) {
  3912. if (do_restore) {
  3913. cache.head = old_state.head;
  3914. cache.n = old_state.n;
  3915. if (cache.recurrent) { // recurrent models like Mamba or RWKV can't have a state partially erased
  3916. llama_kv_cache_seq_rm(cache, -1, -1, -1);
  3917. } else {
  3918. for (auto & slot : slot_boundaries) {
  3919. llama_kv_cache_seq_rm(cache, -1, slot.first, slot.second);
  3920. }
  3921. }
  3922. }
  3923. }
  3924. };
  3925. //
  3926. // model loading and saving
  3927. //
  3928. enum llama_fver {
  3929. GGUF_FILE_VERSION_V1 = 1,
  3930. GGUF_FILE_VERSION_V2 = 2,
  3931. GGUF_FILE_VERSION_V3 = 3,
  3932. };
  3933. static const char * llama_file_version_name(llama_fver version) {
  3934. switch (version) {
  3935. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  3936. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  3937. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  3938. }
  3939. return "unknown";
  3940. }
  3941. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  3942. char buf[256];
  3943. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  3944. for (size_t i = 1; i < ne.size(); i++) {
  3945. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  3946. }
  3947. return buf;
  3948. }
  3949. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  3950. char buf[256];
  3951. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  3952. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  3953. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  3954. }
  3955. return buf;
  3956. }
  3957. namespace GGUFMeta {
  3958. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  3959. struct GKV_Base_Type {
  3960. static constexpr gguf_type gt = gt_;
  3961. static T getter(const gguf_context * ctx, const int kid) {
  3962. return gfun(ctx, kid);
  3963. }
  3964. };
  3965. template<typename T> struct GKV_Base;
  3966. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  3967. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  3968. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  3969. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  3970. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  3971. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  3972. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  3973. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  3974. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  3975. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  3976. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  3977. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  3978. template<> struct GKV_Base<std::string> {
  3979. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  3980. static std::string getter(const gguf_context * ctx, const int kid) {
  3981. return gguf_get_val_str(ctx, kid);
  3982. }
  3983. };
  3984. struct ArrayInfo {
  3985. const gguf_type gt;
  3986. const size_t length;
  3987. const void * data;
  3988. };
  3989. template<> struct GKV_Base<ArrayInfo> {
  3990. public:
  3991. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  3992. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  3993. return ArrayInfo {
  3994. gguf_get_arr_type(ctx, k),
  3995. size_t(gguf_get_arr_n(ctx, k)),
  3996. gguf_get_arr_data(ctx, k),
  3997. };
  3998. }
  3999. };
  4000. template<typename T>
  4001. class GKV : public GKV_Base<T> {
  4002. GKV() = delete;
  4003. public:
  4004. static T get_kv(const gguf_context * ctx, const int k) {
  4005. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  4006. if (kt != GKV::gt) {
  4007. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  4008. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  4009. }
  4010. return GKV::getter(ctx, k);
  4011. }
  4012. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  4013. switch (ty) {
  4014. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  4015. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  4016. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  4017. case LLAMA_KV_OVERRIDE_TYPE_STR: return "str";
  4018. }
  4019. return "unknown";
  4020. }
  4021. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  4022. if (!ovrd) { return false; }
  4023. if (ovrd->tag == expected_type) {
  4024. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  4025. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  4026. switch (ovrd->tag) {
  4027. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  4028. LLAMA_LOG_INFO("%s\n", ovrd->val_bool ? "true" : "false");
  4029. } break;
  4030. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  4031. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->val_i64);
  4032. } break;
  4033. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  4034. LLAMA_LOG_INFO("%.6f\n", ovrd->val_f64);
  4035. } break;
  4036. case LLAMA_KV_OVERRIDE_TYPE_STR: {
  4037. LLAMA_LOG_INFO("%s\n", ovrd->val_str);
  4038. } break;
  4039. default:
  4040. // Shouldn't be possible to end up here, but just in case...
  4041. throw std::runtime_error(
  4042. format("Unsupported attempt to override %s type for metadata key %s\n",
  4043. override_type_to_str(ovrd->tag), ovrd->key));
  4044. }
  4045. return true;
  4046. }
  4047. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  4048. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  4049. return false;
  4050. }
  4051. template<typename OT>
  4052. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  4053. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  4054. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  4055. target = ovrd->val_bool;
  4056. return true;
  4057. }
  4058. return false;
  4059. }
  4060. template<typename OT>
  4061. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  4062. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  4063. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  4064. target = ovrd->val_i64;
  4065. return true;
  4066. }
  4067. return false;
  4068. }
  4069. template<typename OT>
  4070. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  4071. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  4072. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  4073. target = ovrd->val_f64;
  4074. return true;
  4075. }
  4076. return false;
  4077. }
  4078. template<typename OT>
  4079. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  4080. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  4081. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_STR, ovrd)) {
  4082. target = ovrd->val_str;
  4083. return true;
  4084. }
  4085. return false;
  4086. }
  4087. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  4088. if (try_override<T>(target, ovrd)) {
  4089. return true;
  4090. }
  4091. if (k < 0) { return false; }
  4092. target = get_kv(ctx, k);
  4093. return true;
  4094. }
  4095. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  4096. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  4097. }
  4098. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  4099. return set(ctx, key.c_str(), target, ovrd);
  4100. }
  4101. };
  4102. }
  4103. using llama_buf_map = std::unordered_map<uint32_t, ggml_backend_buffer_t>;
  4104. static size_t llama_model_max_nodes(const llama_model & model) {
  4105. return std::max<size_t>(8192, model.tensors_by_name.size()*5);
  4106. }
  4107. struct llama_model_loader {
  4108. int n_kv = 0;
  4109. int n_tensors = 0;
  4110. int n_created = 0;
  4111. uint64_t n_elements = 0;
  4112. size_t n_bytes = 0;
  4113. bool use_mmap = false;
  4114. bool check_tensors;
  4115. llama_files files;
  4116. llama_ftype ftype;
  4117. llama_fver fver;
  4118. llama_mmaps mappings;
  4119. // Holds information on a model weight
  4120. struct llama_tensor_weight {
  4121. uint16_t idx; // source file index
  4122. size_t offs; // tensor data offset in the original file
  4123. ggml_tensor * tensor;
  4124. llama_tensor_weight(const llama_file * file, uint16_t idx, const struct gguf_context * gguf_ctx, ggml_tensor * tensor) : idx(idx), tensor(tensor) {
  4125. const int tensor_idx = gguf_find_tensor(gguf_ctx, ggml_get_name(tensor));
  4126. if (tensor_idx < 0) {
  4127. throw std::runtime_error(format("tensor '%s' not found in the model", ggml_get_name(tensor)));
  4128. }
  4129. offs = gguf_get_data_offset(gguf_ctx) + gguf_get_tensor_offset(gguf_ctx, tensor_idx);
  4130. if (offs + ggml_nbytes(tensor) < offs || offs + ggml_nbytes(tensor) > file->size) {
  4131. throw std::runtime_error(format("tensor '%s' data is not within the file bounds, model is corrupted or incomplete", ggml_get_name(tensor)));
  4132. }
  4133. }
  4134. };
  4135. // custom comparator to sort weights more nicely by layer
  4136. struct weight_name_comparer {
  4137. bool operator()(const std::string & a, const std::string & b) const {
  4138. int a_layer = -1;
  4139. int b_layer = -1;
  4140. sscanf(a.c_str(), "blk.%d.", &a_layer);
  4141. sscanf(b.c_str(), "blk.%d.", &b_layer);
  4142. if (a_layer != b_layer) {
  4143. return a_layer < b_layer;
  4144. }
  4145. return a < b;
  4146. }
  4147. };
  4148. std::map<std::string, struct llama_tensor_weight, weight_name_comparer> weights_map;
  4149. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  4150. gguf_context_ptr meta;
  4151. std::vector<ggml_context_ptr> contexts;
  4152. std::string arch_name;
  4153. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  4154. llama_model_loader(const std::string & fname, bool use_mmap, bool check_tensors, const struct llama_model_kv_override * param_overrides_p) {
  4155. int trace = 0;
  4156. if (getenv("LLAMA_TRACE")) {
  4157. trace = atoi(getenv("LLAMA_TRACE"));
  4158. }
  4159. if (param_overrides_p != nullptr) {
  4160. for (const struct llama_model_kv_override * p = param_overrides_p; p->key[0] != 0; p++) {
  4161. kv_overrides.insert({std::string(p->key), *p});
  4162. }
  4163. }
  4164. struct ggml_context * ctx = NULL;
  4165. struct gguf_init_params params = {
  4166. /*.no_alloc = */ true,
  4167. /*.ctx = */ &ctx,
  4168. };
  4169. meta.reset(gguf_init_from_file(fname.c_str(), params));
  4170. if (!meta) {
  4171. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  4172. }
  4173. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  4174. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  4175. files.emplace_back(new llama_file(fname.c_str(), "rb"));
  4176. contexts.emplace_back(ctx);
  4177. // Save tensors data offset of the main file.
  4178. // For subsidiary files, `meta` tensor data offset must not be used,
  4179. // so we build a unified tensors index for weights.
  4180. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  4181. std::string tensor_name = std::string(cur->name);
  4182. // make sure there is no duplicated tensor names
  4183. if (weights_map.find(tensor_name) != weights_map.end()) {
  4184. throw std::runtime_error(format("invalid model: tensor '%s' is duplicated", ggml_get_name(cur)));
  4185. }
  4186. n_elements += ggml_nelements(cur);
  4187. n_bytes += ggml_nbytes(cur);
  4188. weights_map.emplace(tensor_name, llama_tensor_weight(files.back().get(), 0, meta.get(), cur));
  4189. }
  4190. uint16_t n_split = 0;
  4191. get_key(llm_kv(LLM_KV_SPLIT_COUNT), n_split, false);
  4192. // Load additional GGML contexts
  4193. if (n_split > 1) {
  4194. uint16_t idx = 0;
  4195. get_key(llm_kv(LLM_KV_SPLIT_NO), idx);
  4196. if (idx != 0) {
  4197. throw std::runtime_error(format("illegal split file: %d, model must be loaded with the first split", idx));
  4198. }
  4199. char split_prefix[PATH_MAX] = {0};
  4200. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), fname.c_str(), idx, n_split)) {
  4201. throw std::runtime_error(format("invalid split file: %s", fname.c_str()));
  4202. }
  4203. if (trace > 0) {
  4204. LLAMA_LOG_INFO("%s: loading additional %d GGUFs\n", __func__, n_split);
  4205. }
  4206. char split_path[PATH_MAX] = {0};
  4207. for (idx = 1; idx < n_split; idx++) {
  4208. llama_split_path(split_path, sizeof(split_path), split_prefix, idx, n_split);
  4209. struct gguf_init_params split_params = {
  4210. /*.no_alloc = */ true,
  4211. /*.ctx = */ &ctx,
  4212. };
  4213. gguf_context_ptr ctx_gguf { gguf_init_from_file(split_path, split_params) };
  4214. if (!ctx_gguf) {
  4215. throw std::runtime_error(format("%s: failed to load GGUF split from %s\n", __func__, split_path));
  4216. }
  4217. files.emplace_back(new llama_file(split_path, "rb"));
  4218. contexts.emplace_back(ctx);
  4219. // Save tensors data offset info of the shard.
  4220. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  4221. std::string tensor_name = std::string(cur->name);
  4222. // make sure there is no duplicated tensor names
  4223. if (weights_map.find(tensor_name) != weights_map.end()) {
  4224. throw std::runtime_error(format("invalid model: tensor '%s' is duplicated", ggml_get_name(cur)));
  4225. }
  4226. n_elements += ggml_nelements(cur);
  4227. n_bytes += ggml_nbytes(cur);
  4228. weights_map.emplace(tensor_name, llama_tensor_weight(files.back().get(), idx, ctx_gguf.get(), cur));
  4229. }
  4230. }
  4231. get_key(llm_kv(LLM_KV_SPLIT_TENSORS_COUNT), n_tensors);
  4232. // sanity check
  4233. {
  4234. const int n_tensors_loaded = (int) weights_map.size();
  4235. if (n_tensors != n_tensors_loaded) {
  4236. throw std::runtime_error(format("corrupted model: %d tensors expected but %d found", n_tensors, n_tensors_loaded));
  4237. }
  4238. }
  4239. LLAMA_LOG_INFO("%s: additional %d GGUFs metadata loaded.\n", __func__, n_split - 1);
  4240. }
  4241. n_kv = gguf_get_n_kv(meta.get());
  4242. n_tensors = weights_map.size();
  4243. fver = (enum llama_fver) gguf_get_version(meta.get());
  4244. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  4245. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  4246. // determine file type based on the number of tensors for each quantization and print meta data
  4247. // TODO: make optional
  4248. {
  4249. std::map<enum ggml_type, uint32_t> n_type;
  4250. uint32_t n_type_max = 0;
  4251. enum ggml_type type_max = GGML_TYPE_F32;
  4252. for (const auto & it : weights_map) {
  4253. const llama_tensor_weight & w = it.second;
  4254. const ggml_tensor * tensor = w.tensor;
  4255. enum ggml_type type = tensor->type;
  4256. n_type[type]++;
  4257. if (n_type_max < n_type[type]) {
  4258. n_type_max = n_type[type];
  4259. type_max = type;
  4260. }
  4261. if (trace > 0) {
  4262. const uint16_t sid = w.idx;
  4263. 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());
  4264. }
  4265. }
  4266. switch (type_max) {
  4267. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  4268. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  4269. case GGML_TYPE_BF16: ftype = LLAMA_FTYPE_MOSTLY_BF16; break;
  4270. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  4271. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  4272. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  4273. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  4274. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  4275. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  4276. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  4277. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  4278. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  4279. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  4280. case GGML_TYPE_TQ1_0: ftype = LLAMA_FTYPE_MOSTLY_TQ1_0; break;
  4281. case GGML_TYPE_TQ2_0: ftype = LLAMA_FTYPE_MOSTLY_TQ2_0; break;
  4282. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  4283. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  4284. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  4285. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  4286. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  4287. case GGML_TYPE_IQ1_M: ftype = LLAMA_FTYPE_MOSTLY_IQ1_M; break;
  4288. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  4289. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  4290. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  4291. default:
  4292. {
  4293. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  4294. ftype = LLAMA_FTYPE_ALL_F32;
  4295. } break;
  4296. }
  4297. // this is a way to mark that we have "guessed" the file type
  4298. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  4299. {
  4300. const int kid = gguf_find_key(meta.get(), "general.file_type"); // TODO: use LLM_KV
  4301. if (kid >= 0) {
  4302. ftype = (llama_ftype) gguf_get_val_u32(meta.get(), kid);
  4303. }
  4304. }
  4305. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  4306. for (int i = 0; i < n_kv; i++) {
  4307. const char * name = gguf_get_key(meta.get(), i);
  4308. const enum gguf_type type = gguf_get_kv_type(meta.get(), i);
  4309. const std::string type_name =
  4310. type == GGUF_TYPE_ARRAY
  4311. ? 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))
  4312. : gguf_type_name(type);
  4313. std::string value = gguf_kv_to_str(meta.get(), i);
  4314. const size_t MAX_VALUE_LEN = 40;
  4315. if (value.size() > MAX_VALUE_LEN) {
  4316. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  4317. }
  4318. replace_all(value, "\n", "\\n");
  4319. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  4320. }
  4321. // print type counts
  4322. for (auto & kv : n_type) {
  4323. if (kv.second == 0) {
  4324. continue;
  4325. }
  4326. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  4327. }
  4328. }
  4329. if (!llama_mmap::SUPPORTED) {
  4330. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  4331. use_mmap = false;
  4332. }
  4333. this->use_mmap = use_mmap;
  4334. this->check_tensors = check_tensors;
  4335. }
  4336. template<typename T>
  4337. typename std::enable_if<std::is_integral<T>::value, bool>::type
  4338. get_arr_n(const std::string & key, T & result, const bool required = true) {
  4339. const int kid = gguf_find_key(meta.get(), key.c_str());
  4340. if (kid < 0) {
  4341. if (required) {
  4342. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  4343. }
  4344. return false;
  4345. }
  4346. struct GGUFMeta::ArrayInfo arr_info =
  4347. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta.get(), kid);
  4348. result = arr_info.length;
  4349. return true;
  4350. }
  4351. template<typename T>
  4352. typename std::enable_if<std::is_integral<T>::value, bool>::type
  4353. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  4354. return get_arr_n(llm_kv(kid), result, required);
  4355. }
  4356. template<typename T>
  4357. bool get_arr(const std::string & key, std::vector<T> & result, const bool required = true) {
  4358. const int kid = gguf_find_key(meta.get(), key.c_str());
  4359. if (kid < 0 || gguf_get_kv_type(meta.get(), kid) != GGUF_TYPE_ARRAY) {
  4360. if (required) {
  4361. throw std::runtime_error(format("array key not found in model: %s", key.c_str()));
  4362. }
  4363. return false;
  4364. }
  4365. struct GGUFMeta::ArrayInfo arr_info =
  4366. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta.get(), kid);
  4367. switch (arr_info.gt) {
  4368. case GGUF_TYPE_FLOAT32: GGML_ASSERT((std::is_same<T, float>::value)); break;
  4369. case GGUF_TYPE_INT32: GGML_ASSERT(
  4370. (std::is_same<T, int32_t>::value) ||
  4371. (std::is_same<T, uint32_t>::value)); break;
  4372. default:
  4373. throw std::runtime_error(format("%s is not a float32, int32 array", key.c_str()));
  4374. }
  4375. result.resize(arr_info.length);
  4376. result.assign((const T*)arr_info.data, (const T *)arr_info.data + arr_info.length);
  4377. return true;
  4378. }
  4379. template<typename T, size_t N_MAX>
  4380. bool get_arr(const std::string & key, std::array<T, N_MAX> & result, const bool required = true) {
  4381. const int kid = gguf_find_key(meta.get(), key.c_str());
  4382. if (kid < 0 || gguf_get_kv_type(meta.get(), kid) != GGUF_TYPE_ARRAY) {
  4383. if (required) {
  4384. throw std::runtime_error(format("array key not found in model: %s", key.c_str()));
  4385. }
  4386. return false;
  4387. }
  4388. struct GGUFMeta::ArrayInfo arr_info =
  4389. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta.get(), kid);
  4390. switch (arr_info.gt) {
  4391. case GGUF_TYPE_FLOAT32: GGML_ASSERT((std::is_same<T, float>::value)); break;
  4392. case GGUF_TYPE_INT32: GGML_ASSERT(
  4393. (std::is_same<T, int32_t>::value) ||
  4394. (std::is_same<T, uint32_t>::value)); break;
  4395. default:
  4396. throw std::runtime_error(format("%s is not a float32, int32 array", key.c_str()));
  4397. }
  4398. if (arr_info.length > N_MAX) {
  4399. 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));
  4400. }
  4401. std::copy((const T*)arr_info.data, (const T *)arr_info.data + arr_info.length, result.begin());
  4402. return true;
  4403. }
  4404. template<typename T>
  4405. bool get_arr(const enum llm_kv kid, T & result, const bool required = true) {
  4406. return get_arr(llm_kv(kid), result, required);
  4407. }
  4408. template<typename T>
  4409. bool get_key(const std::string & key, T & result, const bool required = true) {
  4410. auto it = kv_overrides.find(key);
  4411. const struct llama_model_kv_override * override =
  4412. it != kv_overrides.end() ? &it->second : nullptr;
  4413. const bool found = GGUFMeta::GKV<T>::set(meta.get(), key, result, override);
  4414. if (required && !found) {
  4415. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  4416. }
  4417. return found;
  4418. }
  4419. template<typename T>
  4420. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  4421. return get_key(llm_kv(kid), result, required);
  4422. }
  4423. // get array of n <= N_MAX elements, or a single element repeated n times
  4424. template<typename T, size_t N_MAX>
  4425. bool get_key_or_arr(const std::string & key, std::array<T, N_MAX> & result, uint32_t n, const bool required = true) {
  4426. const int kid = gguf_find_key(meta.get(), key.c_str());
  4427. if (kid < 0) {
  4428. if (required) {
  4429. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  4430. }
  4431. return false;
  4432. }
  4433. if (n > N_MAX) {
  4434. throw std::runtime_error(format("n > N_MAX: %u > %u for key %s", (uint32_t) n, (uint32_t) N_MAX, key.c_str()));
  4435. }
  4436. if (gguf_get_kv_type(meta.get(), kid) == GGUF_TYPE_ARRAY) {
  4437. struct GGUFMeta::ArrayInfo arr_info =
  4438. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta.get(), kid);
  4439. if (n != arr_info.length) {
  4440. throw std::runtime_error(format("key %s has wrong array length; expected %u, got %u", key.c_str(), n, (uint32_t) arr_info.length));
  4441. }
  4442. return get_arr(key, result, required);
  4443. } else {
  4444. T value;
  4445. bool ok = get_key(key, value, required);
  4446. if (!ok) {
  4447. return false;
  4448. }
  4449. for (uint32_t i = 0; i < n; i++) {
  4450. result[i] = value;
  4451. }
  4452. return true;
  4453. }
  4454. }
  4455. template<typename T>
  4456. bool get_key_or_arr(const enum llm_kv kid, T & result, uint32_t n, const bool required = true) {
  4457. return get_key_or_arr(llm_kv(kid), result, n, required);
  4458. }
  4459. std::string get_arch_name() const {
  4460. return arch_name;
  4461. }
  4462. enum llm_arch get_arch() const {
  4463. return llm_kv.arch;
  4464. }
  4465. const llama_tensor_weight * get_weight(const char * name) const {
  4466. auto pos = weights_map.find(name);
  4467. if (pos != weights_map.end()) {
  4468. return &pos->second;
  4469. }
  4470. return nullptr;
  4471. }
  4472. const llama_tensor_weight & require_weight(const char * name) const {
  4473. const llama_tensor_weight * weight = get_weight(name);
  4474. if (!weight) {
  4475. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  4476. }
  4477. return *weight;
  4478. }
  4479. struct ggml_tensor * get_tensor_meta(const char * name) const {
  4480. const auto * weight = get_weight(name);
  4481. if (!weight) {
  4482. return nullptr;
  4483. }
  4484. return weight->tensor;
  4485. }
  4486. struct ggml_tensor * require_tensor_meta(const std::string & name) const {
  4487. struct ggml_tensor * tensor = get_tensor_meta(name.c_str());
  4488. if (!tensor) {
  4489. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  4490. }
  4491. return tensor;
  4492. }
  4493. const struct ggml_tensor * check_tensor_dims(const std::string & name, const std::vector<int64_t> & ne, bool required) const {
  4494. const struct ggml_tensor * cur = get_tensor_meta(name.c_str());
  4495. if (cur == NULL) {
  4496. if (!required) {
  4497. return NULL;
  4498. }
  4499. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  4500. }
  4501. {
  4502. bool is_ok = true;
  4503. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  4504. if ((i < ne.size() && ne[i] != cur->ne[i]) || (i >= ne.size() && cur->ne[i] != 1)) {
  4505. is_ok = false;
  4506. break;
  4507. }
  4508. }
  4509. if (!is_ok) {
  4510. throw std::runtime_error(
  4511. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  4512. __func__, name.c_str(),
  4513. llama_format_tensor_shape(ne).c_str(),
  4514. llama_format_tensor_shape(cur).c_str()));
  4515. }
  4516. }
  4517. return cur;
  4518. }
  4519. static const int TENSOR_NOT_REQUIRED = 1;
  4520. static const int TENSOR_DUPLICATED = 2;
  4521. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::initializer_list<int64_t> & ne, int flags = 0) {
  4522. const struct ggml_tensor * cur = check_tensor_dims(name, ne, !(flags & TENSOR_NOT_REQUIRED));
  4523. if (cur == NULL) {
  4524. return NULL;
  4525. }
  4526. bool duplicated = flags & TENSOR_DUPLICATED;
  4527. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, cur);
  4528. ggml_set_name(tensor, ggml_get_name(cur));
  4529. if (duplicated) {
  4530. size_data += ggml_nbytes(cur);
  4531. } else {
  4532. n_created++;
  4533. }
  4534. return tensor;
  4535. }
  4536. 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) {
  4537. const struct ggml_tensor * cur = check_tensor_dims(name, ne, required);
  4538. if (cur == NULL) {
  4539. return NULL;
  4540. }
  4541. if (cur->type != base->type) {
  4542. 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)));
  4543. }
  4544. std::array<int64_t, GGML_MAX_DIMS> dims;
  4545. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  4546. dims[i] = i < ne.size() ? ne.begin()[i] : 1;
  4547. }
  4548. struct ggml_tensor * tensor = ggml_view_4d(ctx, base,
  4549. dims[0], dims[1], dims[2], dims[3],
  4550. cur->nb[1], cur->nb[2], cur->nb[3],
  4551. offset);
  4552. ggml_set_name(tensor, name.c_str());
  4553. n_created++;
  4554. return tensor;
  4555. }
  4556. void done_getting_tensors() const {
  4557. if (n_created != n_tensors) {
  4558. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  4559. }
  4560. }
  4561. void init_mappings(bool prefetch = true, llama_mlocks * mlock_mmaps = nullptr) {
  4562. if (use_mmap) {
  4563. mappings.reserve(files.size());
  4564. mmaps_used.reserve(files.size());
  4565. for (const auto & file : files) {
  4566. auto * reg = ggml_backend_dev_backend_reg(ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU));
  4567. auto * is_numa_fn = (decltype(ggml_is_numa) *) ggml_backend_reg_get_proc_address(reg, "ggml_backend_cpu_is_numa");
  4568. std::unique_ptr<llama_mmap> mapping(new llama_mmap(file.get(), prefetch ? -1 : 0, is_numa_fn()));
  4569. mmaps_used.emplace_back(mapping->size, 0);
  4570. if (mlock_mmaps) {
  4571. std::unique_ptr<llama_mlock> mlock_mmap(new llama_mlock());
  4572. mlock_mmap->init(mapping->addr);
  4573. mlock_mmaps->emplace_back(std::move(mlock_mmap));
  4574. }
  4575. mappings.emplace_back(std::move(mapping));
  4576. }
  4577. }
  4578. // compute the total size of all tensors for progress reporting
  4579. for (const auto & it : weights_map) {
  4580. size_data += ggml_nbytes(it.second.tensor);
  4581. }
  4582. }
  4583. void get_mapping_range(size_t * first, size_t * last, void ** addr, int idx, ggml_context * ctx) const {
  4584. GGML_ASSERT(!mappings.empty());
  4585. const auto & mapping = mappings.at(idx);
  4586. *first = mapping->size;
  4587. *last = 0;
  4588. *addr = mapping->addr;
  4589. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  4590. const auto * weight = get_weight(ggml_get_name(tensor));
  4591. if (!weight || weight->idx != idx) {
  4592. continue;
  4593. }
  4594. *first = std::min(*first, weight->offs);
  4595. *last = std::max(*last, weight->offs + ggml_nbytes(tensor));
  4596. }
  4597. }
  4598. // for backwards compatibility, does not support ggml-backend
  4599. void load_data_for(struct ggml_tensor * cur) const {
  4600. const auto & w = require_weight(ggml_get_name(cur));
  4601. if (use_mmap) {
  4602. const auto & mapping = mappings.at(w.idx);
  4603. if (cur->data == nullptr) {
  4604. cur->data = (uint8_t *)mapping->addr + w.offs;
  4605. } else {
  4606. memcpy(cur->data, (uint8_t *)mapping->addr + w.offs, ggml_nbytes(cur));
  4607. }
  4608. } else {
  4609. GGML_ASSERT(cur->data != nullptr);
  4610. GGML_ASSERT(w.idx < files.size());
  4611. const auto & file = files.at(w.idx);
  4612. file->seek(w.offs, SEEK_SET);
  4613. file->read_raw(cur->data, ggml_nbytes(cur));
  4614. }
  4615. if (check_tensors && !ggml_validate_row_data(cur->type, cur->data, ggml_nbytes(cur))) {
  4616. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  4617. }
  4618. }
  4619. size_t size_done = 0;
  4620. size_t size_data = 0;
  4621. std::vector<std::pair<size_t, size_t>> mmaps_used;
  4622. // Returns false if cancelled by progress_callback
  4623. bool load_all_data(
  4624. struct ggml_context * ctx,
  4625. llama_buf_map & bufs,
  4626. llama_mlocks * lmlocks,
  4627. llama_progress_callback progress_callback,
  4628. void * progress_callback_user_data) {
  4629. GGML_ASSERT(size_data != 0 && "call init_mappings() first");
  4630. std::vector<no_init<uint8_t>> read_buf;
  4631. std::vector<std::future<std::pair<ggml_tensor *, bool>>> validation_result;
  4632. // 4 staging buffers for async uploads, each sized 1MB seems to be a good default for single NVMe drives.
  4633. // NVMe raid configurations might require more / larger buffers.
  4634. constexpr size_t n_buffers = 4;
  4635. constexpr size_t buffer_size = 1 * 1024 * 1024; // 1MB
  4636. std::vector<ggml_backend_buffer_t> host_buffers;
  4637. std::vector<ggml_backend_event_t> events;
  4638. std::vector<void *> host_ptrs;
  4639. size_t buffer_idx = 0; // buffer to use for async loads
  4640. ggml_backend_t upload_backend = [&](const char * func) -> ggml_backend_t {
  4641. if (use_mmap || check_tensors) {
  4642. return nullptr;
  4643. }
  4644. // When not using mmaped io use async uploads from pinned memory to GPU memory.
  4645. // First determine if the backend supports the necessary features for async uploads.
  4646. auto * buf = bufs.count(0) ? bufs.at(0) : nullptr;
  4647. if (!buf) {
  4648. LLAMA_LOG_DEBUG("%s: no buffer found for async uploads\n", func);
  4649. return nullptr;
  4650. }
  4651. auto * buft = ggml_backend_buffer_get_type(buf);
  4652. auto * dev = ggml_backend_buft_get_device(buft);
  4653. if (!dev) {
  4654. LLAMA_LOG_DEBUG("%s: no device found for buffer type %s for async uploads\n", func,
  4655. ggml_backend_buft_name(buft));
  4656. return nullptr;
  4657. }
  4658. if (buft != ggml_backend_dev_buffer_type(dev)) {
  4659. LLAMA_LOG_DEBUG("%s: buffer type %s is not the default buffer type for device %s for async uploads\n", func,
  4660. ggml_backend_buft_name(buft), ggml_backend_dev_name(dev));
  4661. return nullptr;
  4662. }
  4663. ggml_backend_dev_props props;
  4664. ggml_backend_dev_get_props(dev, &props);
  4665. if (!props.caps.async || !props.caps.host_buffer || !props.caps.events) {
  4666. LLAMA_LOG_DEBUG("%s: device %s does not support async, host buffers or events\n", func,
  4667. ggml_backend_dev_name(dev));
  4668. return nullptr;
  4669. }
  4670. auto * host_buft = ggml_backend_dev_host_buffer_type(dev);
  4671. if (!host_buft) {
  4672. LLAMA_LOG_DEBUG("%s: no host buffer type found for device %s\n", func,
  4673. ggml_backend_dev_name(dev));
  4674. return nullptr;
  4675. }
  4676. // If the backend is supported, create pinned memory buffers and events for synchronisation.
  4677. for (size_t idx = 0; idx < n_buffers; ++idx) {
  4678. auto * buf = ggml_backend_buft_alloc_buffer(host_buft, buffer_size);
  4679. if (!buf) {
  4680. LLAMA_LOG_DEBUG("%s: failed to allocate host buffer for async uploads for device %s\n", func,
  4681. ggml_backend_dev_name(dev));
  4682. return nullptr;
  4683. }
  4684. host_buffers.emplace_back(buf);
  4685. host_ptrs.emplace_back(ggml_backend_buffer_get_base(buf));
  4686. auto * event = ggml_backend_event_new(dev);
  4687. if (!event) {
  4688. LLAMA_LOG_DEBUG("%s: failed to create event for async uploads for device %s\n", func,
  4689. ggml_backend_dev_name(dev));
  4690. return nullptr;
  4691. }
  4692. events.emplace_back(event);
  4693. }
  4694. ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr);
  4695. if (!backend) {
  4696. LLAMA_LOG_DEBUG("%s: failed to initialize backend for device %s for async uploads\n", func,
  4697. ggml_backend_dev_name(dev));
  4698. return nullptr;
  4699. }
  4700. return backend;
  4701. }(__func__);
  4702. if (upload_backend) {
  4703. LLAMA_LOG_DEBUG("%s: using async uploads for device %s, buffer type %s, backend %s\n", __func__,
  4704. ggml_backend_dev_name(ggml_backend_get_device(upload_backend)),
  4705. ggml_backend_buft_name(ggml_backend_buffer_get_type(bufs.at(0))),
  4706. ggml_backend_name(upload_backend));
  4707. }
  4708. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  4709. const auto * weight = get_weight(ggml_get_name(cur));
  4710. if (weight == nullptr) {
  4711. // this can happen with split experts models
  4712. continue;
  4713. }
  4714. if (progress_callback) {
  4715. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  4716. return false;
  4717. }
  4718. }
  4719. size_t n_size = ggml_nbytes(cur);
  4720. if (use_mmap) {
  4721. const auto & mapping = mappings.at(weight->idx);
  4722. ggml_backend_buffer_t buf_mmap = nullptr;
  4723. if (bufs.count(weight->idx)) {
  4724. buf_mmap = bufs.at(weight->idx);
  4725. }
  4726. uint8_t * data = (uint8_t *) mapping->addr + weight->offs;
  4727. if (check_tensors) {
  4728. validation_result.emplace_back(std::async(std::launch::async, [cur, data, n_size] {
  4729. return std::make_pair(cur, ggml_validate_row_data(cur->type, data, n_size));
  4730. }));
  4731. }
  4732. GGML_ASSERT(buf_mmap || cur->data); // either we have a buffer to allocate the tensor in, or it is already allocated
  4733. if (buf_mmap && cur->data == nullptr) {
  4734. ggml_backend_tensor_alloc(buf_mmap, cur, data);
  4735. if (lmlocks) {
  4736. const auto & lmlock = lmlocks->at(weight->idx);
  4737. lmlock->grow_to(weight->offs + n_size);
  4738. }
  4739. auto & mmap_used = mmaps_used[weight->idx];
  4740. mmap_used.first = std::min(mmap_used.first, weight->offs);
  4741. mmap_used.second = std::max(mmap_used.second, weight->offs + n_size);
  4742. } else {
  4743. ggml_backend_tensor_set(cur, data, 0, n_size);
  4744. }
  4745. } else {
  4746. const auto & file = files.at(weight->idx);
  4747. if (ggml_backend_buffer_is_host(cur->buffer)) {
  4748. file->seek(weight->offs, SEEK_SET);
  4749. file->read_raw(cur->data, n_size);
  4750. if (check_tensors) {
  4751. validation_result.emplace_back(std::async(std::launch::async, [cur, n_size] {
  4752. return std::make_pair(cur, ggml_validate_row_data(cur->type, cur->data, n_size));
  4753. }));
  4754. }
  4755. } else {
  4756. // If upload_backend is valid load the tensor in chunks to pinned memory and upload the buffers asynchronously to the GPU.
  4757. if (upload_backend) {
  4758. file->seek(weight->offs, SEEK_SET);
  4759. size_t bytes_read = 0;
  4760. while (bytes_read < n_size) {
  4761. size_t read_iteration = std::min<size_t>(buffer_size, n_size - bytes_read);
  4762. ggml_backend_event_synchronize(events[buffer_idx]);
  4763. file->read_raw(host_ptrs[buffer_idx], read_iteration);
  4764. ggml_backend_tensor_set_async(upload_backend, cur, host_ptrs[buffer_idx], bytes_read, read_iteration);
  4765. ggml_backend_event_record(events[buffer_idx], upload_backend);
  4766. bytes_read += read_iteration;
  4767. ++buffer_idx;
  4768. buffer_idx %= n_buffers;
  4769. }
  4770. } else {
  4771. read_buf.resize(n_size);
  4772. file->seek(weight->offs, SEEK_SET);
  4773. file->read_raw(read_buf.data(), n_size);
  4774. ggml_backend_tensor_set(cur, read_buf.data(), 0, n_size);
  4775. if (check_tensors && !ggml_validate_row_data(cur->type, read_buf.data(), n_size)) {
  4776. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  4777. }
  4778. }
  4779. }
  4780. }
  4781. size_done += n_size;
  4782. }
  4783. // free temporary resources used for async uploads
  4784. for (auto * event : events) {
  4785. ggml_backend_event_synchronize(event);
  4786. ggml_backend_event_free(event);
  4787. }
  4788. for (auto * buf : host_buffers) {
  4789. ggml_backend_buffer_free(buf);
  4790. }
  4791. ggml_backend_free(upload_backend);
  4792. // check validation results
  4793. bool validation_failed = false;
  4794. for (auto & future : validation_result) {
  4795. auto result = future.get();
  4796. if (!result.second) {
  4797. LLAMA_LOG_ERROR("%s: tensor '%s' has invalid data\n", __func__, ggml_get_name(result.first));
  4798. validation_failed = true;
  4799. }
  4800. }
  4801. if (validation_failed) {
  4802. throw std::runtime_error("found tensors with invalid data");
  4803. }
  4804. // check if this is the last call and do final cleanup
  4805. if (size_done >= size_data) {
  4806. // unmap offloaded tensors and metadata
  4807. if (use_mmap) {
  4808. for (uint32_t idx = 0; idx < mappings.size(); idx++) {
  4809. const auto & mmap_used = mmaps_used.at(idx);
  4810. auto & mapping = mappings.at(idx);
  4811. mapping->unmap_fragment(0, mmap_used.first);
  4812. if (mmap_used.second != 0) {
  4813. mapping->unmap_fragment(mmap_used.second, mapping->size);
  4814. }
  4815. }
  4816. }
  4817. if (progress_callback) {
  4818. // Even though the model is done loading, we still honor
  4819. // cancellation since we need to free allocations.
  4820. return progress_callback(1.0f, progress_callback_user_data);
  4821. }
  4822. }
  4823. return true;
  4824. }
  4825. };
  4826. // temporary allocate memory for the input batch if needed
  4827. static const llama_seq_id batch_default_seq_id = 0;
  4828. struct llama_batch_allocr {
  4829. std::array<llama_seq_id, 1> seq_id_0 = {batch_default_seq_id};
  4830. std::vector<llama_pos> pos;
  4831. std::vector<int32_t> n_seq_id;
  4832. std::vector<llama_seq_id *> seq_id;
  4833. std::vector<int8_t> logits;
  4834. struct llama_batch batch;
  4835. // optionally fulfill the batch returned by llama_batch_get_one
  4836. llama_batch_allocr(llama_context & ctx, struct llama_batch in_batch) {
  4837. batch = in_batch;
  4838. GGML_ASSERT(batch.n_tokens > 0);
  4839. if (!batch.pos) {
  4840. // determine the last position in KV cache
  4841. llama_pos last_pos = -1;
  4842. for (const auto & cell : ctx.kv_self.cells) {
  4843. if (cell.has_seq_id(batch_default_seq_id)) {
  4844. last_pos = std::max(last_pos, cell.pos);
  4845. }
  4846. }
  4847. last_pos++; // next position
  4848. pos.resize(batch.n_tokens);
  4849. for (int32_t i = 0; i < batch.n_tokens; i++) {
  4850. pos[i] = i+last_pos;
  4851. }
  4852. batch.pos = pos.data();
  4853. }
  4854. if (!batch.n_seq_id) {
  4855. n_seq_id.resize(batch.n_tokens);
  4856. for (int32_t i = 0; i < batch.n_tokens; i++) {
  4857. n_seq_id[i] = seq_id_0.size();
  4858. }
  4859. batch.n_seq_id = n_seq_id.data();
  4860. }
  4861. if (!batch.seq_id) {
  4862. seq_id.resize(batch.n_tokens + 1);
  4863. seq_id[batch.n_tokens] = NULL;
  4864. for (int32_t i = 0; i < batch.n_tokens; i++) {
  4865. seq_id[i] = seq_id_0.data();
  4866. }
  4867. batch.seq_id = seq_id.data();
  4868. }
  4869. if (!batch.logits) {
  4870. logits.resize(batch.n_tokens);
  4871. logits[logits.size() - 1] = true;
  4872. batch.logits = logits.data();
  4873. }
  4874. }
  4875. };
  4876. template<>
  4877. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  4878. uint32_t tmp;
  4879. const bool found = get_key(kid, tmp, required);
  4880. if (found) {
  4881. result = (enum llama_pooling_type) tmp;
  4882. } else {
  4883. result = LLAMA_POOLING_TYPE_UNSPECIFIED;
  4884. }
  4885. return found;
  4886. }
  4887. //
  4888. // load LLaMA models
  4889. //
  4890. static const char * llama_model_arch_name(llm_arch arch) {
  4891. auto it = LLM_ARCH_NAMES.find(arch);
  4892. if (it == LLM_ARCH_NAMES.end()) {
  4893. return "unknown";
  4894. }
  4895. return it->second;
  4896. }
  4897. static std::string llama_model_ftype_name(llama_ftype ftype) {
  4898. if (ftype & LLAMA_FTYPE_GUESSED) {
  4899. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  4900. }
  4901. switch (ftype) {
  4902. case LLAMA_FTYPE_ALL_F32: return "all F32";
  4903. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  4904. case LLAMA_FTYPE_MOSTLY_BF16: return "BF16";
  4905. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  4906. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  4907. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  4908. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  4909. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  4910. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  4911. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  4912. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  4913. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  4914. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  4915. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  4916. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  4917. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  4918. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  4919. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  4920. case LLAMA_FTYPE_MOSTLY_TQ1_0: return "TQ1_0 - 1.69 bpw ternary";
  4921. case LLAMA_FTYPE_MOSTLY_TQ2_0: return "TQ2_0 - 2.06 bpw ternary";
  4922. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: return "IQ2_XXS - 2.0625 bpw";
  4923. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  4924. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  4925. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  4926. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  4927. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: return "IQ3_XXS - 3.0625 bpw";
  4928. case LLAMA_FTYPE_MOSTLY_IQ1_S: return "IQ1_S - 1.5625 bpw";
  4929. case LLAMA_FTYPE_MOSTLY_IQ1_M: return "IQ1_M - 1.75 bpw";
  4930. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  4931. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  4932. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  4933. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  4934. default: return "unknown, may not work";
  4935. }
  4936. }
  4937. static const char * llama_model_type_name(e_model type) {
  4938. switch (type) {
  4939. case MODEL_14M: return "14M";
  4940. case MODEL_17M: return "17M";
  4941. case MODEL_22M: return "22M";
  4942. case MODEL_33M: return "33M";
  4943. case MODEL_60M: return "60M";
  4944. case MODEL_70M: return "70M";
  4945. case MODEL_80M: return "80M";
  4946. case MODEL_109M: return "109M";
  4947. case MODEL_137M: return "137M";
  4948. case MODEL_160M: return "160M";
  4949. case MODEL_220M: return "220M";
  4950. case MODEL_250M: return "250M";
  4951. case MODEL_270M: return "270M";
  4952. case MODEL_335M: return "335M";
  4953. case MODEL_410M: return "410M";
  4954. case MODEL_450M: return "450M";
  4955. case MODEL_770M: return "770M";
  4956. case MODEL_780M: return "780M";
  4957. case MODEL_0_5B: return "0.5B";
  4958. case MODEL_1B: return "1B";
  4959. case MODEL_1_3B: return "1.3B";
  4960. case MODEL_1_4B: return "1.4B";
  4961. case MODEL_1_5B: return "1.5B";
  4962. case MODEL_1_6B: return "1.6B";
  4963. case MODEL_2B: return "2B";
  4964. case MODEL_2_8B: return "2.8B";
  4965. case MODEL_3B: return "3B";
  4966. case MODEL_4B: return "4B";
  4967. case MODEL_6B: return "6B";
  4968. case MODEL_6_9B: return "6.9B";
  4969. case MODEL_7B: return "7B";
  4970. case MODEL_8B: return "8B";
  4971. case MODEL_9B: return "9B";
  4972. case MODEL_11B: return "11B";
  4973. case MODEL_12B: return "12B";
  4974. case MODEL_13B: return "13B";
  4975. case MODEL_14B: return "14B";
  4976. case MODEL_15B: return "15B";
  4977. case MODEL_16B: return "16B";
  4978. case MODEL_20B: return "20B";
  4979. case MODEL_30B: return "30B";
  4980. case MODEL_32B: return "32B";
  4981. case MODEL_34B: return "34B";
  4982. case MODEL_35B: return "35B";
  4983. case MODEL_40B: return "40B";
  4984. case MODEL_65B: return "65B";
  4985. case MODEL_70B: return "70B";
  4986. case MODEL_236B: return "236B";
  4987. case MODEL_314B: return "314B";
  4988. case MODEL_SMALL: return "0.1B";
  4989. case MODEL_MEDIUM: return "0.4B";
  4990. case MODEL_LARGE: return "0.8B";
  4991. case MODEL_XL: return "1.5B";
  4992. case MODEL_A1_7B: return "A1.7B";
  4993. case MODEL_A2_7B: return "A2.7B";
  4994. case MODEL_8x7B: return "8x7B";
  4995. case MODEL_8x22B: return "8x22B";
  4996. case MODEL_16x12B: return "16x12B";
  4997. case MODEL_10B_128x3_66B: return "10B+128x3.66B";
  4998. case MODEL_57B_A14B: return "57B.A14B";
  4999. case MODEL_27B: return "27B";
  5000. default: return "?B";
  5001. }
  5002. }
  5003. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  5004. switch (type) {
  5005. case LLAMA_VOCAB_TYPE_NONE: return "no vocab";
  5006. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  5007. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  5008. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  5009. case LLAMA_VOCAB_TYPE_UGM: return "UGM";
  5010. case LLAMA_VOCAB_TYPE_RWKV: return "RWKV";
  5011. default: return "unknown";
  5012. }
  5013. }
  5014. static void llm_load_stats(llama_model_loader & ml, llama_model & model) {
  5015. model.n_elements = ml.n_elements;
  5016. model.n_bytes = ml.n_bytes;
  5017. }
  5018. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  5019. model.arch = ml.get_arch();
  5020. if (model.arch == LLM_ARCH_UNKNOWN) {
  5021. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  5022. }
  5023. }
  5024. static void llm_load_hparams(
  5025. llama_model_loader & ml,
  5026. llama_model & model) {
  5027. auto & hparams = model.hparams;
  5028. const gguf_context * ctx = ml.meta.get();
  5029. // get metadata as string
  5030. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  5031. enum gguf_type type = gguf_get_kv_type(ctx, i);
  5032. if (type == GGUF_TYPE_ARRAY) {
  5033. continue;
  5034. }
  5035. const char * name = gguf_get_key(ctx, i);
  5036. const std::string value = gguf_kv_to_str(ctx, i);
  5037. model.gguf_kv.emplace(name, value);
  5038. }
  5039. // get general kv
  5040. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  5041. // get hparams kv
  5042. ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab, false) || ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  5043. // everything past this point is not vocab-related
  5044. if (hparams.vocab_only) {
  5045. return;
  5046. }
  5047. ml.get_key(LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  5048. ml.get_key(LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  5049. ml.get_key(LLM_KV_BLOCK_COUNT, hparams.n_layer);
  5050. ml.get_key(LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  5051. ml.get_key(LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  5052. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  5053. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  5054. if (hparams.n_expert > 0) {
  5055. GGML_ASSERT(hparams.n_expert_used > 0);
  5056. } else {
  5057. GGML_ASSERT(hparams.n_expert_used == 0);
  5058. }
  5059. // zero-out the per-layer hparams
  5060. std::fill(hparams.n_head_arr.begin(), hparams.n_head_arr.end(), 0);
  5061. std::fill(hparams.n_head_kv_arr.begin(), hparams.n_head_kv_arr.end(), 0);
  5062. std::fill(hparams.n_ff_arr.begin(), hparams.n_ff_arr.end(), 0);
  5063. std::fill(hparams.cross_attn_layers.begin(), hparams.cross_attn_layers.end(), -1);
  5064. ml.get_key_or_arr(LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff_arr, hparams.n_layer);
  5065. ml.get_key_or_arr(LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head_arr, hparams.n_layer);
  5066. ml.get_arr(LLM_KV_ATTENTION_CROSS_ATTENTION_LAYERS, hparams.cross_attn_layers, false);
  5067. // n_head_kv is optional, default to n_head
  5068. hparams.n_head_kv_arr = hparams.n_head_arr;
  5069. ml.get_key_or_arr(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv_arr, hparams.n_layer, false);
  5070. bool rope_finetuned = false;
  5071. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  5072. hparams.rope_finetuned = rope_finetuned;
  5073. hparams.n_ctx_orig_yarn = hparams.n_ctx_train;
  5074. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_ctx_orig_yarn, false);
  5075. // rope_freq_base (optional)
  5076. hparams.rope_freq_base_train = 10000.0f;
  5077. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  5078. std::string rope_scaling("linear");
  5079. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  5080. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  5081. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  5082. // rope_freq_scale (inverse of the kv) is optional
  5083. float ropescale = 0.0f;
  5084. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  5085. // try the old key name
  5086. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  5087. }
  5088. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  5089. ml.get_key(LLM_KV_ROPE_SCALING_ATTN_FACTOR, hparams.rope_attn_factor, false);
  5090. // non-transformer models do not have attention heads
  5091. if (hparams.n_head() > 0) {
  5092. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  5093. // gpt-j n_rot = rotary_dim
  5094. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head();
  5095. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  5096. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head();
  5097. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  5098. // sanity check for n_rot (optional)
  5099. hparams.n_rot = hparams.n_embd_head_k;
  5100. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  5101. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_MLLAMA || model.arch == LLM_ARCH_FALCON) {
  5102. if (hparams.n_rot != hparams.n_embd_head_k) {
  5103. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd_head_k));
  5104. }
  5105. }
  5106. } else {
  5107. hparams.n_rot = 0;
  5108. hparams.n_embd_head_k = 0;
  5109. hparams.n_embd_head_v = 0;
  5110. }
  5111. // arch-specific KVs
  5112. switch (model.arch) {
  5113. case LLM_ARCH_LLAMA:
  5114. {
  5115. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5116. if (hparams.n_expert == 8) {
  5117. switch (hparams.n_layer) {
  5118. case 32: model.type = e_model::MODEL_8x7B; break;
  5119. case 56: model.type = e_model::MODEL_8x22B; break;
  5120. default: model.type = e_model::MODEL_UNKNOWN;
  5121. }
  5122. } else {
  5123. switch (hparams.n_layer) {
  5124. case 16: model.type = e_model::MODEL_1B; break; // Llama 3.2 1B
  5125. case 22: model.type = e_model::MODEL_1B; break;
  5126. case 26: model.type = e_model::MODEL_3B; break;
  5127. case 28: model.type = e_model::MODEL_3B; break; // Llama 3.2 3B
  5128. // granite uses a vocab with len 49152
  5129. 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;
  5130. case 36: model.type = e_model::MODEL_8B; break; // granite
  5131. case 40: model.type = e_model::MODEL_13B; break;
  5132. case 48: model.type = e_model::MODEL_34B; break;
  5133. case 60: model.type = e_model::MODEL_30B; break;
  5134. case 80: model.type = hparams.n_head() == hparams.n_head_kv() ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  5135. default: model.type = e_model::MODEL_UNKNOWN;
  5136. }
  5137. }
  5138. } break;
  5139. case LLM_ARCH_MLLAMA:
  5140. {
  5141. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5142. switch (hparams.n_layer) {
  5143. case 40: model.type = e_model::MODEL_11B; break;
  5144. case 100: model.type = e_model::MODEL_90B; break;
  5145. default: model.type = e_model::MODEL_UNKNOWN;
  5146. }
  5147. } break;
  5148. case LLM_ARCH_MINICPM:
  5149. {
  5150. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5151. ml.get_key(LLM_KV_EMBEDDING_SCALE, hparams.f_embedding_scale);
  5152. ml.get_key(LLM_KV_RESIDUAL_SCALE, hparams.f_residual_scale);
  5153. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  5154. switch (hparams.n_layer) {
  5155. case 52: model.type = e_model::MODEL_1B; break;
  5156. case 40: model.type = e_model::MODEL_2B; break;
  5157. default: model.type = e_model::MODEL_UNKNOWN;
  5158. }
  5159. } break;
  5160. case LLM_ARCH_MINICPM3:
  5161. {
  5162. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5163. ml.get_key(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q);
  5164. ml.get_key(LLM_KV_ATTENTION_KV_LORA_RANK, hparams.n_lora_kv);
  5165. switch (hparams.n_layer) {
  5166. case 62: model.type = e_model::MODEL_4B; break;
  5167. default: model.type = e_model::MODEL_UNKNOWN;
  5168. }
  5169. } break;
  5170. case LLM_ARCH_GROK:
  5171. {
  5172. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5173. switch (hparams.n_layer) {
  5174. case 64: model.type = e_model::MODEL_314B; break;
  5175. default: model.type = e_model::MODEL_UNKNOWN;
  5176. }
  5177. } break;
  5178. case LLM_ARCH_FALCON:
  5179. {
  5180. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5181. switch (hparams.n_layer) {
  5182. case 32: model.type = e_model::MODEL_7B; break;
  5183. case 60: model.type = e_model::MODEL_40B; break;
  5184. default: model.type = e_model::MODEL_UNKNOWN;
  5185. }
  5186. } break;
  5187. case LLM_ARCH_BAICHUAN:
  5188. {
  5189. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5190. switch (hparams.n_layer) {
  5191. case 32: model.type = e_model::MODEL_7B; break;
  5192. case 40: model.type = e_model::MODEL_13B; break;
  5193. default: model.type = e_model::MODEL_UNKNOWN;
  5194. }
  5195. if (model.type == e_model::MODEL_13B) {
  5196. // TODO: become GGUF KV parameter
  5197. hparams.f_max_alibi_bias = 8.0f;
  5198. }
  5199. } break;
  5200. case LLM_ARCH_STARCODER:
  5201. {
  5202. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5203. switch (hparams.n_layer) {
  5204. case 24: model.type = e_model::MODEL_1B; break;
  5205. case 36: model.type = e_model::MODEL_3B; break;
  5206. case 42: model.type = e_model::MODEL_7B; break;
  5207. case 40: model.type = e_model::MODEL_15B; break;
  5208. default: model.type = e_model::MODEL_UNKNOWN;
  5209. }
  5210. } break;
  5211. case LLM_ARCH_REFACT:
  5212. {
  5213. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5214. switch (hparams.n_layer) {
  5215. case 32: model.type = e_model::MODEL_1B; break;
  5216. default: model.type = e_model::MODEL_UNKNOWN;
  5217. }
  5218. // TODO: become GGUF KV parameter
  5219. hparams.f_max_alibi_bias = 8.0f;
  5220. } break;
  5221. case LLM_ARCH_BERT:
  5222. {
  5223. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5224. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  5225. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  5226. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  5227. switch (hparams.n_layer) {
  5228. case 3:
  5229. model.type = e_model::MODEL_17M; break; // bge-micro
  5230. case 6:
  5231. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  5232. case 12:
  5233. switch (hparams.n_embd) {
  5234. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  5235. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  5236. } break;
  5237. case 24:
  5238. model.type = e_model::MODEL_335M; break; // bge-large
  5239. }
  5240. } break;
  5241. case LLM_ARCH_JINA_BERT_V2:
  5242. {
  5243. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5244. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  5245. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  5246. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  5247. hparams.f_max_alibi_bias = 8.0f;
  5248. switch (hparams.n_layer) {
  5249. case 4: model.type = e_model::MODEL_33M; break; // jina-embeddings-small
  5250. case 12: model.type = e_model::MODEL_137M; break; // jina-embeddings-base
  5251. }
  5252. } break;
  5253. case LLM_ARCH_NOMIC_BERT:
  5254. {
  5255. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5256. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  5257. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  5258. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  5259. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  5260. model.type = e_model::MODEL_137M;
  5261. }
  5262. } break;
  5263. case LLM_ARCH_BLOOM:
  5264. {
  5265. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5266. switch (hparams.n_layer) {
  5267. case 24: model.type = e_model::MODEL_1B; break;
  5268. case 30:
  5269. switch (hparams.n_embd) {
  5270. case 2560: model.type = e_model::MODEL_3B; break;
  5271. case 4096: model.type = e_model::MODEL_7B; break;
  5272. } break;
  5273. }
  5274. // TODO: become GGUF KV parameter
  5275. hparams.f_max_alibi_bias = 8.0f;
  5276. } break;
  5277. case LLM_ARCH_MPT:
  5278. {
  5279. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5280. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  5281. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  5282. switch (hparams.n_layer) {
  5283. case 32: model.type = e_model::MODEL_7B; break;
  5284. case 48: model.type = e_model::MODEL_30B; break;
  5285. default: model.type = e_model::MODEL_UNKNOWN;
  5286. }
  5287. } break;
  5288. case LLM_ARCH_STABLELM:
  5289. {
  5290. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5291. switch (hparams.n_layer) {
  5292. case 24: model.type = e_model::MODEL_1B; break;
  5293. case 32: model.type = e_model::MODEL_3B; break;
  5294. case 40: model.type = e_model::MODEL_12B; break;
  5295. default: model.type = e_model::MODEL_UNKNOWN;
  5296. }
  5297. } break;
  5298. case LLM_ARCH_QWEN:
  5299. {
  5300. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5301. switch (hparams.n_layer) {
  5302. case 32: model.type = e_model::MODEL_7B; break;
  5303. case 40: model.type = e_model::MODEL_13B; break;
  5304. default: model.type = e_model::MODEL_UNKNOWN;
  5305. }
  5306. } break;
  5307. case LLM_ARCH_QWEN2VL:
  5308. {
  5309. std::array<int, 4> section_dims;
  5310. ml.get_key_or_arr(LLM_KV_ROPE_DIMENSION_SECTIONS, section_dims, 4, true);
  5311. std::copy(section_dims.begin(), section_dims.begin() + 4, std::begin(hparams.rope_sections));
  5312. }
  5313. // fall through
  5314. case LLM_ARCH_QWEN2:
  5315. {
  5316. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5317. switch (hparams.n_layer) {
  5318. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  5319. case 28: model.type = hparams.n_embd == 1536 ? e_model::MODEL_1_5B : e_model::MODEL_7B; break;
  5320. case 32: model.type = e_model::MODEL_7B; break;
  5321. case 36: model.type = e_model::MODEL_3B; break;
  5322. case 40: model.type = hparams.n_head() == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  5323. case 48: model.type = e_model::MODEL_14B; break;
  5324. case 64: model.type = e_model::MODEL_32B; break;
  5325. case 80: model.type = e_model::MODEL_70B; break;
  5326. default: model.type = e_model::MODEL_UNKNOWN;
  5327. }
  5328. } break;
  5329. case LLM_ARCH_QWEN2MOE:
  5330. {
  5331. ml.get_key(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp, false);
  5332. ml.get_key(LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, hparams.n_ff_shexp, false);
  5333. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5334. switch (hparams.n_layer) {
  5335. case 24: model.type = e_model::MODEL_A2_7B; break;
  5336. case 28: model.type = e_model::MODEL_57B_A14B; break;
  5337. default: model.type = e_model::MODEL_UNKNOWN;
  5338. }
  5339. } break;
  5340. case LLM_ARCH_PHI2:
  5341. {
  5342. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5343. switch (hparams.n_layer) {
  5344. case 24: model.type = e_model::MODEL_1B; break;
  5345. case 32: model.type = e_model::MODEL_3B; break;
  5346. default: model.type = e_model::MODEL_UNKNOWN;
  5347. }
  5348. } break;
  5349. case LLM_ARCH_PHI3:
  5350. {
  5351. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5352. switch (hparams.n_layer) {
  5353. case 24: model.type = e_model::MODEL_1B; break;
  5354. case 32: model.type = e_model::MODEL_3B; break;
  5355. case 40: model.type = e_model::MODEL_14B; break;
  5356. default: model.type = e_model::MODEL_UNKNOWN;
  5357. }
  5358. // for backward compatibility ; see: https://github.com/ggerganov/llama.cpp/pull/8931
  5359. if ((hparams.n_layer == 32 || hparams.n_layer == 40) && hparams.n_ctx_train == 4096) {
  5360. // default value for Phi-3-mini-4k-instruct and Phi-3-medium-4k-instruct
  5361. hparams.n_swa = 2047;
  5362. } else if (hparams.n_layer == 32 && hparams.n_head_kv(0) == 32 && hparams.n_ctx_train == 131072) {
  5363. // default value for Phi-3-mini-128k-instruct
  5364. hparams.n_swa = 262144;
  5365. } else if (hparams.n_layer == 40 && hparams.n_ctx_train == 131072) {
  5366. // default value for Phi-3-medium-128k-instruct
  5367. hparams.n_swa = 131072;
  5368. }
  5369. bool found_swa = ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa, false);
  5370. if (!found_swa && hparams.n_swa == 0) {
  5371. throw std::runtime_error("invalid value for sliding_window");
  5372. }
  5373. } break;
  5374. case LLM_ARCH_PLAMO:
  5375. {
  5376. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5377. switch (hparams.n_layer) {
  5378. case 40: model.type = e_model::MODEL_13B; break;
  5379. default: model.type = e_model::MODEL_UNKNOWN;
  5380. }
  5381. } break;
  5382. case LLM_ARCH_GPT2:
  5383. {
  5384. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5385. switch (hparams.n_layer) {
  5386. case 12: model.type = e_model::MODEL_SMALL; break;
  5387. case 24: model.type = e_model::MODEL_MEDIUM; break;
  5388. case 36: model.type = e_model::MODEL_LARGE; break;
  5389. case 48: model.type = e_model::MODEL_XL; break;
  5390. default: model.type = e_model::MODEL_UNKNOWN;
  5391. }
  5392. } break;
  5393. case LLM_ARCH_CODESHELL:
  5394. {
  5395. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5396. switch (hparams.n_layer) {
  5397. case 42: model.type = e_model::MODEL_7B; break;
  5398. default: model.type = e_model::MODEL_UNKNOWN;
  5399. }
  5400. } break;
  5401. case LLM_ARCH_ORION:
  5402. {
  5403. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5404. switch (hparams.n_layer) {
  5405. case 40: model.type = e_model::MODEL_14B; break;
  5406. default: model.type = e_model::MODEL_UNKNOWN;
  5407. }
  5408. } break;
  5409. case LLM_ARCH_INTERNLM2:
  5410. {
  5411. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5412. switch (hparams.n_layer) {
  5413. case 32: model.type = e_model::MODEL_7B; break;
  5414. case 48: model.type = e_model::MODEL_20B; break;
  5415. default: model.type = e_model::MODEL_UNKNOWN;
  5416. }
  5417. } break;
  5418. case LLM_ARCH_GEMMA:
  5419. {
  5420. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5421. switch (hparams.n_layer) {
  5422. case 18: model.type = e_model::MODEL_2B; break;
  5423. case 28: model.type = e_model::MODEL_7B; break;
  5424. default: model.type = e_model::MODEL_UNKNOWN;
  5425. }
  5426. } break;
  5427. case LLM_ARCH_GEMMA2:
  5428. {
  5429. hparams.n_swa = 4096; // default value of gemma 2
  5430. ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa, false);
  5431. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5432. ml.get_key(LLM_KV_ATTN_LOGIT_SOFTCAPPING, hparams.f_attn_logit_softcapping, false);
  5433. ml.get_key(LLM_KV_FINAL_LOGIT_SOFTCAPPING, hparams.f_final_logit_softcapping, false);
  5434. hparams.attn_soft_cap = true;
  5435. switch (hparams.n_layer) {
  5436. case 26: model.type = e_model::MODEL_2B; break;
  5437. case 42: model.type = e_model::MODEL_9B; break;
  5438. case 46: model.type = e_model::MODEL_27B; break;
  5439. default: model.type = e_model::MODEL_UNKNOWN;
  5440. }
  5441. } break;
  5442. case LLM_ARCH_STARCODER2:
  5443. {
  5444. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5445. switch (hparams.n_layer) {
  5446. case 30: model.type = e_model::MODEL_3B; break;
  5447. case 32: model.type = e_model::MODEL_7B; break;
  5448. case 40: model.type = e_model::MODEL_15B; break;
  5449. case 52: model.type = e_model::MODEL_20B; break; // granite
  5450. case 88: model.type = e_model::MODEL_34B; break; // granite
  5451. default: model.type = e_model::MODEL_UNKNOWN;
  5452. }
  5453. } break;
  5454. case LLM_ARCH_MAMBA:
  5455. {
  5456. ml.get_key(LLM_KV_SSM_CONV_KERNEL, hparams.ssm_d_conv);
  5457. ml.get_key(LLM_KV_SSM_INNER_SIZE, hparams.ssm_d_inner);
  5458. ml.get_key(LLM_KV_SSM_STATE_SIZE, hparams.ssm_d_state);
  5459. ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
  5460. ml.get_key(LLM_KV_SSM_DT_B_C_RMS, hparams.ssm_dt_b_c_rms, false);
  5461. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5462. switch (hparams.n_layer) {
  5463. case 24:
  5464. switch (hparams.n_embd) {
  5465. case 768: model.type = e_model::MODEL_SMALL; break;
  5466. default: model.type = e_model::MODEL_UNKNOWN;
  5467. } break;
  5468. case 48:
  5469. switch (hparams.n_embd) {
  5470. case 1024: model.type = e_model::MODEL_MEDIUM; break;
  5471. case 1536: model.type = e_model::MODEL_LARGE; break;
  5472. case 2048: model.type = e_model::MODEL_XL; break;
  5473. default: model.type = e_model::MODEL_UNKNOWN;
  5474. } break;
  5475. case 64:
  5476. switch (hparams.n_embd) {
  5477. case 2560: model.type = e_model::MODEL_3B; break;
  5478. default: model.type = e_model::MODEL_UNKNOWN;
  5479. } break;
  5480. default: model.type = e_model::MODEL_UNKNOWN;
  5481. }
  5482. } break;
  5483. case LLM_ARCH_XVERSE:
  5484. {
  5485. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5486. switch (hparams.n_layer) {
  5487. case 32: model.type = e_model::MODEL_7B; break;
  5488. case 40: model.type = e_model::MODEL_13B; break;
  5489. case 80: model.type = e_model::MODEL_65B; break;
  5490. default: model.type = e_model::MODEL_UNKNOWN;
  5491. }
  5492. } break;
  5493. case LLM_ARCH_COMMAND_R:
  5494. {
  5495. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  5496. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5497. switch (hparams.n_layer) {
  5498. case 40: model.type = e_model::MODEL_35B; break;
  5499. default: model.type = e_model::MODEL_UNKNOWN;
  5500. }
  5501. } break;
  5502. case LLM_ARCH_DBRX:
  5503. {
  5504. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5505. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv);
  5506. switch (hparams.n_layer) {
  5507. case 40: model.type = e_model::MODEL_16x12B; break;
  5508. default: model.type = e_model::MODEL_UNKNOWN;
  5509. }
  5510. } break;
  5511. case LLM_ARCH_OLMO:
  5512. {
  5513. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5514. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  5515. switch (hparams.n_layer) {
  5516. case 22: model.type = e_model::MODEL_1B; break;
  5517. case 32: model.type = e_model::MODEL_7B; break;
  5518. case 80: model.type = e_model::MODEL_70B; break;
  5519. default: model.type = e_model::MODEL_UNKNOWN;
  5520. }
  5521. } break;
  5522. case LLM_ARCH_OLMO2:
  5523. {
  5524. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5525. switch (hparams.n_layer) {
  5526. case 16: model.type = e_model::MODEL_1B; break;
  5527. case 32: model.type = e_model::MODEL_7B; break;
  5528. case 40: model.type = e_model::MODEL_13B; break;
  5529. default: model.type = e_model::MODEL_UNKNOWN;
  5530. }
  5531. } break;
  5532. case LLM_ARCH_OLMOE:
  5533. {
  5534. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5535. switch (hparams.n_layer) {
  5536. case 16: model.type = e_model::MODEL_A1_7B; break;
  5537. default: model.type = e_model::MODEL_UNKNOWN;
  5538. }
  5539. } break;
  5540. case LLM_ARCH_OPENELM:
  5541. {
  5542. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5543. switch (hparams.n_layer) {
  5544. case 16: model.type = e_model::MODEL_270M; break;
  5545. case 20: model.type = e_model::MODEL_450M; break;
  5546. case 28: model.type = e_model::MODEL_1B; break;
  5547. case 36: model.type = e_model::MODEL_3B; break;
  5548. default: model.type = e_model::MODEL_UNKNOWN;
  5549. }
  5550. } break;
  5551. case LLM_ARCH_GPTNEOX:
  5552. {
  5553. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5554. ml.get_key(LLM_KV_USE_PARALLEL_RESIDUAL, hparams.use_par_res);
  5555. switch (hparams.n_layer) {
  5556. case 6:
  5557. switch (hparams.n_ff()) {
  5558. case 512: model.type = e_model::MODEL_14M; break;
  5559. case 2048: model.type = e_model::MODEL_70M; break;
  5560. default: model.type = e_model::MODEL_UNKNOWN;
  5561. } break;
  5562. case 12:
  5563. switch (hparams.n_ff()) {
  5564. case 3072: model.type = e_model::MODEL_160M; break;
  5565. default: model.type = e_model::MODEL_UNKNOWN;
  5566. } break;
  5567. case 16:
  5568. switch (hparams.n_ff()) {
  5569. case 8192: model.type = e_model::MODEL_1B; break;
  5570. default: model.type = e_model::MODEL_UNKNOWN;
  5571. } break;
  5572. case 24:
  5573. switch (hparams.n_ff()) {
  5574. case 4096: model.type = e_model::MODEL_410M; break;
  5575. case 8192: model.type = e_model::MODEL_1_4B; break;
  5576. default: model.type = e_model::MODEL_UNKNOWN;
  5577. } break;
  5578. case 32:
  5579. switch (hparams.n_ff()) {
  5580. case 10240: model.type = e_model::MODEL_2_8B; break;
  5581. case 16384: model.type = e_model::MODEL_6_9B; break;
  5582. default: model.type = e_model::MODEL_UNKNOWN;
  5583. } break;
  5584. case 36:
  5585. switch (hparams.n_ff()) {
  5586. case 20480: model.type = e_model::MODEL_12B; break;
  5587. default: model.type = e_model::MODEL_UNKNOWN;
  5588. } break;
  5589. case 44:
  5590. switch (hparams.n_ff()) {
  5591. case 24576: model.type = e_model::MODEL_20B; break;
  5592. default: model.type = e_model::MODEL_UNKNOWN;
  5593. } break;
  5594. default: model.type = e_model::MODEL_UNKNOWN;
  5595. }
  5596. } break;
  5597. case LLM_ARCH_ARCTIC:
  5598. {
  5599. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5600. if (hparams.n_expert == 128) {
  5601. switch (hparams.n_layer) {
  5602. case 35: model.type = e_model::MODEL_10B_128x3_66B; break;
  5603. default: model.type = e_model::MODEL_UNKNOWN;
  5604. }
  5605. } else {
  5606. model.type = e_model::MODEL_UNKNOWN;
  5607. }
  5608. } break;
  5609. case LLM_ARCH_DEEPSEEK2:
  5610. {
  5611. bool is_lite = (hparams.n_layer == 27);
  5612. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5613. ml.get_key(LLM_KV_LEADING_DENSE_BLOCK_COUNT, hparams.n_layer_dense_lead);
  5614. if (!is_lite) {
  5615. ml.get_key(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q);
  5616. }
  5617. ml.get_key(LLM_KV_ATTENTION_KV_LORA_RANK, hparams.n_lora_kv);
  5618. ml.get_key(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp);
  5619. ml.get_key(LLM_KV_EXPERT_SHARED_COUNT, hparams.n_expert_shared);
  5620. ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale);
  5621. ml.get_key(LLM_KV_ROPE_SCALING_YARN_LOG_MUL, hparams.rope_yarn_log_mul);
  5622. switch (hparams.n_layer) {
  5623. case 27: model.type = e_model::MODEL_16B; break;
  5624. case 60: model.type = e_model::MODEL_236B; break;
  5625. default: model.type = e_model::MODEL_UNKNOWN;
  5626. }
  5627. } break;
  5628. case LLM_ARCH_CHATGLM:
  5629. {
  5630. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5631. switch (hparams.n_layer) {
  5632. case 28: model.type = e_model::MODEL_6B; break;
  5633. case 40: model.type = e_model::MODEL_9B; break;
  5634. default: model.type = e_model::MODEL_UNKNOWN;
  5635. }
  5636. } break;
  5637. case LLM_ARCH_BITNET:
  5638. {
  5639. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5640. switch (hparams.n_layer) {
  5641. case 26: model.type = e_model::MODEL_3B; break;
  5642. default: model.type = e_model::MODEL_UNKNOWN;
  5643. }
  5644. } break;
  5645. case LLM_ARCH_T5:
  5646. {
  5647. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5648. ml.get_key(LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, hparams.n_rel_attn_bkts);
  5649. uint32_t dec_start_token_id;
  5650. if (ml.get_key(LLM_KV_DECODER_START_TOKEN_ID, dec_start_token_id, false)) {
  5651. hparams.dec_start_token_id = dec_start_token_id;
  5652. }
  5653. switch (hparams.n_layer) {
  5654. case 6: model.type = e_model::MODEL_60M; break; // t5-small
  5655. case 8: model.type = e_model::MODEL_80M; break; // flan-t5-small
  5656. case 12:
  5657. switch (hparams.n_ff()) {
  5658. case 3072: model.type = e_model::MODEL_220M; break; // t5-base
  5659. case 2048: model.type = e_model::MODEL_250M; break; // flan-t5-base
  5660. default: model.type = e_model::MODEL_UNKNOWN;
  5661. } break;
  5662. case 24:
  5663. switch (hparams.n_ff()) {
  5664. case 4096: model.type = e_model::MODEL_770M; break; // t5-large
  5665. case 2816: model.type = e_model::MODEL_780M; break; // flan-t5-large
  5666. case 16384: model.type = e_model::MODEL_3B; break; // t5-3b
  5667. case 5120: model.type = e_model::MODEL_3B; break; // flan-t5-xl
  5668. case 65536: model.type = e_model::MODEL_11B; break; // t5-11b
  5669. case 10240: model.type = e_model::MODEL_11B; break; // flan-t5-xxl
  5670. default: model.type = e_model::MODEL_UNKNOWN;
  5671. } break;
  5672. default: model.type = e_model::MODEL_UNKNOWN;
  5673. }
  5674. } break;
  5675. case LLM_ARCH_T5ENCODER:
  5676. {
  5677. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5678. ml.get_key(LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, hparams.n_rel_attn_bkts);
  5679. model.type = e_model::MODEL_UNKNOWN;
  5680. } break;
  5681. case LLM_ARCH_JAIS:
  5682. {
  5683. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5684. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  5685. switch (hparams.n_layer) {
  5686. case 24: model.type = e_model::MODEL_1_3B; break;
  5687. case 40: model.type = e_model::MODEL_13B; break;
  5688. /* TODO: add variants */
  5689. default: model.type = e_model::MODEL_UNKNOWN;
  5690. }
  5691. } break;
  5692. case LLM_ARCH_NEMOTRON:
  5693. {
  5694. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5695. switch (hparams.n_layer) {
  5696. case 32: model.type = e_model::MODEL_4B; break;
  5697. default: model.type = e_model::MODEL_UNKNOWN;
  5698. }
  5699. } break;
  5700. case LLM_ARCH_EXAONE:
  5701. {
  5702. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5703. switch (hparams.n_layer) {
  5704. case 32: model.type = e_model::MODEL_8B; break;
  5705. default: model.type = e_model::MODEL_UNKNOWN;
  5706. }
  5707. } break;
  5708. case LLM_ARCH_RWKV6:
  5709. {
  5710. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5711. ml.get_key(LLM_KV_WKV_HEAD_SIZE, hparams.wkv_head_size);
  5712. ml.get_key(LLM_KV_TIME_MIX_EXTRA_DIM, hparams.time_mix_extra_dim);
  5713. ml.get_key(LLM_KV_TIME_DECAY_EXTRA_DIM, hparams.time_decay_extra_dim);
  5714. ml.get_key(LLM_KV_RESCALE_EVERY_N_LAYERS, hparams.rescale_every_n_layers, false);
  5715. switch (hparams.n_layer) {
  5716. case 24: model.type = e_model::MODEL_1_6B; break;
  5717. case 32:
  5718. switch (hparams.n_embd) {
  5719. case 2560: model.type = e_model::MODEL_3B; break;
  5720. case 4096: model.type = e_model::MODEL_7B; break;
  5721. default: model.type = e_model::MODEL_UNKNOWN;
  5722. } break;
  5723. case 61: model.type = e_model::MODEL_14B; break;
  5724. default: model.type = e_model::MODEL_UNKNOWN;
  5725. }
  5726. } break;
  5727. case LLM_ARCH_GRANITE:
  5728. case LLM_ARCH_GRANITE_MOE:
  5729. {
  5730. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5731. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  5732. ml.get_key(LLM_KV_RESIDUAL_SCALE, hparams.f_residual_scale);
  5733. ml.get_key(LLM_KV_EMBEDDING_SCALE, hparams.f_embedding_scale);
  5734. ml.get_key(LLM_KV_ATTENTION_SCALE, hparams.f_attention_scale);
  5735. switch (hparams.n_layer) {
  5736. case 32: model.type = e_model::MODEL_3B; break;
  5737. case 40: model.type = e_model::MODEL_3B; break;
  5738. // Add additional layer/vocab/etc checks here for other model sizes
  5739. default: model.type = e_model::MODEL_UNKNOWN;
  5740. }
  5741. } break;
  5742. case LLM_ARCH_CHAMELEON:
  5743. {
  5744. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5745. hparams.f_norm_eps = 1e-5; // eps for qk-norm, torch default
  5746. ml.get_key(LLM_KV_SWIN_NORM, hparams.swin_norm);
  5747. switch (hparams.n_layer) {
  5748. case 32: model.type = e_model::MODEL_7B; break;
  5749. case 48: model.type = e_model::MODEL_34B; break;
  5750. default: model.type = e_model::MODEL_UNKNOWN;
  5751. }
  5752. } break;
  5753. case LLM_ARCH_SOLAR:
  5754. {
  5755. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5756. for (int i = 0; i < hparams.n_bskcn_arr.max_size(); ++i) {
  5757. auto & bskcn = hparams.n_bskcn_arr.at(i);
  5758. bskcn.fill(0);
  5759. 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);
  5760. }
  5761. switch (hparams.n_layer) {
  5762. case 64: model.type = e_model::MODEL_22B; break;
  5763. default: model.type = e_model::MODEL_UNKNOWN;
  5764. }
  5765. }
  5766. default: (void)0;
  5767. }
  5768. model.ftype = ml.ftype;
  5769. if (hparams.f_max_alibi_bias > 0.0f) {
  5770. hparams.use_alibi = true;
  5771. }
  5772. hparams.rope_type = llama_rope_type(&model);
  5773. }
  5774. static void llm_load_vocab(
  5775. llama_model_loader & ml,
  5776. llama_model & model) {
  5777. auto & vocab = model.vocab;
  5778. struct gguf_context * ctx = ml.meta.get();
  5779. const auto kv = LLM_KV(model.arch);
  5780. // determine vocab type
  5781. {
  5782. std::string tokenizer_model;
  5783. std::string tokenizer_pre;
  5784. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_model);
  5785. ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false);
  5786. if (tokenizer_model == "no_vocab") {
  5787. vocab.type = LLAMA_VOCAB_TYPE_NONE;
  5788. // default special tokens
  5789. vocab.special_bos_id = LLAMA_TOKEN_NULL;
  5790. vocab.special_eos_id = LLAMA_TOKEN_NULL;
  5791. vocab.special_unk_id = LLAMA_TOKEN_NULL;
  5792. vocab.special_sep_id = LLAMA_TOKEN_NULL;
  5793. vocab.special_pad_id = LLAMA_TOKEN_NULL;
  5794. vocab.special_cls_id = LLAMA_TOKEN_NULL;
  5795. vocab.special_mask_id = LLAMA_TOKEN_NULL;
  5796. vocab.linefeed_id = LLAMA_TOKEN_NULL;
  5797. // read vocab size from metadata
  5798. if (!ml.get_key(LLM_KV_VOCAB_SIZE, vocab.n_vocab, false)) {
  5799. vocab.n_vocab = 0;
  5800. LLAMA_LOG_WARN("%s: there is no vocab_size in metadata, vocab.n_vocab will be set to %u\n", __func__, vocab.n_vocab);
  5801. }
  5802. return;
  5803. }
  5804. if (tokenizer_model == "llama") {
  5805. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  5806. // default special tokens
  5807. vocab.special_bos_id = 1;
  5808. vocab.special_eos_id = 2;
  5809. vocab.special_unk_id = 0;
  5810. vocab.special_sep_id = LLAMA_TOKEN_NULL;
  5811. vocab.special_pad_id = LLAMA_TOKEN_NULL;
  5812. vocab.special_cls_id = LLAMA_TOKEN_NULL;
  5813. vocab.special_mask_id = LLAMA_TOKEN_NULL;
  5814. } else if (tokenizer_model == "bert") {
  5815. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  5816. // default special tokens
  5817. vocab.special_bos_id = LLAMA_TOKEN_NULL;
  5818. vocab.special_eos_id = LLAMA_TOKEN_NULL;
  5819. vocab.special_unk_id = 100;
  5820. vocab.special_sep_id = 102;
  5821. vocab.special_pad_id = 0;
  5822. vocab.special_cls_id = 101;
  5823. vocab.special_mask_id = 103;
  5824. } else if (tokenizer_model == "gpt2") {
  5825. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  5826. // read bpe merges and populate bpe ranks
  5827. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  5828. if (merges_keyidx == -1) {
  5829. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  5830. }
  5831. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  5832. for (int i = 0; i < n_merges; i++) {
  5833. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  5834. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  5835. std::string first;
  5836. std::string second;
  5837. const size_t pos = word.find(' ', 1);
  5838. if (pos != std::string::npos) {
  5839. first = word.substr(0, pos);
  5840. second = word.substr(pos + 1);
  5841. }
  5842. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  5843. }
  5844. // default special tokens
  5845. vocab.special_bos_id = 11;
  5846. vocab.special_eos_id = 11;
  5847. vocab.special_unk_id = LLAMA_TOKEN_NULL;
  5848. vocab.special_sep_id = LLAMA_TOKEN_NULL;
  5849. vocab.special_pad_id = LLAMA_TOKEN_NULL;
  5850. vocab.special_cls_id = LLAMA_TOKEN_NULL;
  5851. vocab.special_mask_id = LLAMA_TOKEN_NULL;
  5852. } else if (tokenizer_model == "t5") {
  5853. vocab.type = LLAMA_VOCAB_TYPE_UGM;
  5854. // default special tokens
  5855. vocab.special_bos_id = LLAMA_TOKEN_NULL;
  5856. vocab.special_eos_id = 1;
  5857. vocab.special_unk_id = 2;
  5858. vocab.special_sep_id = LLAMA_TOKEN_NULL;
  5859. vocab.special_pad_id = 0;
  5860. vocab.special_cls_id = LLAMA_TOKEN_NULL;
  5861. vocab.special_mask_id = LLAMA_TOKEN_NULL;
  5862. const int precompiled_charsmap_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP).c_str());
  5863. if (precompiled_charsmap_keyidx != -1) {
  5864. size_t n_precompiled_charsmap = gguf_get_arr_n(ctx, precompiled_charsmap_keyidx);
  5865. const char * precompiled_charsmap = (const char *) gguf_get_arr_data(ctx, precompiled_charsmap_keyidx);
  5866. vocab.precompiled_charsmap.assign(precompiled_charsmap, precompiled_charsmap + n_precompiled_charsmap);
  5867. #ifdef IS_BIG_ENDIAN
  5868. // correct endiannes of data in precompiled_charsmap binary blob
  5869. uint32_t * xcda_blob_size = (uint32_t *) &vocab.precompiled_charsmap[0];
  5870. *xcda_blob_size = __builtin_bswap32(*xcda_blob_size);
  5871. assert(*xcda_blob_size + sizeof(uint32_t) < n_precompiled_charsmap);
  5872. size_t xcda_array_size = *xcda_blob_size / sizeof(uint32_t);
  5873. uint32_t * xcda_array = (uint32_t *) &vocab.precompiled_charsmap[sizeof(uint32_t)];
  5874. for (size_t i = 0; i < xcda_array_size; ++i) {
  5875. xcda_array[i] = __builtin_bswap32(xcda_array[i]);
  5876. }
  5877. #endif
  5878. }
  5879. } else if (tokenizer_model == "rwkv") {
  5880. vocab.type = LLAMA_VOCAB_TYPE_RWKV;
  5881. // default special tokens
  5882. vocab.special_bos_id = LLAMA_TOKEN_NULL;
  5883. vocab.special_eos_id = LLAMA_TOKEN_NULL;
  5884. vocab.special_unk_id = LLAMA_TOKEN_NULL;
  5885. vocab.special_sep_id = LLAMA_TOKEN_NULL;
  5886. vocab.special_pad_id = LLAMA_TOKEN_NULL;
  5887. } else {
  5888. throw std::runtime_error(format("unknown tokenizer: '%s'", tokenizer_model.c_str()));
  5889. }
  5890. // for now, only BPE models have pre-tokenizers
  5891. if (vocab.type == LLAMA_VOCAB_TYPE_BPE) {
  5892. vocab.tokenizer_add_space_prefix = false;
  5893. vocab.tokenizer_clean_spaces = true;
  5894. if (tokenizer_pre == "default") {
  5895. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5896. } else if (
  5897. tokenizer_pre == "llama3" ||
  5898. tokenizer_pre == "llama-v3" ||
  5899. tokenizer_pre == "llama-bpe") {
  5900. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_LLAMA3;
  5901. vocab.tokenizer_ignore_merges = true;
  5902. vocab.tokenizer_add_bos = true;
  5903. } else if (
  5904. tokenizer_pre == "deepseek-llm") {
  5905. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM;
  5906. vocab.tokenizer_clean_spaces = false;
  5907. } else if (
  5908. tokenizer_pre == "deepseek-coder") {
  5909. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER;
  5910. vocab.tokenizer_clean_spaces = false;
  5911. } else if (
  5912. tokenizer_pre == "falcon") {
  5913. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_FALCON;
  5914. } else if (
  5915. tokenizer_pre == "mpt") {
  5916. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_MPT;
  5917. } else if (
  5918. tokenizer_pre == "starcoder") {
  5919. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_STARCODER;
  5920. } else if (
  5921. tokenizer_pre == "gpt-2" ||
  5922. tokenizer_pre == "phi-2" ||
  5923. tokenizer_pre == "jina-es" ||
  5924. tokenizer_pre == "jina-de" ||
  5925. tokenizer_pre == "jina-v1-en" ||
  5926. tokenizer_pre == "jina-v2-es" ||
  5927. tokenizer_pre == "jina-v2-de" ||
  5928. tokenizer_pre == "jina-v2-code") {
  5929. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_GPT2;
  5930. } else if (
  5931. tokenizer_pre == "refact") {
  5932. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_REFACT;
  5933. } else if (
  5934. tokenizer_pre == "command-r") {
  5935. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_COMMAND_R;
  5936. vocab.tokenizer_clean_spaces = false;
  5937. } else if (
  5938. tokenizer_pre == "qwen2") {
  5939. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_QWEN2;
  5940. vocab.tokenizer_clean_spaces = false;
  5941. } else if (
  5942. tokenizer_pre == "stablelm2") {
  5943. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_STABLELM2;
  5944. } else if (
  5945. tokenizer_pre == "olmo") {
  5946. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_OLMO;
  5947. } else if (
  5948. tokenizer_pre == "dbrx") {
  5949. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DBRX;
  5950. } else if (
  5951. tokenizer_pre == "smaug-bpe") {
  5952. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_SMAUG;
  5953. } else if (
  5954. tokenizer_pre == "poro-chat") {
  5955. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_PORO;
  5956. vocab.tokenizer_clean_spaces = false;
  5957. } else if (
  5958. tokenizer_pre == "chatglm-bpe") {
  5959. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_CHATGLM4;
  5960. vocab.special_bos_id = LLAMA_TOKEN_NULL;
  5961. } else if (
  5962. tokenizer_pre == "viking") {
  5963. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_VIKING;
  5964. vocab.tokenizer_clean_spaces = false;
  5965. } else if (
  5966. tokenizer_pre == "jais") {
  5967. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_JAIS;
  5968. } else if (
  5969. tokenizer_pre == "tekken") {
  5970. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_TEKKEN;
  5971. vocab.tokenizer_clean_spaces = false;
  5972. vocab.tokenizer_ignore_merges = true;
  5973. vocab.tokenizer_add_bos = true;
  5974. } else if (
  5975. tokenizer_pre == "smollm") {
  5976. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_SMOLLM;
  5977. vocab.tokenizer_clean_spaces = false;
  5978. } else if (
  5979. tokenizer_pre == "codeshell") {
  5980. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_CODESHELL;
  5981. } else if (
  5982. tokenizer_pre == "bloom") {
  5983. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_BLOOM;
  5984. } else if (
  5985. tokenizer_pre == "gpt3-finnish") {
  5986. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_GPT3_FINNISH;
  5987. } else if (
  5988. tokenizer_pre == "exaone") {
  5989. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_EXAONE;
  5990. } else if (
  5991. tokenizer_pre == "chameleon") {
  5992. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_CHAMELEON;
  5993. vocab.tokenizer_add_bos = true;
  5994. vocab.tokenizer_clean_spaces = false;
  5995. } else if (
  5996. tokenizer_pre == "minerva-7b") {
  5997. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_MINERVA;
  5998. } else {
  5999. LLAMA_LOG_WARN("%s: missing or unrecognized pre-tokenizer type, using: 'default'\n", __func__);
  6000. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  6001. }
  6002. } else if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  6003. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  6004. vocab.tokenizer_add_space_prefix = true;
  6005. vocab.tokenizer_clean_spaces = false;
  6006. vocab.tokenizer_add_bos = true;
  6007. vocab.tokenizer_add_eos = false;
  6008. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  6009. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  6010. vocab.tokenizer_add_space_prefix = false;
  6011. vocab.tokenizer_clean_spaces = true;
  6012. vocab.tokenizer_add_bos = true;
  6013. vocab.tokenizer_add_eos = false;
  6014. } else if (vocab.type == LLAMA_VOCAB_TYPE_UGM) {
  6015. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  6016. vocab.tokenizer_add_bos = false;
  6017. vocab.tokenizer_add_eos = true;
  6018. } else if (vocab.type == LLAMA_VOCAB_TYPE_RWKV) {
  6019. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  6020. vocab.tokenizer_add_space_prefix = false;
  6021. vocab.tokenizer_clean_spaces = false;
  6022. vocab.tokenizer_add_bos = false;
  6023. vocab.tokenizer_add_eos = false;
  6024. } else {
  6025. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  6026. }
  6027. ml.get_key(LLM_KV_TOKENIZER_ADD_PREFIX, vocab.tokenizer_add_space_prefix, false);
  6028. ml.get_key(LLM_KV_TOKENIZER_REMOVE_EXTRA_WS, vocab.tokenizer_remove_extra_whitespaces, false);
  6029. }
  6030. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  6031. if (token_idx == -1) {
  6032. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  6033. }
  6034. const float * scores = nullptr;
  6035. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  6036. if (score_idx != -1) {
  6037. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  6038. }
  6039. const int * toktypes = nullptr;
  6040. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  6041. if (toktype_idx != -1) {
  6042. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  6043. }
  6044. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  6045. vocab.n_vocab = n_vocab;
  6046. vocab.id_to_token.resize(n_vocab);
  6047. for (uint32_t i = 0; i < n_vocab; i++) {
  6048. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  6049. //GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  6050. if (word.empty()) {
  6051. LLAMA_LOG_WARN("%s: empty token at index %u\n", __func__, i);
  6052. word = "[EMPTY_" + std::to_string(i) + "]";
  6053. }
  6054. vocab.token_to_id[word] = i;
  6055. vocab.max_token_len = std::max(vocab.max_token_len, (int) word.size());
  6056. auto & token_data = vocab.id_to_token[i];
  6057. token_data.text = std::move(word);
  6058. token_data.score = scores ? scores[i] : 0.0f;
  6059. token_data.attr = LLAMA_TOKEN_ATTR_NORMAL;
  6060. if (toktypes) { //TODO: remove, required until per token attributes are available from GGUF file
  6061. switch(toktypes[i]) {
  6062. case LLAMA_TOKEN_TYPE_UNKNOWN: token_data.attr = LLAMA_TOKEN_ATTR_UNKNOWN; break;
  6063. case LLAMA_TOKEN_TYPE_UNUSED: token_data.attr = LLAMA_TOKEN_ATTR_UNUSED; break;
  6064. case LLAMA_TOKEN_TYPE_NORMAL: token_data.attr = LLAMA_TOKEN_ATTR_NORMAL; break;
  6065. case LLAMA_TOKEN_TYPE_CONTROL: token_data.attr = LLAMA_TOKEN_ATTR_CONTROL; break;
  6066. case LLAMA_TOKEN_TYPE_USER_DEFINED: token_data.attr = LLAMA_TOKEN_ATTR_USER_DEFINED; break;
  6067. case LLAMA_TOKEN_TYPE_BYTE: token_data.attr = LLAMA_TOKEN_ATTR_BYTE; break;
  6068. case LLAMA_TOKEN_TYPE_UNDEFINED: token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED; break;
  6069. default: token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED; break;
  6070. }
  6071. }
  6072. }
  6073. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  6074. vocab.init_tokenizer();
  6075. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  6076. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  6077. try {
  6078. vocab.linefeed_id = llama_byte_to_token_impl(vocab, '\n');
  6079. } catch (const std::exception & e) {
  6080. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  6081. vocab.linefeed_id = vocab.special_pad_id;
  6082. }
  6083. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  6084. vocab.linefeed_id = vocab.special_pad_id;
  6085. } else if (vocab.type == LLAMA_VOCAB_TYPE_RWKV) {
  6086. const std::vector<int> ids = llama_tokenize_internal(vocab, "\n", false);
  6087. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  6088. vocab.linefeed_id = ids[0];
  6089. } else {
  6090. const std::vector<int> ids = llama_tokenize_internal(vocab, "\xC4\x8A", false); // U+010A
  6091. //GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  6092. if (ids.empty()) {
  6093. LLAMA_LOG_WARN("%s: model vocab missing newline token, using special_pad_id instead\n", __func__);
  6094. vocab.linefeed_id = vocab.special_pad_id;
  6095. } else {
  6096. vocab.linefeed_id = ids[0];
  6097. }
  6098. }
  6099. // special tokens
  6100. {
  6101. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  6102. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  6103. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  6104. { LLM_KV_TOKENIZER_EOT_ID, vocab.special_eot_id },
  6105. { LLM_KV_TOKENIZER_EOM_ID, vocab.special_eom_id },
  6106. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  6107. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  6108. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  6109. { LLM_KV_TOKENIZER_CLS_ID, vocab.special_cls_id },
  6110. { LLM_KV_TOKENIZER_MASK_ID, vocab.special_mask_id },
  6111. { LLM_KV_TOKENIZER_FIM_PRE_ID, vocab.special_fim_pre_id },
  6112. { LLM_KV_TOKENIZER_FIM_SUF_ID, vocab.special_fim_suf_id },
  6113. { LLM_KV_TOKENIZER_FIM_MID_ID, vocab.special_fim_mid_id },
  6114. { LLM_KV_TOKENIZER_FIM_PAD_ID, vocab.special_fim_pad_id },
  6115. { LLM_KV_TOKENIZER_FIM_REP_ID, vocab.special_fim_rep_id },
  6116. { LLM_KV_TOKENIZER_FIM_SEP_ID, vocab.special_fim_sep_id },
  6117. // deprecated
  6118. { LLM_KV_TOKENIZER_PREFIX_ID, vocab.special_fim_pre_id },
  6119. { LLM_KV_TOKENIZER_SUFFIX_ID, vocab.special_fim_suf_id },
  6120. { LLM_KV_TOKENIZER_MIDDLE_ID, vocab.special_fim_mid_id },
  6121. };
  6122. for (const auto & it : special_token_types) {
  6123. const std::string & key = kv(std::get<0>(it));
  6124. int32_t & id = std::get<1>(it);
  6125. uint32_t new_id;
  6126. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  6127. continue;
  6128. }
  6129. if (new_id >= vocab.id_to_token.size()) {
  6130. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  6131. __func__, key.c_str(), new_id, id);
  6132. } else {
  6133. id = new_id;
  6134. }
  6135. }
  6136. // Handle add_bos_token and add_eos_token
  6137. {
  6138. bool temp = true;
  6139. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  6140. vocab.tokenizer_add_bos = temp;
  6141. }
  6142. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  6143. vocab.tokenizer_add_eos = temp;
  6144. }
  6145. }
  6146. // auto-detect special tokens by text
  6147. // TODO: convert scripts should provide these tokens through the KV metadata LLM_KV_TOKENIZER_...
  6148. // for now, we apply this workaround to find the tokens based on their text
  6149. for (const auto & t : vocab.token_to_id) {
  6150. // find EOT token: "<|eot_id|>", "<|im_end|>", "<end_of_turn>", etc.
  6151. if (vocab.special_eot_id == LLAMA_TOKEN_NULL) {
  6152. if (false
  6153. || t.first == "<|eot_id|>"
  6154. || t.first == "<|im_end|>"
  6155. || t.first == "<|end|>"
  6156. || t.first == "<end_of_turn>"
  6157. || t.first == "<|endoftext|>"
  6158. || t.first == "<EOT>"
  6159. || t.first == "<|end▁of▁sentence|>" // DeepSeek
  6160. ) {
  6161. vocab.special_eot_id = t.second;
  6162. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6163. 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",
  6164. __func__, t.second, t.first.c_str());
  6165. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6166. }
  6167. }
  6168. }
  6169. // find EOM token: "<|eom_id|>"
  6170. if (vocab.special_eom_id == LLAMA_TOKEN_NULL) {
  6171. if (false
  6172. || t.first == "<|eom_id|>"
  6173. ) {
  6174. vocab.special_eom_id = t.second;
  6175. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6176. 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",
  6177. __func__, t.second, t.first.c_str());
  6178. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6179. }
  6180. }
  6181. }
  6182. // find FIM_PRE token: "<|fim_prefix|>", "<fim-prefix>", "<PRE>", etc.
  6183. if (vocab.special_fim_pre_id == LLAMA_TOKEN_NULL) {
  6184. if (false
  6185. || t.first == "<|fim_prefix|>" // Qwen
  6186. || t.first == "<fim-prefix>"
  6187. || t.first == "<|fim▁begin|>" // DeepSeek
  6188. || t.first == "<PRE>"
  6189. ) {
  6190. vocab.special_fim_pre_id = t.second;
  6191. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6192. 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",
  6193. __func__, t.second, t.first.c_str());
  6194. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6195. }
  6196. }
  6197. }
  6198. // find FIM_SUF token: "<|fim_suffix|>", "<fim-suffix>", "<SUF>", etc.
  6199. if (vocab.special_fim_suf_id == LLAMA_TOKEN_NULL) {
  6200. if (false
  6201. || t.first == "<|fim_suffix|>" // Qwen
  6202. || t.first == "<fim-suffix>"
  6203. || t.first == "<|fim▁hole|>" // DeepSeek
  6204. || t.first == "<SUF>"
  6205. ) {
  6206. vocab.special_fim_suf_id = t.second;
  6207. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6208. 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",
  6209. __func__, t.second, t.first.c_str());
  6210. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6211. }
  6212. }
  6213. }
  6214. // find FIM_MID token: "<|fim_middle|>", "<fim-middle>", "<MID>", etc.
  6215. if (vocab.special_fim_mid_id == LLAMA_TOKEN_NULL) {
  6216. if (false
  6217. || t.first == "<|fim_middle|>" // Qwen
  6218. || t.first == "<fim-middle>"
  6219. || t.first == "<|fim▁end|>" // DeepSeek
  6220. || t.first == "<MID>"
  6221. ) {
  6222. vocab.special_fim_mid_id = t.second;
  6223. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6224. 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",
  6225. __func__, t.second, t.first.c_str());
  6226. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6227. }
  6228. }
  6229. }
  6230. // find FIM_PAD token: "<|fim_pad|>", "<fim-pad>", "<PAD>", etc.
  6231. if (vocab.special_fim_pad_id == LLAMA_TOKEN_NULL) {
  6232. if (false
  6233. || t.first == "<|fim_pad|>" // Qwen
  6234. || t.first == "<fim-pad>"
  6235. || t.first == "<PAD>"
  6236. ) {
  6237. vocab.special_fim_pad_id = t.second;
  6238. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6239. 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",
  6240. __func__, t.second, t.first.c_str());
  6241. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6242. }
  6243. }
  6244. }
  6245. // find FIM_REP token: "<|fim_repo|>", "<fim-repo>", "<REP>", etc.
  6246. if (vocab.special_fim_rep_id == LLAMA_TOKEN_NULL) {
  6247. if (false
  6248. || t.first == "<|fim_repo|>" // Qwen
  6249. || t.first == "<|repo_name|>"
  6250. || t.first == "<fim-repo>"
  6251. || t.first == "<REPO>"
  6252. ) {
  6253. vocab.special_fim_rep_id = t.second;
  6254. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6255. 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",
  6256. __func__, t.second, t.first.c_str());
  6257. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6258. }
  6259. }
  6260. }
  6261. // find FIM_SEP token: "<|file_sep|>"
  6262. if (vocab.special_fim_sep_id == LLAMA_TOKEN_NULL) {
  6263. if (false
  6264. || t.first == "<|file_sep|>" // Qwen
  6265. ) {
  6266. vocab.special_fim_sep_id = t.second;
  6267. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6268. 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",
  6269. __func__, t.second, t.first.c_str());
  6270. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6271. }
  6272. }
  6273. }
  6274. }
  6275. // maintain a list of tokens that cause end-of-generation
  6276. // this is currently determined based on the token text, which is obviously not ideal
  6277. // ref: https://github.com/ggerganov/llama.cpp/issues/9606
  6278. vocab.special_eog_ids.clear();
  6279. if (vocab.special_fim_pad_id != LLAMA_TOKEN_NULL && vocab.special_eog_ids.count(vocab.special_fim_pad_id) == 0) {
  6280. vocab.special_eog_ids.insert(vocab.special_fim_pad_id);
  6281. }
  6282. if (vocab.special_fim_rep_id != LLAMA_TOKEN_NULL && vocab.special_eog_ids.count(vocab.special_fim_rep_id) == 0) {
  6283. vocab.special_eog_ids.insert(vocab.special_fim_rep_id);
  6284. }
  6285. if (vocab.special_fim_sep_id != LLAMA_TOKEN_NULL && vocab.special_eog_ids.count(vocab.special_fim_sep_id) == 0) {
  6286. vocab.special_eog_ids.insert(vocab.special_fim_sep_id);
  6287. }
  6288. for (const auto & t : vocab.token_to_id) {
  6289. if (false
  6290. || t.first == "<|eot_id|>"
  6291. || t.first == "<|im_end|>"
  6292. || t.first == "<|end|>"
  6293. || t.first == "<end_of_turn>"
  6294. || t.first == "<|endoftext|>"
  6295. || t.first == "<|eom_id|>"
  6296. || t.first == "<EOT>"
  6297. ) {
  6298. vocab.special_eog_ids.insert(t.second);
  6299. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6300. 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",
  6301. __func__, t.second, t.first.c_str());
  6302. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6303. }
  6304. } else {
  6305. // token is control, but not marked as EOG -> print a debug log
  6306. if (vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL && vocab.special_eog_ids.count(t.second) == 0) {
  6307. LLAMA_LOG_DEBUG("%s: control token: %6d '%s' is not marked as EOG\n",
  6308. __func__, t.second, t.first.c_str());
  6309. }
  6310. }
  6311. }
  6312. // sanity checks
  6313. if (vocab.special_eos_id != LLAMA_TOKEN_NULL && vocab.special_eog_ids.count(vocab.special_eos_id) == 0) {
  6314. vocab.special_eog_ids.insert(vocab.special_eos_id);
  6315. LLAMA_LOG_WARN("%s: special_eos_id is not in special_eog_ids - the tokenizer config may be incorrect\n", __func__);
  6316. }
  6317. if (vocab.special_eot_id != LLAMA_TOKEN_NULL && vocab.special_eog_ids.count(vocab.special_eot_id) == 0) {
  6318. vocab.special_eog_ids.insert(vocab.special_eot_id);
  6319. LLAMA_LOG_WARN("%s: special_eot_id is not in special_eog_ids - the tokenizer config may be incorrect\n", __func__);
  6320. }
  6321. if (vocab.special_eom_id != LLAMA_TOKEN_NULL && vocab.special_eog_ids.count(vocab.special_eom_id) == 0) {
  6322. vocab.special_eog_ids.insert(vocab.special_eom_id);
  6323. LLAMA_LOG_WARN("%s: special_eom_id is not in special_eog_ids - the tokenizer config may be incorrect\n", __func__);
  6324. }
  6325. }
  6326. // build special tokens cache
  6327. {
  6328. for (llama_vocab::id id = 0; id < (llama_vocab::id)n_vocab; ++id) {
  6329. if (vocab.id_to_token[id].attr & (LLAMA_TOKEN_ATTR_CONTROL | LLAMA_TOKEN_ATTR_USER_DEFINED | LLAMA_TOKEN_ATTR_UNKNOWN)) {
  6330. vocab.cache_special_tokens.push_back(id);
  6331. }
  6332. }
  6333. std::sort(vocab.cache_special_tokens.begin(), vocab.cache_special_tokens.end(),
  6334. [&] (const llama_vocab::id a, const llama_vocab::id b) {
  6335. return vocab.id_to_token[a].text.size() > vocab.id_to_token[b].text.size();
  6336. }
  6337. );
  6338. LLAMA_LOG_INFO("%s: special tokens cache size = %u\n", __func__, (uint32_t)vocab.cache_special_tokens.size());
  6339. }
  6340. // build token to piece cache
  6341. {
  6342. size_t size_cache = 0;
  6343. std::vector<llama_vocab::token> cache_token_to_piece(n_vocab);
  6344. for (uint32_t id = 0; id < n_vocab; ++id) {
  6345. cache_token_to_piece[id] = llama_token_to_piece(&model, id, true);
  6346. size_cache += cache_token_to_piece[id].size();
  6347. }
  6348. std::swap(vocab.cache_token_to_piece, cache_token_to_piece);
  6349. LLAMA_LOG_INFO("%s: token to piece cache size = %.4f MB\n", __func__, size_cache / 1024.0 / 1024.0);
  6350. }
  6351. // Handle per token attributes
  6352. //NOTE: Each model customizes per token attributes.
  6353. //NOTE: Per token attributes are missing from the GGUF file.
  6354. //TODO: Extract attributes from GGUF file.
  6355. {
  6356. auto _contains_any = [] (const std::string &str, const std::vector<std::string> &substrs) -> bool {
  6357. for (auto substr : substrs) {
  6358. if (str.find(substr) < std::string::npos) {
  6359. return true;
  6360. }
  6361. }
  6362. return false;
  6363. };
  6364. auto _set_tokenid_attr = [&] (const llama_vocab::id id, llama_token_attr attr, bool value) {
  6365. uint32_t current = vocab.id_to_token.at(id).attr;
  6366. current = value ? (current | attr) : (current & ~attr);
  6367. vocab.id_to_token[id].attr = (llama_token_attr) current;
  6368. };
  6369. auto _set_token_attr = [&] (const std::string & token, llama_token_attr attr, bool value) {
  6370. _set_tokenid_attr(vocab.token_to_id.at(token), attr, value);
  6371. };
  6372. std::string model_name;
  6373. std::string tokenizer_pre;
  6374. ml.get_key(LLM_KV_GENERAL_NAME, model_name, false);
  6375. ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false);
  6376. // model name to lowercase
  6377. std::transform(model_name.begin(), model_name.end(), model_name.begin(),
  6378. [] (const std::string::value_type x) {
  6379. return std::tolower(x);
  6380. }
  6381. );
  6382. // set attributes by model/tokenizer name
  6383. if (_contains_any(tokenizer_pre, {"jina-v2-de", "jina-v2-es", "jina-v2-code"})) {
  6384. _set_token_attr("<mask>", LLAMA_TOKEN_ATTR_LSTRIP, true);
  6385. } else if (_contains_any(model_name, {"phi-3", "phi3"})) {
  6386. for (auto id : vocab.cache_special_tokens) {
  6387. _set_tokenid_attr(id, LLAMA_TOKEN_ATTR_RSTRIP, true);
  6388. }
  6389. for (auto token : {"</s>"}) {
  6390. _set_token_attr(token, LLAMA_TOKEN_ATTR_RSTRIP, true);
  6391. }
  6392. for (auto token : {"<unk>", "<s>", "<|endoftext|>"}) {
  6393. _set_token_attr(token, LLAMA_TOKEN_ATTR_RSTRIP, false);
  6394. }
  6395. }
  6396. }
  6397. }
  6398. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  6399. const auto & hparams = model.hparams;
  6400. const auto & vocab = model.vocab;
  6401. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  6402. auto print_f = [](const std::function<uint32_t(uint32_t)> & f, uint32_t n) {
  6403. bool is_var = false;
  6404. std::vector<uint32_t> v;
  6405. for (uint32_t i = 0; i < n; ++i) {
  6406. v.push_back(f(i));
  6407. if (v[i] != v[0]) {
  6408. is_var = true;
  6409. }
  6410. }
  6411. std::stringstream ss;
  6412. if (is_var) {
  6413. ss << "[";
  6414. for (uint32_t i = 0; i < n; ++i) {
  6415. ss << v[i];
  6416. if (i < n - 1) {
  6417. ss << ", ";
  6418. }
  6419. }
  6420. ss << "]";
  6421. } else {
  6422. ss << v[0];
  6423. }
  6424. return ss.str();
  6425. };
  6426. // hparams
  6427. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  6428. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  6429. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  6430. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  6431. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  6432. LLAMA_LOG_INFO("%s: vocab_only = %d\n", __func__, hparams.vocab_only);
  6433. if (!hparams.vocab_only) {
  6434. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  6435. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  6436. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  6437. LLAMA_LOG_INFO("%s: n_head = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_head(il); }, hparams.n_layer).c_str());
  6438. 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());
  6439. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  6440. LLAMA_LOG_INFO("%s: n_swa = %u\n", __func__, hparams.n_swa);
  6441. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  6442. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  6443. LLAMA_LOG_INFO("%s: n_gqa = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_gqa(il); }, hparams.n_layer).c_str());
  6444. 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());
  6445. 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());
  6446. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  6447. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  6448. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  6449. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  6450. LLAMA_LOG_INFO("%s: f_logit_scale = %.1e\n", __func__, hparams.f_logit_scale);
  6451. LLAMA_LOG_INFO("%s: n_ff = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_ff(il); }, hparams.n_layer).c_str());
  6452. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  6453. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  6454. LLAMA_LOG_INFO("%s: causal attn = %d\n", __func__, hparams.causal_attn);
  6455. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  6456. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  6457. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  6458. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  6459. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  6460. LLAMA_LOG_INFO("%s: n_ctx_orig_yarn = %u\n", __func__, hparams.n_ctx_orig_yarn);
  6461. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  6462. LLAMA_LOG_INFO("%s: ssm_d_conv = %u\n", __func__, hparams.ssm_d_conv);
  6463. LLAMA_LOG_INFO("%s: ssm_d_inner = %u\n", __func__, hparams.ssm_d_inner);
  6464. LLAMA_LOG_INFO("%s: ssm_d_state = %u\n", __func__, hparams.ssm_d_state);
  6465. LLAMA_LOG_INFO("%s: ssm_dt_rank = %u\n", __func__, hparams.ssm_dt_rank);
  6466. LLAMA_LOG_INFO("%s: ssm_dt_b_c_rms = %d\n", __func__, hparams.ssm_dt_b_c_rms);
  6467. }
  6468. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  6469. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  6470. if (ml.n_elements >= 1e12) {
  6471. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  6472. } else if (ml.n_elements >= 1e9) {
  6473. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  6474. } else if (ml.n_elements >= 1e6) {
  6475. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  6476. } else {
  6477. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  6478. }
  6479. if (ml.n_bytes < GiB) {
  6480. 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);
  6481. } else {
  6482. 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);
  6483. }
  6484. // general kv
  6485. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  6486. // special tokens
  6487. 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() ); }
  6488. 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() ); }
  6489. 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() ); }
  6490. 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() ); }
  6491. 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() ); }
  6492. 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() ); }
  6493. 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() ); }
  6494. 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() ); }
  6495. 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() ); }
  6496. 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() ); }
  6497. 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() ); }
  6498. 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() ); }
  6499. 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() ); }
  6500. 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() ); }
  6501. 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() ); }
  6502. 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() ); }
  6503. for (const auto & id : vocab.special_eog_ids) {
  6504. LLAMA_LOG_INFO( "%s: EOG token = %d '%s'\n", __func__, id, vocab.id_to_token[id].text.c_str() );
  6505. }
  6506. LLAMA_LOG_INFO("%s: max token length = %d\n", __func__, vocab.max_token_len);
  6507. if (model.arch == LLM_ARCH_DEEPSEEK2) {
  6508. LLAMA_LOG_INFO("%s: n_layer_dense_lead = %d\n", __func__, hparams.n_layer_dense_lead);
  6509. LLAMA_LOG_INFO("%s: n_lora_q = %d\n", __func__, hparams.n_lora_q);
  6510. LLAMA_LOG_INFO("%s: n_lora_kv = %d\n", __func__, hparams.n_lora_kv);
  6511. LLAMA_LOG_INFO("%s: n_ff_exp = %d\n", __func__, hparams.n_ff_exp);
  6512. LLAMA_LOG_INFO("%s: n_expert_shared = %d\n", __func__, hparams.n_expert_shared);
  6513. LLAMA_LOG_INFO("%s: expert_weights_scale = %.1f\n", __func__, hparams.expert_weights_scale);
  6514. LLAMA_LOG_INFO("%s: rope_yarn_log_mul = %.4f\n", __func__, hparams.rope_yarn_log_mul);
  6515. }
  6516. if (model.arch == LLM_ARCH_QWEN2MOE) {
  6517. LLAMA_LOG_INFO("%s: n_ff_exp = %d\n", __func__, hparams.n_ff_exp);
  6518. LLAMA_LOG_INFO("%s: n_ff_shexp = %d\n", __func__, hparams.n_ff_shexp);
  6519. }
  6520. if (model.arch == LLM_ARCH_MINICPM || model.arch == LLM_ARCH_GRANITE || model.arch == LLM_ARCH_GRANITE_MOE) {
  6521. LLAMA_LOG_INFO("%s: f_embedding_scale = %f\n", __func__, hparams.f_embedding_scale);
  6522. LLAMA_LOG_INFO("%s: f_residual_scale = %f\n", __func__, hparams.f_residual_scale);
  6523. LLAMA_LOG_INFO("%s: f_attention_scale = %f\n", __func__, hparams.f_attention_scale);
  6524. }
  6525. }
  6526. enum llm_tensor_layer {
  6527. LLM_TENSOR_LAYER_INPUT,
  6528. LLM_TENSOR_LAYER_REPEATING,
  6529. LLM_TENSOR_LAYER_OUTPUT,
  6530. };
  6531. struct llm_tensor_info {
  6532. llm_tensor_layer layer;
  6533. ggml_op op;
  6534. };
  6535. static const std::map<llm_tensor, llm_tensor_info> llm_tensor_info_mapping = {
  6536. {LLM_TENSOR_TOKEN_EMBD, {LLM_TENSOR_LAYER_INPUT, GGML_OP_GET_ROWS}},
  6537. {LLM_TENSOR_POS_EMBD, {LLM_TENSOR_LAYER_INPUT, GGML_OP_GET_ROWS}},
  6538. {LLM_TENSOR_TOKEN_EMBD_NORM, {LLM_TENSOR_LAYER_INPUT, GGML_OP_GET_ROWS}},
  6539. {LLM_TENSOR_TOKEN_TYPES, {LLM_TENSOR_LAYER_INPUT, GGML_OP_GET_ROWS}},
  6540. {LLM_TENSOR_OUTPUT, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}},
  6541. {LLM_TENSOR_CLS, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}},
  6542. {LLM_TENSOR_CLS_OUT, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}},
  6543. {LLM_TENSOR_OUTPUT_NORM, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL}},
  6544. {LLM_TENSOR_DEC_OUTPUT_NORM, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL}},
  6545. {LLM_TENSOR_ENC_OUTPUT_NORM, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL}},
  6546. {LLM_TENSOR_ROPE_FREQS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ROPE}},
  6547. {LLM_TENSOR_ROPE_FACTORS_LONG, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ROPE}},
  6548. {LLM_TENSOR_ROPE_FACTORS_SHORT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ROPE}},
  6549. {LLM_TENSOR_ATTN_Q, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6550. {LLM_TENSOR_ATTN_K, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6551. {LLM_TENSOR_ATTN_V, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6552. {LLM_TENSOR_ATTN_QKV, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6553. {LLM_TENSOR_ATTN_OUT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6554. {LLM_TENSOR_FFN_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6555. {LLM_TENSOR_FFN_DOWN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6556. {LLM_TENSOR_FFN_UP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6557. {LLM_TENSOR_FFN_DOWN_SHEXP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6558. {LLM_TENSOR_FFN_GATE_SHEXP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6559. {LLM_TENSOR_FFN_UP_SHEXP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6560. {LLM_TENSOR_ATTN_Q_A, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6561. {LLM_TENSOR_ATTN_Q_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6562. {LLM_TENSOR_ATTN_KV_A_MQA, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6563. {LLM_TENSOR_ATTN_KV_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6564. {LLM_TENSOR_DEC_ATTN_Q, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6565. {LLM_TENSOR_DEC_ATTN_K, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6566. {LLM_TENSOR_ATTN_Q, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6567. {LLM_TENSOR_ATTN_K, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6568. {LLM_TENSOR_ATTN_V, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6569. {LLM_TENSOR_ATTN_QKV, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6570. {LLM_TENSOR_ATTN_OUT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6571. {LLM_TENSOR_FFN_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6572. {LLM_TENSOR_FFN_DOWN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6573. {LLM_TENSOR_FFN_UP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6574. {LLM_TENSOR_FFN_DOWN_SHEXP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6575. {LLM_TENSOR_FFN_GATE_SHEXP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6576. {LLM_TENSOR_FFN_UP_SHEXP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6577. {LLM_TENSOR_ATTN_Q_A, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6578. {LLM_TENSOR_ATTN_Q_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6579. {LLM_TENSOR_ATTN_KV_A_MQA, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6580. {LLM_TENSOR_ATTN_KV_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6581. {LLM_TENSOR_DEC_ATTN_Q, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6582. {LLM_TENSOR_DEC_ATTN_K, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6583. {LLM_TENSOR_DEC_ATTN_V, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6584. {LLM_TENSOR_DEC_ATTN_OUT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6585. {LLM_TENSOR_DEC_CROSS_ATTN_Q, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6586. {LLM_TENSOR_DEC_CROSS_ATTN_K, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6587. {LLM_TENSOR_DEC_CROSS_ATTN_V, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6588. {LLM_TENSOR_DEC_CROSS_ATTN_OUT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6589. {LLM_TENSOR_DEC_FFN_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6590. {LLM_TENSOR_DEC_FFN_DOWN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6591. {LLM_TENSOR_DEC_FFN_UP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6592. {LLM_TENSOR_ENC_ATTN_Q, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6593. {LLM_TENSOR_ENC_ATTN_K, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6594. {LLM_TENSOR_ENC_ATTN_V, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6595. {LLM_TENSOR_ENC_ATTN_OUT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6596. {LLM_TENSOR_ENC_FFN_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6597. {LLM_TENSOR_ENC_FFN_DOWN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6598. {LLM_TENSOR_ENC_FFN_UP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6599. {LLM_TENSOR_FFN_GATE_INP_SHEXP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6600. {LLM_TENSOR_FFN_GATE_INP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6601. {LLM_TENSOR_SSM_IN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6602. {LLM_TENSOR_SSM_X, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6603. {LLM_TENSOR_SSM_DT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6604. {LLM_TENSOR_SSM_OUT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6605. {LLM_TENSOR_TIME_MIX_W1, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6606. {LLM_TENSOR_TIME_MIX_W2, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6607. {LLM_TENSOR_TIME_MIX_DECAY_W1, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6608. {LLM_TENSOR_TIME_MIX_DECAY_W2, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6609. {LLM_TENSOR_TIME_MIX_KEY, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6610. {LLM_TENSOR_TIME_MIX_VALUE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6611. {LLM_TENSOR_TIME_MIX_RECEPTANCE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6612. {LLM_TENSOR_TIME_MIX_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6613. {LLM_TENSOR_TIME_MIX_OUTPUT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6614. {LLM_TENSOR_CHANNEL_MIX_KEY, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6615. {LLM_TENSOR_CHANNEL_MIX_RECEPTANCE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6616. {LLM_TENSOR_CHANNEL_MIX_VALUE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6617. {LLM_TENSOR_FFN_ACT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_DIV}},
  6618. {LLM_TENSOR_SSM_CONV1D, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_SSM_CONV}},
  6619. {LLM_TENSOR_SSM_A, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_SSM_SCAN}},
  6620. {LLM_TENSOR_SSM_D, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6621. {LLM_TENSOR_TIME_MIX_LERP_X, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6622. {LLM_TENSOR_TIME_MIX_LN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6623. {LLM_TENSOR_CHANNEL_MIX_LERP_K, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6624. {LLM_TENSOR_CHANNEL_MIX_LERP_R, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6625. {LLM_TENSOR_TIME_MIX_LERP_W, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}},
  6626. {LLM_TENSOR_TIME_MIX_LERP_K, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}},
  6627. {LLM_TENSOR_TIME_MIX_LERP_V, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}},
  6628. {LLM_TENSOR_TIME_MIX_LERP_R, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}},
  6629. {LLM_TENSOR_TIME_MIX_LERP_G, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}},
  6630. {LLM_TENSOR_TIME_MIX_DECAY, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}},
  6631. {LLM_TENSOR_TIME_MIX_FIRST, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_RWKV_WKV6}},
  6632. {LLM_TENSOR_ATTN_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6633. {LLM_TENSOR_ATTN_NORM_2, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6634. {LLM_TENSOR_ATTN_OUT_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6635. {LLM_TENSOR_ATTN_POST_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6636. {LLM_TENSOR_FFN_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6637. {LLM_TENSOR_FFN_POST_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6638. {LLM_TENSOR_FFN_NORM_EXPS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6639. {LLM_TENSOR_ATTN_Q_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6640. {LLM_TENSOR_ATTN_K_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6641. {LLM_TENSOR_LAYER_OUT_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6642. {LLM_TENSOR_ATTN_Q_A_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6643. {LLM_TENSOR_ATTN_KV_A_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6644. {LLM_TENSOR_ATTN_SUB_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6645. {LLM_TENSOR_FFN_SUB_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6646. {LLM_TENSOR_DEC_ATTN_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6647. {LLM_TENSOR_DEC_CROSS_ATTN_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6648. {LLM_TENSOR_DEC_FFN_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6649. {LLM_TENSOR_ENC_ATTN_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6650. {LLM_TENSOR_ENC_FFN_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6651. {LLM_TENSOR_DEC_ATTN_REL_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_GET_ROWS}},
  6652. {LLM_TENSOR_ENC_ATTN_REL_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_GET_ROWS}},
  6653. {LLM_TENSOR_FFN_DOWN_EXPS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT_ID}},
  6654. {LLM_TENSOR_FFN_GATE_EXPS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT_ID}},
  6655. {LLM_TENSOR_FFN_UP_EXPS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT_ID}},
  6656. // this tensor is loaded for T5, but never used
  6657. {LLM_TENSOR_DEC_CROSS_ATTN_REL_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_NONE}},
  6658. {LLM_TENSOR_BSKCN_TV, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6659. {LLM_TENSOR_CROSS_ATTN_K_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6660. {LLM_TENSOR_CROSS_ATTN_K_PROJ, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6661. {LLM_TENSOR_CROSS_ATTN_O_PROJ, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6662. {LLM_TENSOR_CROSS_ATTN_Q_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6663. {LLM_TENSOR_CROSS_ATTN_Q_PROJ, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6664. {LLM_TENSOR_CROSS_ATTN_V_PROJ, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6665. {LLM_TENSOR_CROSS_ATTN_ATTN_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6666. {LLM_TENSOR_CROSS_ATTN_MLP_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6667. };
  6668. // checks if the weight tensor can be used with the specified buffer type and device
  6669. 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) {
  6670. GGML_ASSERT(w != nullptr);
  6671. if (op == GGML_OP_NONE) {
  6672. return true;
  6673. }
  6674. ggml_init_params params = {
  6675. /*.mem_size =*/ ggml_tensor_overhead()*8,
  6676. /*.mem_buffer =*/ NULL,
  6677. /*.no_alloc =*/ true,
  6678. };
  6679. ggml_context_ptr ctx_ptr { ggml_init(params) };
  6680. if (!ctx_ptr) {
  6681. throw std::runtime_error(format("failed to create ggml context"));
  6682. }
  6683. ggml_context * ctx = ctx_ptr.get();
  6684. ggml_tensor * op_tensor = nullptr;
  6685. switch (op) {
  6686. case GGML_OP_GET_ROWS:
  6687. {
  6688. ggml_tensor * b = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 512);
  6689. op_tensor = ggml_get_rows(ctx, w, b);
  6690. } break;
  6691. case GGML_OP_MUL_MAT:
  6692. {
  6693. ggml_tensor * b = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, w->ne[0], 512, w->ne[2], w->ne[3]);
  6694. op_tensor = ggml_mul_mat(ctx, w, b);
  6695. } break;
  6696. case GGML_OP_MUL_MAT_ID:
  6697. {
  6698. int n_expert_used = hparams.n_expert_used;
  6699. ggml_tensor * b = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, w->ne[0], n_expert_used, 512);
  6700. ggml_tensor * ids = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, n_expert_used, 512);
  6701. op_tensor = ggml_mul_mat_id(ctx, w, b, ids);
  6702. } break;
  6703. case GGML_OP_ADD:
  6704. {
  6705. ggml_tensor * a = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, w->ne[0], w->ne[1], w->ne[2], w->ne[3]);
  6706. op_tensor = ggml_add(ctx, a, w);
  6707. } break;
  6708. case GGML_OP_MUL:
  6709. {
  6710. ggml_tensor * a = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, w->ne[0], w->ne[1], w->ne[2], w->ne[3]);
  6711. op_tensor = ggml_mul(ctx, a, w);
  6712. } break;
  6713. case GGML_OP_DIV:
  6714. {
  6715. ggml_tensor * a = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, w->ne[0]);
  6716. op_tensor = ggml_div(ctx, a, w);
  6717. } break;
  6718. case GGML_OP_ROPE:
  6719. {
  6720. int n_embd_head = hparams.n_embd_head_v;
  6721. int n_head = hparams.n_head();
  6722. ggml_tensor * a = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n_embd_head, n_head, 512);
  6723. ggml_tensor * b = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 512);
  6724. op_tensor = ggml_rope_ext(
  6725. ctx, a, b, w,
  6726. 0, 0, 0, 0, 0,
  6727. 0, 0, 0, 0
  6728. );
  6729. } break;
  6730. case GGML_OP_SSM_CONV:
  6731. {
  6732. // FIXME
  6733. ggml_tensor * conv_x = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, 12345, w->ne[1], 6789);
  6734. op_tensor = ggml_ssm_conv(ctx, conv_x, w);
  6735. } break;
  6736. case GGML_OP_SSM_SCAN:
  6737. {
  6738. // FIXME
  6739. const int64_t d_state = w->ne[0];
  6740. const int64_t d_inner = w->ne[1];
  6741. const int64_t n_seq_tokens = 512;
  6742. const int64_t n_seqs = 1;
  6743. ggml_tensor * s = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, d_state, d_inner, n_seqs);
  6744. ggml_tensor * x = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, d_inner, n_seq_tokens, n_seqs);
  6745. ggml_tensor * dt = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, d_inner, n_seq_tokens, n_seqs);
  6746. ggml_tensor * B = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, d_state, n_seq_tokens, n_seqs);
  6747. ggml_tensor * C = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, d_state, n_seq_tokens, n_seqs);
  6748. op_tensor = ggml_ssm_scan(ctx, s, x, dt, w, B, C);
  6749. } break;
  6750. case GGML_OP_RWKV_WKV6:
  6751. {
  6752. // FIXME
  6753. const int64_t S = 123;
  6754. const int64_t H = 123;
  6755. const int64_t n_tokens = 123;
  6756. const int64_t n_seqs = 123;
  6757. ggml_tensor * k = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, 1, H, n_tokens);
  6758. ggml_tensor * v = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 1, S, H, n_tokens);
  6759. ggml_tensor * r = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 1, S, H, n_tokens);
  6760. ggml_tensor * tf = w;
  6761. ggml_tensor * td = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 1, S, H, n_tokens);
  6762. ggml_tensor * state = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, n_seqs, S, H);
  6763. op_tensor = ggml_rwkv_wkv6(ctx, k, v, r, tf, td, state);
  6764. } break;
  6765. default:
  6766. GGML_ABORT("%s: missing test for op %s for tensor %s", __func__, ggml_op_name(op), w->name);
  6767. }
  6768. // create a temporary dummy buffer for the weight so that supports_op can check the buffer type
  6769. GGML_ASSERT(w->buffer == nullptr);
  6770. w->buffer = ggml_backend_buft_alloc_buffer(buft, 0);
  6771. bool op_supported = ggml_backend_dev_supports_op(dev, op_tensor);
  6772. ggml_backend_buffer_free(w->buffer);
  6773. w->buffer = nullptr;
  6774. return op_supported;
  6775. }
  6776. // find the first buffer type in the list that can use the tensor
  6777. 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) {
  6778. GGML_ASSERT(!buft_list.empty());
  6779. for (const auto & cur : buft_list) {
  6780. ggml_backend_dev_t cur_dev = cur.first;
  6781. ggml_backend_buffer_type_t cur_buft = cur.second;
  6782. if (weight_buft_supported(model.hparams, tensor, op, cur_buft, cur_dev)) {
  6783. return cur_buft;
  6784. }
  6785. }
  6786. return nullptr;
  6787. }
  6788. // CPU: ACCEL -> CPU extra -> GPU host -> CPU
  6789. static llama_model::buft_list_t make_cpu_buft_list(llama_model & model) {
  6790. llama_model::buft_list_t buft_list;
  6791. // add ACCEL buffer types
  6792. for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
  6793. ggml_backend_dev_t dev = ggml_backend_dev_get(i);
  6794. if (ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_ACCEL) {
  6795. auto * buft = ggml_backend_dev_buffer_type(dev);
  6796. // skip
  6797. if (buft != ggml_backend_cpu_buffer_type()) {
  6798. buft_list.emplace_back(dev, buft);
  6799. }
  6800. }
  6801. }
  6802. // add extra buffer types
  6803. auto * cpu_dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
  6804. auto * cpu_reg = ggml_backend_dev_backend_reg(cpu_dev);
  6805. auto ggml_backend_dev_get_extra_bufts_fn = (ggml_backend_dev_get_extra_bufts_t)
  6806. ggml_backend_reg_get_proc_address(cpu_reg, "ggml_backend_dev_get_extra_bufts");
  6807. if (ggml_backend_dev_get_extra_bufts_fn) {
  6808. ggml_backend_buffer_type_t * extra_bufts = ggml_backend_dev_get_extra_bufts_fn(cpu_dev);
  6809. while (extra_bufts && *extra_bufts) {
  6810. buft_list.emplace_back(cpu_dev, *extra_bufts);
  6811. ++extra_bufts;
  6812. }
  6813. }
  6814. // add a host buffer type
  6815. // storing the tensors in a host buffer is useful when the processing of large batches
  6816. // is offloaded to a GPU device, since it reduces the time spent on data transfers
  6817. // generally, this will be done using the first device in the list
  6818. // a better approach would be to handle this on a weight-by-weight basis using the offload_op
  6819. // function of the device to determine if it would benefit from being stored in a host buffer
  6820. for (auto * dev : model.devices) {
  6821. ggml_backend_buffer_type_t buft = ggml_backend_dev_host_buffer_type(dev);
  6822. if (buft) {
  6823. buft_list.emplace_back(dev, buft);
  6824. break;
  6825. }
  6826. }
  6827. // add the CPU buffer type
  6828. for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
  6829. ggml_backend_dev_t dev = ggml_backend_dev_get(i);
  6830. if (ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_CPU) {
  6831. buft_list.emplace_back(dev, ggml_backend_dev_buffer_type(dev));
  6832. }
  6833. }
  6834. return buft_list;
  6835. }
  6836. // GPU: split if LLAMA_SPLIT_MODE_ROW -> GPU
  6837. 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) {
  6838. llama_model::buft_list_t buft_list;
  6839. // add the device split buffer type if requested and available
  6840. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  6841. ggml_backend_reg_t reg = ggml_backend_dev_backend_reg(dev);
  6842. auto ggml_backend_split_buffer_type_fn = (ggml_backend_split_buffer_type_t)
  6843. ggml_backend_reg_get_proc_address(reg, "ggml_backend_split_buffer_type");
  6844. if (ggml_backend_split_buffer_type_fn) {
  6845. size_t dev_index = [&]() {
  6846. auto * reg = ggml_backend_dev_backend_reg(dev);
  6847. for (size_t i = 0; i < ggml_backend_reg_dev_count(reg); ++i) {
  6848. if (ggml_backend_reg_dev_get(reg, i) == dev) {
  6849. return i;
  6850. }
  6851. }
  6852. throw std::runtime_error(format("device %s not found in its backend reg", ggml_backend_dev_name(dev)));
  6853. }();
  6854. auto * buft = ggml_backend_split_buffer_type_fn(dev_index, tensor_split);
  6855. if (buft != nullptr) {
  6856. buft_list.emplace_back(dev, buft);
  6857. }
  6858. }
  6859. }
  6860. // add the device default buffer type
  6861. buft_list.emplace_back(dev, ggml_backend_dev_buffer_type(dev));
  6862. return buft_list;
  6863. }
  6864. // Returns false if cancelled by progress_callback
  6865. static bool llm_load_tensors(
  6866. llama_model_loader & ml,
  6867. llama_model & model,
  6868. int n_gpu_layers,
  6869. enum llama_split_mode split_mode,
  6870. int main_gpu,
  6871. const float * tensor_split,
  6872. bool use_mlock,
  6873. llama_progress_callback progress_callback,
  6874. void * progress_callback_user_data) {
  6875. auto & hparams = model.hparams;
  6876. model.split_mode = split_mode;
  6877. model.main_gpu = main_gpu;
  6878. model.n_gpu_layers = n_gpu_layers;
  6879. const int n_layer = hparams.n_layer;
  6880. bool use_mmap_buffer = true;
  6881. // build a list of buffer types for the CPU and GPU devices
  6882. model.cpu_buft_list = make_cpu_buft_list(model);
  6883. for (auto * dev : model.devices) {
  6884. llama_model::buft_list_t buft_list = make_gpu_buft_list(dev, split_mode, tensor_split);
  6885. // add CPU buffer types as a fallback
  6886. buft_list.insert(buft_list.end(), model.cpu_buft_list.begin(), model.cpu_buft_list.end());
  6887. model.gpu_buft_list.emplace(dev, std::move(buft_list));
  6888. }
  6889. // calculate the split points
  6890. int device_count = llama_get_device_count(model);
  6891. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  6892. std::vector<float> splits(device_count);
  6893. if (all_zero) {
  6894. // default split, by free memory
  6895. for (int i = 0; i < device_count; ++i) {
  6896. ggml_backend_dev_t dev = model.devices[i];
  6897. size_t total;
  6898. size_t free;
  6899. ggml_backend_dev_memory(dev, &free, &total);
  6900. splits[i] = free;
  6901. }
  6902. } else {
  6903. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  6904. }
  6905. // sum and normalize the splits to get the split points
  6906. float split_sum = 0.0f;
  6907. for (int i = 0; i < device_count; ++i) {
  6908. split_sum += splits[i];
  6909. splits[i] = split_sum;
  6910. }
  6911. for (int i = 0; i < device_count; ++i) {
  6912. splits[i] /= split_sum;
  6913. }
  6914. ggml_backend_dev_t cpu_dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
  6915. const int i_gpu_start = std::max((int) hparams.n_layer - n_gpu_layers, (int) 0);
  6916. const int act_gpu_layers = model.devices.empty() ? 0 : std::min(n_gpu_layers, (int)n_layer + 1);
  6917. auto get_layer_buft_list = [&](int il) -> llama_model::layer_dev {
  6918. if (il < i_gpu_start || (il - i_gpu_start) >= act_gpu_layers) {
  6919. return {cpu_dev, &model.cpu_buft_list};
  6920. }
  6921. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(il - i_gpu_start)/act_gpu_layers) - splits.begin();
  6922. auto * dev = model.devices.at(layer_gpu);
  6923. return {dev, &model.gpu_buft_list.at(dev)};
  6924. };
  6925. // assign the input layer
  6926. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  6927. model.dev_input = { cpu_dev, &model.cpu_buft_list };
  6928. // assign the repeating layers to the devices according to the splits
  6929. model.dev_layer.resize(n_layer);
  6930. for (int il = 0; il < n_layer; ++il) {
  6931. model.dev_layer[il] = get_layer_buft_list(il);
  6932. }
  6933. // assign the output layer
  6934. model.dev_output = get_layer_buft_list(n_layer);
  6935. // one ggml context per buffer type
  6936. int max_n_tensors = ml.n_tensors;
  6937. max_n_tensors += 1; // duplicated output tensor
  6938. max_n_tensors += n_layer*2; // duplicated rope freq tensors
  6939. const size_t ctx_size = ggml_tensor_overhead()*max_n_tensors;
  6940. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  6941. auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
  6942. auto it = ctx_map.find(buft);
  6943. if (it == ctx_map.end()) {
  6944. ggml_init_params params = {
  6945. /*.mem_size =*/ ctx_size,
  6946. /*.mem_buffer =*/ NULL,
  6947. /*.no_alloc =*/ true,
  6948. };
  6949. ggml_context * ctx = ggml_init(params);
  6950. if (!ctx) {
  6951. throw std::runtime_error(format("failed to create ggml context"));
  6952. }
  6953. ctx_map[buft] = ctx;
  6954. model.ctxs.emplace_back(ctx);
  6955. return ctx;
  6956. }
  6957. return it->second;
  6958. };
  6959. // create tensors for the weights
  6960. {
  6961. // note: cast to int64_t since we will use these for the tensor dimensions
  6962. const int64_t n_head = hparams.n_head();
  6963. const int64_t n_head_kv = hparams.n_head_kv();
  6964. const int64_t n_embd = hparams.n_embd;
  6965. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  6966. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  6967. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  6968. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  6969. const int64_t n_ff = hparams.n_ff();
  6970. const int64_t n_embd_gqa = n_embd_v_gqa;
  6971. const int64_t n_vocab = hparams.n_vocab;
  6972. const int64_t n_vocab_type = hparams.n_vocab_type;
  6973. const int64_t n_rot = hparams.n_rot;
  6974. const int64_t n_expert = hparams.n_expert;
  6975. const int64_t n_expert_used = hparams.n_expert_used;
  6976. const int64_t n_ctx_train = hparams.n_ctx_train;
  6977. if (n_expert > 0 && hparams.n_expert_used == 0) {
  6978. throw std::runtime_error("model has expert layers but no expert layers are used");
  6979. }
  6980. int n_moved_tensors = 0;
  6981. ggml_tensor * first_moved_tensor = nullptr;
  6982. ggml_backend_buffer_type_t first_moved_from_buft = nullptr;
  6983. ggml_backend_buffer_type_t first_moved_to_buft = nullptr;
  6984. auto create_tensor = [&](const LLM_TN_IMPL & tn, const std::initializer_list<int64_t> & ne, int flags) -> ggml_tensor * {
  6985. ggml_tensor * t_meta = ml.get_tensor_meta(tn.str().c_str());
  6986. if (!t_meta) {
  6987. if (flags & llama_model_loader::TENSOR_NOT_REQUIRED) {
  6988. return nullptr;
  6989. }
  6990. throw std::runtime_error(format("missing tensor '%s'", tn.str().c_str()));
  6991. }
  6992. // some models use the token embedding tensor as the output, but since these are used in different layers and with different ops
  6993. // the tensor is duplicated
  6994. // to handle this, we check if the tensor is duplicated, and if so, we assume that it is being loaded as the output tensor
  6995. llm_tensor tn_tensor = tn.tensor;
  6996. if (tn.tensor == LLM_TENSOR_TOKEN_EMBD && flags & llama_model_loader::TENSOR_DUPLICATED) {
  6997. tn_tensor = LLM_TENSOR_OUTPUT;
  6998. }
  6999. auto it = llm_tensor_info_mapping.find(tn_tensor);
  7000. if (it == llm_tensor_info_mapping.end()) {
  7001. throw std::runtime_error(format("missing tensor info mapping for %s", tn.str().c_str()));
  7002. }
  7003. const auto & info = it->second;
  7004. // tensors with "bias" suffix are always used with GGML_OP_ADD
  7005. ggml_op op;
  7006. bool bias = tn.suffix != nullptr && strcmp(tn.suffix, "bias") == 0;
  7007. if (bias) {
  7008. op = GGML_OP_ADD;
  7009. } else {
  7010. op = info.op;
  7011. }
  7012. // sanity checks
  7013. if (info.layer == LLM_TENSOR_LAYER_INPUT || info.layer == LLM_TENSOR_LAYER_OUTPUT) {
  7014. if (tn.bid != -1) {
  7015. GGML_ABORT("input/output layer tensor %s used with a layer number", tn.str().c_str());
  7016. }
  7017. } else {
  7018. if (tn.bid == -1) {
  7019. GGML_ABORT("repeating layer tensor %s used without a layer number", tn.str().c_str());
  7020. }
  7021. }
  7022. // select the buffer type for this tensor
  7023. llama_model::buft_list_t * buft_list;
  7024. switch (info.layer) {
  7025. case LLM_TENSOR_LAYER_INPUT:
  7026. buft_list = model.dev_input.buft_list;
  7027. break;
  7028. case LLM_TENSOR_LAYER_OUTPUT:
  7029. buft_list = model.dev_output.buft_list;
  7030. break;
  7031. case LLM_TENSOR_LAYER_REPEATING:
  7032. buft_list = model.dev_layer.at(tn.bid).buft_list;
  7033. break;
  7034. default:
  7035. GGML_ABORT("invalid layer %d for tensor %s", info.layer, tn.str().c_str());
  7036. }
  7037. ggml_backend_buffer_type_t buft = select_weight_buft(model, t_meta, op, *buft_list);
  7038. if (!buft) {
  7039. throw std::runtime_error(format("failed to find a compatible buffer type for tensor %s", tn.str().c_str()));
  7040. }
  7041. // avoid using a host buffer when using mmap
  7042. auto * buft_dev = ggml_backend_buft_get_device(buft);
  7043. if (ml.use_mmap && buft_dev && buft == ggml_backend_dev_host_buffer_type(buft_dev)) {
  7044. auto * cpu_dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
  7045. buft = ggml_backend_dev_buffer_type(cpu_dev);
  7046. }
  7047. if (buft != buft_list->front().second) {
  7048. n_moved_tensors++;
  7049. if (!first_moved_tensor) {
  7050. first_moved_tensor = t_meta;
  7051. first_moved_from_buft = buft_list->front().second;
  7052. first_moved_to_buft = buft;
  7053. }
  7054. }
  7055. ggml_context * ctx = ctx_for_buft(buft);
  7056. // if duplicated, check if the original tensor was allocated in the same buffer type context and avoid creating a new one
  7057. if (flags & llama_model_loader::TENSOR_DUPLICATED) {
  7058. ggml_tensor * t = ggml_get_tensor(ctx, tn.str().c_str());
  7059. if (t) {
  7060. return t;
  7061. }
  7062. }
  7063. return ml.create_tensor(ctx, tn, ne, flags);
  7064. };
  7065. model.layers.resize(n_layer);
  7066. // TODO: move to a separate function
  7067. const auto tn = LLM_TN(model.arch);
  7068. switch (model.arch) {
  7069. case LLM_ARCH_LLAMA:
  7070. case LLM_ARCH_REFACT:
  7071. case LLM_ARCH_MINICPM:
  7072. case LLM_ARCH_GRANITE:
  7073. case LLM_ARCH_GRANITE_MOE:
  7074. {
  7075. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7076. // output
  7077. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7078. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7079. // if output is NULL, init from the input tok embed
  7080. if (model.output == NULL) {
  7081. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7082. }
  7083. for (int i = 0; i < n_layer; ++i) {
  7084. auto & layer = model.layers[i];
  7085. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7086. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head}, 0);
  7087. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  7088. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  7089. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd}, 0);
  7090. // optional bias tensors
  7091. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7092. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7093. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7094. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7095. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7096. if (hparams.rope_scaling_type_train == LLAMA_ROPE_SCALING_TYPE_LONGROPE) {
  7097. layer.rope_long = create_tensor(tn(LLM_TENSOR_ROPE_FACTORS_LONG, "weight", i), {n_rot/2}, llama_model_loader::TENSOR_NOT_REQUIRED | (i != 0 ? llama_model_loader::TENSOR_DUPLICATED : 0));
  7098. layer.rope_short = create_tensor(tn(LLM_TENSOR_ROPE_FACTORS_SHORT, "weight", i), {n_rot/2}, llama_model_loader::TENSOR_NOT_REQUIRED | (i != 0 ? llama_model_loader::TENSOR_DUPLICATED : 0));
  7099. }
  7100. else {
  7101. 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));
  7102. }
  7103. if (n_expert == 0) {
  7104. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7105. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7106. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7107. // optional MLP bias
  7108. layer.ffn_gate_b = create_tensor(tn(LLM_TENSOR_FFN_GATE, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7109. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7110. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7111. } else {
  7112. layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0);
  7113. 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);
  7114. layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert}, 0);
  7115. layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert}, 0);
  7116. }
  7117. }
  7118. } break;
  7119. case LLM_ARCH_MLLAMA:
  7120. {
  7121. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab+8}, 0);
  7122. // output
  7123. {
  7124. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7125. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7126. // if output is NULL, init from the input tok embed
  7127. if (model.output == NULL) {
  7128. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7129. }
  7130. }
  7131. for (int i = 0; i < n_layer; ++i) {
  7132. auto & layer = model.layers[i];
  7133. if (hparams.cross_attention_layers(i)) {
  7134. layer.cross_attn_k_norm = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_K_NORM, "weight", i), {128}, 0);
  7135. layer.cross_attn_k_proj = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_K_PROJ, "weight", i), {n_embd, 1024}, 0);
  7136. layer.cross_attn_o_proj = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_O_PROJ, "weight", i), {n_embd, n_embd}, 0);
  7137. layer.cross_attn_q_norm = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_Q_NORM, "weight", i), {128}, 0);
  7138. layer.cross_attn_q_proj = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_Q_PROJ, "weight", i), {n_embd, n_embd}, 0);
  7139. layer.cross_attn_v_proj = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_V_PROJ, "weight", i), {n_embd, 1024}, 0);
  7140. layer.cross_attn_attn_gate = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_ATTN_GATE, i), {1}, 0);
  7141. layer.cross_attn_mlp_gate = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_MLP_GATE, i), {1}, 0);
  7142. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7143. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7144. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7145. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7146. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7147. } else {
  7148. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7149. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head}, 0);
  7150. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  7151. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  7152. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd}, 0);
  7153. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7154. 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));
  7155. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7156. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7157. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7158. }
  7159. }
  7160. } break;
  7161. case LLM_ARCH_MINICPM3:
  7162. {
  7163. const int64_t n_embd_head_qk_rope = hparams.n_rot;
  7164. const int64_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  7165. const int64_t q_lora_rank = hparams.n_lora_q;
  7166. const int64_t kv_lora_rank = hparams.n_lora_kv;
  7167. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7168. // output
  7169. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7170. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7171. // if output is NULL, init from the input tok embed
  7172. if (model.output == NULL) {
  7173. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7174. }
  7175. for (int i = 0; i < n_layer; ++i) {
  7176. auto & layer = model.layers[i];
  7177. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7178. layer.attn_q_a_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_A_NORM, "weight", i), {q_lora_rank}, 0);
  7179. layer.attn_kv_a_norm = create_tensor(tn(LLM_TENSOR_ATTN_KV_A_NORM, "weight", i), {kv_lora_rank}, 0);
  7180. layer.wq_a = create_tensor(tn(LLM_TENSOR_ATTN_Q_A, "weight", i), {n_embd, q_lora_rank}, 0);
  7181. layer.wq_b = create_tensor(tn(LLM_TENSOR_ATTN_Q_B, "weight", i), {q_lora_rank, n_head * n_embd_head_k}, 0);
  7182. 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);
  7183. 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);
  7184. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_head * ( n_embd_head_v), n_embd}, 0);
  7185. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7186. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7187. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7188. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7189. 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));
  7190. 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));
  7191. }
  7192. } break;
  7193. case LLM_ARCH_GROK:
  7194. {
  7195. if (n_expert == 0) {
  7196. throw std::runtime_error("Grok model cannot have zero experts");
  7197. }
  7198. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7199. // output
  7200. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7201. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7202. // if output is NULL, init from the input tok embed
  7203. if (model.output == NULL) {
  7204. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7205. }
  7206. for (int i = 0; i < n_layer; ++i) {
  7207. auto & layer = model.layers[i];
  7208. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7209. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7210. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7211. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7212. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7213. layer.attn_out_norm = create_tensor(tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd}, 0);
  7214. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7215. layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0);
  7216. 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);
  7217. layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert}, 0);
  7218. layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert}, 0);
  7219. layer.layer_out_norm = create_tensor(tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd}, 0);
  7220. }
  7221. } break;
  7222. case LLM_ARCH_DBRX:
  7223. {
  7224. if (n_expert == 0) {
  7225. throw std::runtime_error("DBRX model cannot have zero experts");
  7226. }
  7227. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7228. // output
  7229. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7230. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7231. for (int i = 0; i < n_layer; ++i) {
  7232. auto & layer = model.layers[i];
  7233. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7234. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7235. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7236. layer.attn_out_norm = create_tensor(tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd}, 0);
  7237. layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0);
  7238. layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, 0);
  7239. layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff, n_embd, n_expert}, 0);
  7240. layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert}, 0);
  7241. }
  7242. } break;
  7243. case LLM_ARCH_BAICHUAN:
  7244. {
  7245. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7246. {
  7247. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7248. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7249. }
  7250. for (int i = 0; i < n_layer; ++i) {
  7251. auto & layer = model.layers[i];
  7252. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7253. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7254. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7255. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7256. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7257. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7258. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7259. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7260. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7261. }
  7262. } break;
  7263. case LLM_ARCH_FALCON:
  7264. {
  7265. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7266. // output
  7267. {
  7268. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7269. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7270. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7271. if (!model.output) {
  7272. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED); // needs to be on GPU
  7273. }
  7274. }
  7275. for (int i = 0; i < n_layer; ++i) {
  7276. auto & layer = model.layers[i];
  7277. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7278. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7279. layer.attn_norm_2 = create_tensor(tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7280. layer.attn_norm_2_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7281. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7282. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7283. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7284. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7285. }
  7286. } break;
  7287. case LLM_ARCH_STARCODER:
  7288. {
  7289. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7290. model.pos_embd = create_tensor(tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train}, 0);
  7291. // output
  7292. {
  7293. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7294. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7295. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7296. if (!model.output) {
  7297. // needs to be on GPU
  7298. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7299. }
  7300. }
  7301. for (int i = 0; i < n_layer; ++i) {
  7302. auto & layer = model.layers[i];
  7303. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7304. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7305. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7306. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, 0);
  7307. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7308. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  7309. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7310. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  7311. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7312. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  7313. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7314. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0);
  7315. }
  7316. } break;
  7317. case LLM_ARCH_BERT:
  7318. case LLM_ARCH_NOMIC_BERT:
  7319. {
  7320. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7321. model.type_embd = create_tensor(tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type}, 0);
  7322. if (model.arch == LLM_ARCH_BERT) {
  7323. model.pos_embd = create_tensor(tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train}, 0);
  7324. model.cls = create_tensor(tn(LLM_TENSOR_CLS, "weight"), {n_embd, n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7325. model.cls_b = create_tensor(tn(LLM_TENSOR_CLS, "bias"), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7326. model.cls_out = create_tensor(tn(LLM_TENSOR_CLS_OUT, "weight"), {n_embd, 1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7327. model.cls_out_b = create_tensor(tn(LLM_TENSOR_CLS_OUT, "bias"), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7328. }
  7329. model.tok_norm = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd}, 0);
  7330. model.tok_norm_b = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd}, 0);
  7331. for (int i = 0; i < n_layer; ++i) {
  7332. auto & layer = model.layers[i];
  7333. if (model.arch == LLM_ARCH_BERT) {
  7334. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7335. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, 0);
  7336. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7337. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, 0);
  7338. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7339. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, 0);
  7340. } else {
  7341. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7342. }
  7343. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7344. layer.attn_out_norm = create_tensor(tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd}, 0);
  7345. layer.attn_out_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd}, 0);
  7346. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7347. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7348. if (model.arch == LLM_ARCH_BERT) {
  7349. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  7350. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0);
  7351. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  7352. } else {
  7353. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7354. }
  7355. layer.layer_out_norm = create_tensor(tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd}, 0);
  7356. layer.layer_out_norm_b = create_tensor(tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd}, 0);
  7357. }
  7358. } break;
  7359. case LLM_ARCH_JINA_BERT_V2:
  7360. {
  7361. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0); // word_embeddings
  7362. model.type_embd = create_tensor(tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type}, 0); // token_type_embeddings
  7363. model.tok_norm = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd}, 0); // LayerNorm
  7364. model.tok_norm_b = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd}, 0); //LayerNorm bias
  7365. model.cls = create_tensor(tn(LLM_TENSOR_CLS, "weight"), {n_embd, 1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7366. model.cls_b = create_tensor(tn(LLM_TENSOR_CLS, "bias"), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7367. for (int i = 0; i < n_layer; ++i) {
  7368. auto & layer = model.layers[i]; // JinaBertLayer
  7369. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7370. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, 0);
  7371. layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7372. layer.attn_q_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7373. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7374. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, 0);
  7375. layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7376. layer.attn_k_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7377. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7378. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, 0);
  7379. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0); //output_dens
  7380. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0); //output_dens
  7381. layer.attn_out_norm = create_tensor(tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd}, 0); //output_norm
  7382. layer.attn_out_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd}, 0);
  7383. layer.attn_norm_2 = create_tensor(tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7384. layer.attn_norm_2_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7385. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7386. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  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}, 0);
  7389. layer.layer_out_norm = create_tensor(tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd}, 0);
  7390. layer.layer_out_norm_b = create_tensor(tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd}, 0);
  7391. }
  7392. } break;
  7393. case LLM_ARCH_BLOOM:
  7394. {
  7395. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7396. model.tok_norm = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd}, 0);
  7397. model.tok_norm_b = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd}, 0);
  7398. // output
  7399. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7400. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7401. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7402. for (int i = 0; i < n_layer; ++i) {
  7403. auto & layer = model.layers[i];
  7404. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7405. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7406. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7407. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, 0);
  7408. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7409. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  7410. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7411. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  7412. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7413. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  7414. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7415. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0);
  7416. }
  7417. } break;
  7418. case LLM_ARCH_MPT:
  7419. {
  7420. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7421. model.pos_embd = create_tensor(tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7422. // output
  7423. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7424. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7425. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7426. if (!model.output) {
  7427. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED); // needs to be on GPU
  7428. }
  7429. for (int i = 0; i < n_layer; ++i) {
  7430. auto & layer = model.layers[i];
  7431. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7432. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7433. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7434. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7435. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7436. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7437. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7438. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7439. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7440. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7441. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7442. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7443. layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7444. layer.attn_q_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7445. layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7446. layer.attn_k_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7447. // AWQ ScaleActivation layer
  7448. layer.ffn_act = create_tensor(tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7449. }
  7450. } break;
  7451. case LLM_ARCH_STABLELM:
  7452. {
  7453. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7454. // output
  7455. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7456. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7457. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7458. for (int i = 0; i < n_layer; ++i) {
  7459. auto & layer = model.layers[i];
  7460. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7461. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7462. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7463. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7464. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7465. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7466. // optional bias tensors, present in Stable LM 2 1.6B
  7467. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7468. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7469. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7470. // optional q and k layernorms, present in StableLM 2 12B
  7471. 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);
  7472. 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);
  7473. // optional FFN norm, not present in StableLM 2 12B which uses parallel residual
  7474. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7475. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7476. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7477. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7478. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7479. }
  7480. } break;
  7481. case LLM_ARCH_QWEN:
  7482. {
  7483. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7484. // output
  7485. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7486. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7487. for (int i = 0; i < n_layer; ++i) {
  7488. auto & layer = model.layers[i];
  7489. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7490. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3}, 0);
  7491. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3}, 0);
  7492. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7493. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7494. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2}, 0);
  7495. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd}, 0);
  7496. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2}, 0);
  7497. }
  7498. } break;
  7499. case LLM_ARCH_QWEN2:
  7500. case LLM_ARCH_QWEN2VL:
  7501. {
  7502. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7503. // output
  7504. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7505. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7506. // if output is NULL, init from the input tok embed
  7507. if (model.output == NULL) {
  7508. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7509. }
  7510. for (int i = 0; i < n_layer; ++i) {
  7511. auto & layer = model.layers[i];
  7512. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7513. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7514. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7515. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7516. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7517. // optional bias tensors
  7518. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, 0);
  7519. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, 0);
  7520. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, 0);
  7521. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7522. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7523. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7524. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7525. }
  7526. } break;
  7527. case LLM_ARCH_QWEN2MOE:
  7528. {
  7529. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7530. // output
  7531. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7532. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7533. for (int i = 0; i < n_layer; ++i) {
  7534. auto & layer = model.layers[i];
  7535. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7536. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7537. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7538. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7539. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7540. // optional bias tensors
  7541. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, 0);
  7542. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, 0);
  7543. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, 0);
  7544. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7545. layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0);
  7546. if (n_expert == 0) {
  7547. throw std::runtime_error("n_expert must be > 0 for QWEN2MOE");
  7548. }
  7549. if (n_expert_used == 0) {
  7550. throw std::runtime_error("n_expert_used must be > 0 for QWEN2MOE");
  7551. }
  7552. // MoE branch
  7553. const int64_t n_ff_exp = hparams.n_ff_exp ? hparams.n_ff_exp : n_ff / n_expert_used;
  7554. layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert}, 0);
  7555. layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert}, 0);
  7556. layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert}, 0);
  7557. // Shared expert branch
  7558. const int64_t n_ff_shexp = hparams.n_ff_shexp ? hparams.n_ff_shexp : n_ff;
  7559. layer.ffn_gate_inp_shexp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP_SHEXP, "weight", i), {n_embd}, 0);
  7560. layer.ffn_gate_shexp = create_tensor(tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), { n_embd, n_ff_shexp}, 0);
  7561. layer.ffn_down_shexp = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), {n_ff_shexp, n_embd}, 0);
  7562. layer.ffn_up_shexp = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), { n_embd, n_ff_shexp}, 0);
  7563. }
  7564. } break;
  7565. case LLM_ARCH_PHI2:
  7566. {
  7567. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7568. // output
  7569. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7570. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7571. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7572. model.output_b = create_tensor(tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab}, 0);
  7573. for (int i = 0; i < n_layer; ++i) {
  7574. auto & layer = model.layers[i];
  7575. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7576. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7577. 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);
  7578. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7579. if (layer.wqkv == nullptr) {
  7580. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7581. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, 0);
  7582. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7583. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, 0);
  7584. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7585. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, 0);
  7586. }
  7587. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7588. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  7589. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7590. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  7591. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7592. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0);
  7593. }
  7594. } break;
  7595. case LLM_ARCH_PHI3:
  7596. {
  7597. const int64_t n_embd_head = n_embd / n_head;
  7598. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), { n_embd, n_vocab }, 0);
  7599. // output
  7600. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), { n_embd }, 0);
  7601. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), { n_embd, n_vocab }, 0);
  7602. for (int i = 0; i < n_layer; ++i) {
  7603. auto & layer = model.layers[i];
  7604. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), { n_embd }, 0);
  7605. 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);
  7606. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_embd, n_embd }, 0);
  7607. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), { n_embd }, 0);
  7608. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd }, 0);
  7609. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), { n_embd, 2 * n_ff }, 0);
  7610. 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));
  7611. 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));
  7612. }
  7613. } break;
  7614. case LLM_ARCH_PLAMO:
  7615. {
  7616. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7617. // output
  7618. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7619. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7620. for (int i = 0; i < n_layer; ++i) {
  7621. auto & layer = model.layers[i];
  7622. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7623. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7624. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7625. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7626. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7627. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7628. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7629. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7630. }
  7631. } break;
  7632. case LLM_ARCH_GPT2:
  7633. {
  7634. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7635. model.pos_embd = create_tensor(tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train}, 0);
  7636. // output
  7637. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7638. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7639. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7640. for (int i = 0; i < n_layer; ++i) {
  7641. auto & layer = model.layers[i];
  7642. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7643. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7644. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7645. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, 0);
  7646. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7647. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  7648. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7649. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  7650. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7651. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  7652. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7653. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0);
  7654. }
  7655. } break;
  7656. case LLM_ARCH_CODESHELL:
  7657. {
  7658. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7659. // output
  7660. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7661. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7662. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7663. for (int i = 0; i < n_layer; ++i) {
  7664. auto & layer = model.layers[i];
  7665. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7666. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7667. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7668. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, 0);
  7669. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7670. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  7671. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7672. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  7673. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7674. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  7675. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7676. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0);
  7677. }
  7678. } break;
  7679. case LLM_ARCH_ORION:
  7680. {
  7681. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7682. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7683. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7684. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7685. for (int i = 0; i < n_layer; ++i) {
  7686. auto & layer = model.layers[i];
  7687. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7688. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7689. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7690. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7691. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7692. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7693. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7694. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  7695. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7696. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7697. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7698. }
  7699. } break;
  7700. case LLM_ARCH_INTERNLM2:
  7701. {
  7702. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7703. // output
  7704. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7705. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7706. for (int i = 0; i < n_layer; ++i) {
  7707. auto & layer = model.layers[i];
  7708. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7709. // layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7710. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7711. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7712. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7713. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7714. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7715. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7716. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7717. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7718. }
  7719. } break;
  7720. case LLM_ARCH_GEMMA:
  7721. {
  7722. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7723. // output
  7724. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7725. 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
  7726. for (int i = 0; i < n_layer; ++i) {
  7727. auto & layer = model.layers[i];
  7728. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7729. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head}, 0);
  7730. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  7731. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  7732. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd}, 0);
  7733. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7734. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7735. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7736. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7737. }
  7738. } break;
  7739. case LLM_ARCH_GEMMA2:
  7740. {
  7741. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7742. // output
  7743. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7744. 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
  7745. for (int i = 0; i < n_layer; ++i) {
  7746. auto & layer = model.layers[i];
  7747. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7748. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head}, 0);
  7749. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  7750. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  7751. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd}, 0);
  7752. layer.attn_post_norm = create_tensor(tn(LLM_TENSOR_ATTN_POST_NORM, "weight", i), {n_embd}, 0);
  7753. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7754. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7755. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7756. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7757. layer.ffn_post_norm = create_tensor(tn(LLM_TENSOR_FFN_POST_NORM, "weight", i), {n_embd}, 0);
  7758. }
  7759. } break;
  7760. case LLM_ARCH_STARCODER2:
  7761. {
  7762. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7763. // output
  7764. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7765. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7766. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7767. // if output is NULL, init from the input tok embed
  7768. if (model.output == NULL) {
  7769. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7770. }
  7771. for (int i = 0; i < n_layer; ++i) {
  7772. auto & layer = model.layers[i];
  7773. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7774. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7775. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7776. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7777. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7778. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7779. // optional bias tensors
  7780. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, 0);
  7781. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, 0);
  7782. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, 0);
  7783. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  7784. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7785. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  7786. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7787. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7788. // optional bias tensors
  7789. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  7790. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP , "bias", i), { n_ff}, 0);
  7791. }
  7792. } break;
  7793. case LLM_ARCH_MAMBA:
  7794. {
  7795. const int64_t d_conv = hparams.ssm_d_conv;
  7796. const int64_t d_inner = hparams.ssm_d_inner;
  7797. const int64_t d_state = hparams.ssm_d_state;
  7798. const int64_t dt_rank = hparams.ssm_dt_rank;
  7799. // only an expansion factor of 2 is supported for now
  7800. if (2 * n_embd != d_inner) {
  7801. throw std::runtime_error("only an expansion factor of 2 is supported for now");
  7802. }
  7803. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7804. // output
  7805. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7806. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7807. // if output is NULL, init from the input tok embed, duplicated to allow offloading
  7808. if (model.output == NULL) {
  7809. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7810. }
  7811. for (int i = 0; i < n_layer; ++i) {
  7812. auto & layer = model.layers[i];
  7813. // norm
  7814. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7815. layer.ssm_in = create_tensor(tn(LLM_TENSOR_SSM_IN, "weight", i), {n_embd, 2*d_inner}, 0);
  7816. layer.ssm_conv1d = create_tensor(tn(LLM_TENSOR_SSM_CONV1D, "weight", i), {d_conv, d_inner}, 0);
  7817. layer.ssm_conv1d_b = create_tensor(tn(LLM_TENSOR_SSM_CONV1D, "bias", i), {d_inner}, 0);
  7818. layer.ssm_x = create_tensor(tn(LLM_TENSOR_SSM_X, "weight", i), {d_inner, dt_rank + 2*d_state}, 0);
  7819. layer.ssm_dt = create_tensor(tn(LLM_TENSOR_SSM_DT, "weight", i), {dt_rank, d_inner}, 0);
  7820. layer.ssm_dt_b = create_tensor(tn(LLM_TENSOR_SSM_DT, "bias", i), {d_inner}, 0);
  7821. // no "weight" suffix for these
  7822. layer.ssm_a = create_tensor(tn(LLM_TENSOR_SSM_A, i), {d_state, d_inner}, 0);
  7823. layer.ssm_d = create_tensor(tn(LLM_TENSOR_SSM_D, i), {d_inner}, 0);
  7824. // out_proj
  7825. layer.ssm_out = create_tensor(tn(LLM_TENSOR_SSM_OUT, "weight", i), {d_inner, n_embd}, 0);
  7826. }
  7827. } break;
  7828. case LLM_ARCH_XVERSE:
  7829. {
  7830. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7831. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7832. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7833. for (int i = 0; i < n_layer; ++i) {
  7834. auto & layer = model.layers[i];
  7835. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7836. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7837. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7838. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7839. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7840. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7841. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7842. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7843. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7844. }
  7845. } break;
  7846. case LLM_ARCH_COMMAND_R:
  7847. {
  7848. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7849. // output
  7850. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7851. // init output from the input tok embed
  7852. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7853. for (int i = 0; i < n_layer; ++i) {
  7854. auto & layer = model.layers[i];
  7855. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7856. if (n_layer >= 64){
  7857. layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k, n_head}, 0);
  7858. layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k, n_head_kv}, 0);
  7859. }
  7860. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7861. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7862. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7863. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7864. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7865. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7866. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7867. }
  7868. } break;
  7869. case LLM_ARCH_OLMO: // adapted from LLM_ARCH_LLAMA with norm params removed
  7870. {
  7871. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7872. // output
  7873. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7874. // if output is NULL, init from the input tok embed
  7875. if (model.output == NULL) {
  7876. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7877. }
  7878. for (int i = 0; i < n_layer; ++i) {
  7879. auto & layer = model.layers[i];
  7880. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7881. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7882. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7883. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7884. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7885. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7886. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7887. }
  7888. } break;
  7889. case LLM_ARCH_OLMO2:
  7890. {
  7891. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7892. // output
  7893. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7894. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7895. for (int i = 0; i < n_layer; ++i) {
  7896. auto & layer = model.layers[i];
  7897. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7898. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7899. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7900. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7901. layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd}, 0);
  7902. layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd}, 0);
  7903. layer.attn_post_norm = create_tensor(tn(LLM_TENSOR_ATTN_POST_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_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7906. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7907. layer.ffn_post_norm = create_tensor(tn(LLM_TENSOR_FFN_POST_NORM, "weight", i), {n_embd}, 0);
  7908. }
  7909. } break;
  7910. case LLM_ARCH_OLMOE:
  7911. {
  7912. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7913. // output
  7914. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {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.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7920. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7921. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7922. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7923. layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd}, 0);
  7924. layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd}, 0);
  7925. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7926. layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0);
  7927. if (n_expert == 0) {
  7928. throw std::runtime_error("n_expert must be > 0");
  7929. }
  7930. if (n_expert_used == 0) {
  7931. throw std::runtime_error("n_expert_used must be > 0");
  7932. }
  7933. // MoE branch
  7934. layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, 0);
  7935. layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff, n_embd, n_expert}, 0);
  7936. layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert}, 0);
  7937. }
  7938. } break;
  7939. case LLM_ARCH_OPENELM:
  7940. {
  7941. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7942. // output
  7943. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7944. // init output from the input tok embed
  7945. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7946. for (int i = 0; i < n_layer; ++i) {
  7947. const int64_t n_head = hparams.n_head(i);
  7948. const int64_t n_head_qkv = 2*hparams.n_head_kv(i) + n_head;
  7949. const int64_t n_ff = hparams.n_ff(i);
  7950. auto & layer = model.layers[i];
  7951. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7952. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_head_qkv*n_embd_head_k}, 0);
  7953. layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k}, 0);
  7954. layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k}, 0);
  7955. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_head*n_embd_head_k, n_embd}, 0);
  7956. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7957. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7958. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7959. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7960. }
  7961. } break;
  7962. case LLM_ARCH_GPTNEOX:
  7963. {
  7964. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7965. // output
  7966. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7967. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7968. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7969. for (int i = 0; i < n_layer; ++i) {
  7970. auto & layer = model.layers[i];
  7971. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7972. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7973. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7974. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, 0);
  7975. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7976. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  7977. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7978. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  7979. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7980. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  7981. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7982. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0);
  7983. }
  7984. } break;
  7985. case LLM_ARCH_ARCTIC:
  7986. {
  7987. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7988. // output
  7989. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7990. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7991. // if output is NULL, init from the input tok embed
  7992. if (model.output == NULL) {
  7993. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7994. }
  7995. for (int i = 0; i < n_layer; ++i) {
  7996. auto & layer = model.layers[i];
  7997. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7998. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7999. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  8000. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  8001. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  8002. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  8003. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_embd}, 0);
  8004. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_embd, n_embd}, 0);
  8005. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_embd}, 0);
  8006. layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0);
  8007. layer.ffn_norm_exps = create_tensor(tn(LLM_TENSOR_FFN_NORM_EXPS, "weight", i), {n_embd}, 0);
  8008. layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, false);
  8009. layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert}, 0);
  8010. layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert}, 0);
  8011. }
  8012. } break;
  8013. case LLM_ARCH_DEEPSEEK2:
  8014. {
  8015. const bool is_lite = (hparams.n_layer == 27);
  8016. const int64_t n_embd_head_qk_rope = hparams.n_rot;
  8017. const int64_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  8018. const int64_t q_lora_rank = hparams.n_lora_q;
  8019. const int64_t kv_lora_rank = hparams.n_lora_kv;
  8020. const int64_t n_ff_exp = hparams.n_ff_exp;
  8021. const int64_t n_expert_shared = hparams.n_expert_shared;
  8022. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8023. // output
  8024. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8025. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  8026. for (int i = 0; i < n_layer; ++i) {
  8027. auto & layer = model.layers[i];
  8028. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  8029. if (!is_lite) {
  8030. layer.attn_q_a_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_A_NORM, "weight", i), {q_lora_rank}, 0);
  8031. }
  8032. layer.attn_kv_a_norm = create_tensor(tn(LLM_TENSOR_ATTN_KV_A_NORM, "weight", i), {kv_lora_rank}, 0);
  8033. if (!is_lite) {
  8034. layer.wq_a = create_tensor(tn(LLM_TENSOR_ATTN_Q_A, "weight", i), {n_embd, q_lora_rank}, 0);
  8035. layer.wq_b = create_tensor(tn(LLM_TENSOR_ATTN_Q_B, "weight", i), {q_lora_rank, n_head * n_embd_head_k}, 0);
  8036. } else {
  8037. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8038. }
  8039. 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);
  8040. 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);
  8041. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_head * ( n_embd_head_v), n_embd}, 0);
  8042. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  8043. if (i < (int) hparams.n_layer_dense_lead) {
  8044. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  8045. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  8046. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8047. } else {
  8048. layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0);
  8049. if (n_expert == 0) {
  8050. throw std::runtime_error("n_expert must be > 0");
  8051. }
  8052. if (n_expert_used == 0) {
  8053. throw std::runtime_error("n_expert_used must be > 0");
  8054. }
  8055. // MoE branch
  8056. layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert}, 0);
  8057. layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert}, 0);
  8058. layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert}, 0);
  8059. // Shared expert branch
  8060. layer.ffn_gate_shexp = create_tensor(tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), {n_embd, n_ff_exp * n_expert_shared}, 0);
  8061. layer.ffn_down_shexp = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), { n_ff_exp * n_expert_shared, n_embd}, 0);
  8062. layer.ffn_up_shexp = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), {n_embd, n_ff_exp * n_expert_shared}, 0);
  8063. }
  8064. }
  8065. } break;
  8066. case LLM_ARCH_BITNET:
  8067. {
  8068. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8069. // output
  8070. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8071. for (int i = 0; i < n_layer; ++i) {
  8072. auto & layer = model.layers[i];
  8073. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  8074. layer.attn_sub_norm = create_tensor(tn(LLM_TENSOR_ATTN_SUB_NORM, "weight", i), {n_embd}, 0);
  8075. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  8076. layer.wq_scale = create_tensor(tn(LLM_TENSOR_ATTN_Q, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8077. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  8078. layer.wk_scale = create_tensor(tn(LLM_TENSOR_ATTN_K, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8079. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  8080. layer.wv_scale = create_tensor(tn(LLM_TENSOR_ATTN_V, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8081. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  8082. layer.wo_scale = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8083. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  8084. layer.ffn_sub_norm = create_tensor(tn(LLM_TENSOR_FFN_SUB_NORM, "weight", i), {n_ff}, 0);
  8085. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  8086. layer.ffn_gate_scale = create_tensor(tn(LLM_TENSOR_FFN_GATE, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8087. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  8088. layer.ffn_down_scale = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8089. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8090. layer.ffn_up_scale = create_tensor(tn(LLM_TENSOR_FFN_UP, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8091. }
  8092. } break;
  8093. case LLM_ARCH_T5:
  8094. {
  8095. const auto n_rel_attn_bkts = hparams.n_rel_attn_bkts;
  8096. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8097. // output
  8098. model.output_norm_enc = create_tensor(tn(LLM_TENSOR_ENC_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8099. model.output_norm = create_tensor(tn(LLM_TENSOR_DEC_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8100. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8101. // if output is NULL, init from the input tok embed
  8102. if (model.output == NULL) {
  8103. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  8104. }
  8105. for (int i = 0; i < n_layer; ++i) {
  8106. auto & layer = model.layers[i];
  8107. layer.attn_norm_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_NORM, "weight", i), {n_embd}, 0);
  8108. 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);
  8109. layer.wq_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8110. layer.wk_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8111. layer.wv_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  8112. layer.wo_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd}, 0);
  8113. layer.ffn_norm_enc = create_tensor(tn(LLM_TENSOR_ENC_FFN_NORM, "weight", i), {n_embd}, 0);
  8114. layer.ffn_gate_enc = create_tensor(tn(LLM_TENSOR_ENC_FFN_GATE, "weight", i), {n_embd, n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8115. layer.ffn_down_enc = create_tensor(tn(LLM_TENSOR_ENC_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  8116. layer.ffn_up_enc = create_tensor(tn(LLM_TENSOR_ENC_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8117. layer.attn_norm = create_tensor(tn(LLM_TENSOR_DEC_ATTN_NORM, "weight", i), {n_embd}, 0);
  8118. 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);
  8119. layer.wq = create_tensor(tn(LLM_TENSOR_DEC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8120. layer.wk = create_tensor(tn(LLM_TENSOR_DEC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8121. layer.wv = create_tensor(tn(LLM_TENSOR_DEC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  8122. layer.wo = create_tensor(tn(LLM_TENSOR_DEC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd}, 0);
  8123. layer.attn_norm_cross = create_tensor(tn(LLM_TENSOR_DEC_CROSS_ATTN_NORM, "weight", i), {n_embd}, 0);
  8124. // this tensor seems to be unused in HF transformers implementation
  8125. 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);
  8126. layer.wq_cross = create_tensor(tn(LLM_TENSOR_DEC_CROSS_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8127. layer.wk_cross = create_tensor(tn(LLM_TENSOR_DEC_CROSS_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8128. layer.wv_cross = create_tensor(tn(LLM_TENSOR_DEC_CROSS_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  8129. layer.wo_cross = create_tensor(tn(LLM_TENSOR_DEC_CROSS_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd}, 0);
  8130. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_DEC_FFN_NORM, "weight", i), {n_embd}, 0);
  8131. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_DEC_FFN_GATE, "weight", i), {n_embd, n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8132. layer.ffn_down = create_tensor(tn(LLM_TENSOR_DEC_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  8133. layer.ffn_up = create_tensor(tn(LLM_TENSOR_DEC_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8134. }
  8135. } break;
  8136. case LLM_ARCH_T5ENCODER:
  8137. {
  8138. const auto n_rel_attn_bkts = hparams.n_rel_attn_bkts;
  8139. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8140. // output
  8141. model.output_norm_enc = create_tensor(tn(LLM_TENSOR_ENC_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8142. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8143. // if output is NULL, init from the input tok embed
  8144. if (model.output == NULL) {
  8145. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  8146. }
  8147. for (int i = 0; i < n_layer; ++i) {
  8148. auto & layer = model.layers[i];
  8149. layer.attn_norm_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_NORM, "weight", i), {n_embd}, 0);
  8150. 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);
  8151. layer.wq_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8152. layer.wk_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8153. layer.wv_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  8154. layer.wo_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd}, 0);
  8155. layer.ffn_norm_enc = create_tensor(tn(LLM_TENSOR_ENC_FFN_NORM, "weight", i), {n_embd}, 0);
  8156. layer.ffn_gate_enc = create_tensor(tn(LLM_TENSOR_ENC_FFN_GATE, "weight", i), {n_embd, n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8157. layer.ffn_down_enc = create_tensor(tn(LLM_TENSOR_ENC_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  8158. layer.ffn_up_enc = create_tensor(tn(LLM_TENSOR_ENC_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8159. }
  8160. } break;
  8161. case LLM_ARCH_JAIS:
  8162. {
  8163. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8164. // output
  8165. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8166. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  8167. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  8168. for (int i = 0; i < n_layer; ++i) {
  8169. auto & layer = model.layers[i];
  8170. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  8171. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  8172. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  8173. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, 0);
  8174. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  8175. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  8176. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  8177. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  8178. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  8179. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  8180. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  8181. layer.ffn_gate_b = create_tensor(tn(LLM_TENSOR_FFN_GATE, "bias", i), {n_ff}, 0);
  8182. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8183. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0);
  8184. }
  8185. } break;
  8186. case LLM_ARCH_CHATGLM:
  8187. {
  8188. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8189. // output
  8190. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8191. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  8192. for (int i = 0; i < n_layer; ++i) {
  8193. auto & layer = model.layers[i];
  8194. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  8195. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  8196. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, 0);
  8197. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  8198. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  8199. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff * 2}, 0);
  8200. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  8201. }
  8202. } break;
  8203. case LLM_ARCH_NEMOTRON:
  8204. {
  8205. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8206. // output
  8207. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8208. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  8209. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  8210. for (int i = 0; i < n_layer; ++i) {
  8211. auto & layer = model.layers[i];
  8212. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  8213. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  8214. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  8215. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  8216. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  8217. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  8218. // optional bias tensors
  8219. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8220. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8221. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8222. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8223. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  8224. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  8225. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  8226. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8227. // optional MLP bias
  8228. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8229. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8230. }
  8231. } break;
  8232. case LLM_ARCH_EXAONE:
  8233. {
  8234. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8235. // output
  8236. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8237. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  8238. for (int i = 0; i < n_layer; ++i) {
  8239. auto & layer = model.layers[i];
  8240. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  8241. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head}, 0);
  8242. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8243. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  8244. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd}, 0);
  8245. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  8246. 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));
  8247. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  8248. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  8249. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8250. }
  8251. } break;
  8252. case LLM_ARCH_RWKV6:
  8253. {
  8254. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8255. // Block 0, LN0
  8256. model.tok_norm = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd}, 0);
  8257. model.tok_norm_b = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd}, 0);
  8258. // output
  8259. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8260. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  8261. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  8262. const int time_mix_extra_dim = hparams.time_mix_extra_dim;
  8263. const int time_decay_extra_dim = hparams.time_decay_extra_dim;
  8264. const int head_size = hparams.wkv_head_size;
  8265. const int attn_hidden_size = n_embd;
  8266. const int ffn_size = hparams.n_ff_arr[0];
  8267. for (int i = 0; i < n_layer; ++i) {
  8268. auto & layer = model.layers[i];
  8269. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  8270. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  8271. layer.attn_norm_2 = create_tensor(tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd}, 0);
  8272. layer.attn_norm_2_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd}, 0);
  8273. layer.time_mix_w1 = create_tensor(tn(LLM_TENSOR_TIME_MIX_W1, "weight", i), {n_embd, time_mix_extra_dim * 5}, 0);
  8274. layer.time_mix_w2 = create_tensor(tn(LLM_TENSOR_TIME_MIX_W2, "weight", i), {time_mix_extra_dim, n_embd, 5}, 0);
  8275. layer.time_mix_lerp_x = create_tensor(tn(LLM_TENSOR_TIME_MIX_LERP_X, "weight", i), {n_embd, 1, 1}, 0);
  8276. layer.time_mix_lerp_w = create_tensor(tn(LLM_TENSOR_TIME_MIX_LERP_W, "weight", i), {n_embd, 1, 1}, 0);
  8277. layer.time_mix_lerp_k = create_tensor(tn(LLM_TENSOR_TIME_MIX_LERP_K, "weight", i), {n_embd, 1, 1}, 0);
  8278. layer.time_mix_lerp_v = create_tensor(tn(LLM_TENSOR_TIME_MIX_LERP_V, "weight", i), {n_embd, 1, 1}, 0);
  8279. layer.time_mix_lerp_r = create_tensor(tn(LLM_TENSOR_TIME_MIX_LERP_R, "weight", i), {n_embd, 1, 1}, 0);
  8280. layer.time_mix_lerp_g = create_tensor(tn(LLM_TENSOR_TIME_MIX_LERP_G, "weight", i), {n_embd, 1, 1}, 0);
  8281. layer.time_mix_first = create_tensor(tn(LLM_TENSOR_TIME_MIX_FIRST, "weight", i), {head_size, n_embd / head_size}, 0);
  8282. layer.time_mix_decay = create_tensor(tn(LLM_TENSOR_TIME_MIX_DECAY, "weight", i), {n_embd}, 0);
  8283. layer.time_mix_decay_w1 = create_tensor(tn(LLM_TENSOR_TIME_MIX_DECAY_W1, "weight", i), {n_embd, time_decay_extra_dim}, 0);
  8284. layer.time_mix_decay_w2 = create_tensor(tn(LLM_TENSOR_TIME_MIX_DECAY_W2, "weight", i), {time_decay_extra_dim, attn_hidden_size}, 0);
  8285. layer.time_mix_key = create_tensor(tn(LLM_TENSOR_TIME_MIX_KEY, "weight", i), {attn_hidden_size, n_embd}, 0);
  8286. layer.time_mix_value = create_tensor(tn(LLM_TENSOR_TIME_MIX_VALUE, "weight", i), {attn_hidden_size, n_embd}, 0);
  8287. layer.time_mix_receptance = create_tensor(tn(LLM_TENSOR_TIME_MIX_RECEPTANCE, "weight", i), {attn_hidden_size, n_embd}, 0);
  8288. layer.time_mix_gate = create_tensor(tn(LLM_TENSOR_TIME_MIX_GATE, "weight", i), {attn_hidden_size, n_embd}, 0);
  8289. layer.time_mix_ln = create_tensor(tn(LLM_TENSOR_TIME_MIX_LN, "weight", i), {n_embd}, 0);
  8290. layer.time_mix_ln_b = create_tensor(tn(LLM_TENSOR_TIME_MIX_LN, "bias", i), {n_embd}, 0);
  8291. layer.time_mix_output = create_tensor(tn(LLM_TENSOR_TIME_MIX_OUTPUT, "weight", i), {n_embd, attn_hidden_size}, 0);
  8292. layer.channel_mix_lerp_k = create_tensor(tn(LLM_TENSOR_CHANNEL_MIX_LERP_K, "weight", i), {n_embd, 1, 1}, 0);
  8293. layer.channel_mix_lerp_r = create_tensor(tn(LLM_TENSOR_CHANNEL_MIX_LERP_R, "weight", i), {n_embd, 1, 1}, 0);
  8294. layer.channel_mix_key = create_tensor(tn(LLM_TENSOR_CHANNEL_MIX_KEY, "weight", i), {n_embd, ffn_size}, 0);
  8295. layer.channel_mix_value = create_tensor(tn(LLM_TENSOR_CHANNEL_MIX_VALUE, "weight", i), {ffn_size, n_embd}, 0);
  8296. layer.channel_mix_receptance = create_tensor(tn(LLM_TENSOR_CHANNEL_MIX_RECEPTANCE, "weight", i), {n_embd, n_embd}, 0);
  8297. }
  8298. } break;
  8299. case LLM_ARCH_CHAMELEON:
  8300. {
  8301. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8302. // output
  8303. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8304. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8305. // if output is NULL, init from the input tok embed
  8306. if (model.output == NULL) {
  8307. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  8308. }
  8309. for (int i = 0; i < n_layer; ++i) {
  8310. auto & layer = model.layers[i];
  8311. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  8312. layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k, n_head}, 0);
  8313. layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k, n_head_kv}, 0);
  8314. 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);
  8315. 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);
  8316. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  8317. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  8318. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  8319. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  8320. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  8321. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  8322. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  8323. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8324. }
  8325. } break;
  8326. case LLM_ARCH_SOLAR:
  8327. {
  8328. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8329. // output
  8330. {
  8331. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8332. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8333. }
  8334. for (int i = 0; i < n_layer; ++i) {
  8335. auto & layer = model.layers[i];
  8336. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  8337. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head}, 0);
  8338. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8339. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  8340. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd}, 0);
  8341. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  8342. 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));
  8343. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  8344. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  8345. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8346. }
  8347. } break;
  8348. default:
  8349. throw std::runtime_error("unknown architecture");
  8350. }
  8351. if (n_moved_tensors > 0) {
  8352. LLAMA_LOG_DEBUG("%s: tensor '%s' (%s) (and %d others) cannot be used with preferred buffer type %s, using %s instead\n",
  8353. __func__, first_moved_tensor->name, ggml_type_name(first_moved_tensor->type), n_moved_tensors - 1,
  8354. ggml_backend_buft_name(first_moved_from_buft), ggml_backend_buft_name(first_moved_to_buft));
  8355. }
  8356. }
  8357. ml.done_getting_tensors();
  8358. ml.init_mappings(true, use_mlock ? &model.mlock_mmaps : nullptr);
  8359. model.mappings.reserve(ml.mappings.size());
  8360. // create the backend buffers
  8361. std::vector<std::pair<ggml_context *, llama_buf_map>> ctx_bufs;
  8362. ctx_bufs.reserve(ctx_map.size());
  8363. // Ensure we have enough capacity for the maximum backend buffer we will potentially create
  8364. const size_t n_max_backend_buffer = ctx_map.size() * ml.files.size();
  8365. model.bufs.reserve(n_max_backend_buffer);
  8366. for (auto & it : ctx_map) {
  8367. ggml_backend_buffer_type_t buft = it.first;
  8368. ggml_context * ctx = it.second;
  8369. // skip contexts without tensors
  8370. if (ggml_get_first_tensor(ctx) == nullptr) {
  8371. continue;
  8372. }
  8373. llama_buf_map bufs;
  8374. bufs.reserve(n_max_backend_buffer);
  8375. // check if it is possible to use buffer_from_host_ptr with this buffer type
  8376. ggml_backend_dev_t dev = ggml_backend_buft_get_device(buft);
  8377. if (!dev) {
  8378. // FIXME: workaround for CPU backend buft having a NULL device
  8379. dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
  8380. }
  8381. ggml_backend_dev_props props;
  8382. ggml_backend_dev_get_props(dev, &props);
  8383. bool buffer_from_host_ptr_supported = props.caps.buffer_from_host_ptr;
  8384. bool is_default_buft = buft == ggml_backend_dev_buffer_type(dev);
  8385. if (ml.use_mmap && use_mmap_buffer && buffer_from_host_ptr_supported && is_default_buft) {
  8386. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  8387. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  8388. // 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
  8389. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  8390. void * addr = nullptr;
  8391. size_t first, last; // NOLINT
  8392. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  8393. if (first >= last) {
  8394. continue;
  8395. }
  8396. const size_t max_size = ggml_get_max_tensor_size(ctx);
  8397. ggml_backend_buffer_t buf = ggml_backend_dev_buffer_from_host_ptr(dev, (char *) addr + first, last - first, max_size);
  8398. if (buf == nullptr) {
  8399. throw std::runtime_error(format("unable to allocate %s buffer", ggml_backend_buft_name(buft)));
  8400. }
  8401. model.bufs.emplace_back(buf);
  8402. bufs.emplace(idx, buf);
  8403. }
  8404. }
  8405. else {
  8406. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  8407. if (buf == nullptr) {
  8408. throw std::runtime_error(format("unable to allocate %s buffer", ggml_backend_buft_name(buft)));
  8409. }
  8410. model.bufs.emplace_back(buf);
  8411. if (use_mlock && ggml_backend_buffer_is_host(buf)) {
  8412. model.mlock_bufs.emplace_back(new llama_mlock);
  8413. auto & mlock_buf = model.mlock_bufs.back();
  8414. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  8415. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  8416. }
  8417. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  8418. bufs.emplace(idx, buf);
  8419. }
  8420. }
  8421. if (bufs.empty()) {
  8422. throw std::runtime_error("failed to allocate buffer");
  8423. }
  8424. for (auto & buf : bufs) {
  8425. // indicate that this buffer contains weights
  8426. // 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
  8427. ggml_backend_buffer_set_usage(buf.second, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  8428. }
  8429. ctx_bufs.emplace_back(ctx, bufs);
  8430. }
  8431. if (llama_supports_gpu_offload()) {
  8432. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  8433. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  8434. if (n_gpu_layers > (int) hparams.n_layer) {
  8435. LLAMA_LOG_INFO("%s: offloading output layer to GPU\n", __func__);
  8436. }
  8437. const int max_backend_supported_layers = hparams.n_layer + 1;
  8438. const int max_offloadable_layers = hparams.n_layer + 1;
  8439. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  8440. }
  8441. // print memory requirements per buffer type
  8442. for (auto & buf : model.bufs) {
  8443. 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);
  8444. }
  8445. // populate tensors_by_name
  8446. for (auto & ctx : model.ctxs) {
  8447. for (auto * cur = ggml_get_first_tensor(ctx.get()); cur != NULL; cur = ggml_get_next_tensor(ctx.get(), cur)) {
  8448. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  8449. }
  8450. }
  8451. // load tensor data
  8452. for (auto & it : ctx_bufs) {
  8453. ggml_context * ctx = it.first;
  8454. auto & bufs = it.second;
  8455. if (!ml.load_all_data(ctx, bufs, use_mlock ? &model.mlock_mmaps : NULL, progress_callback, progress_callback_user_data)) {
  8456. return false;
  8457. }
  8458. }
  8459. if (use_mmap_buffer) {
  8460. for (auto & mapping : ml.mappings) {
  8461. model.mappings.emplace_back(std::move(mapping));
  8462. }
  8463. }
  8464. return true;
  8465. }
  8466. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  8467. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  8468. model.t_start_us = ggml_time_us();
  8469. try {
  8470. llama_model_loader ml(fname, params.use_mmap, params.check_tensors, params.kv_overrides);
  8471. model.hparams.vocab_only = params.vocab_only;
  8472. try {
  8473. llm_load_arch(ml, model);
  8474. } catch(const std::exception & e) {
  8475. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  8476. }
  8477. try {
  8478. llm_load_hparams(ml, model);
  8479. } catch(const std::exception & e) {
  8480. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  8481. }
  8482. try {
  8483. llm_load_vocab(ml, model);
  8484. } catch(const std::exception & e) {
  8485. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  8486. }
  8487. llm_load_stats(ml, model);
  8488. llm_load_print_meta(ml, model);
  8489. if (model.vocab.type != LLAMA_VOCAB_TYPE_NONE &&
  8490. model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  8491. LLAMA_LOG_WARN("%s: vocab mismatch %u !- %zu ...\n", __func__, model.hparams.n_vocab, model.vocab.id_to_token.size());
  8492. }
  8493. if (params.vocab_only) {
  8494. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  8495. return 0;
  8496. }
  8497. if (!llm_load_tensors(
  8498. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  8499. params.progress_callback, params.progress_callback_user_data
  8500. )) {
  8501. return -2;
  8502. }
  8503. } catch (const std::exception & err) {
  8504. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  8505. return -1;
  8506. }
  8507. // loading time will be recalculate after the first eval, so
  8508. // we take page faults deferred by mmap() into consideration
  8509. model.t_load_us = ggml_time_us() - model.t_start_us;
  8510. return 0;
  8511. }
  8512. //
  8513. // llm_build
  8514. //
  8515. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  8516. enum llm_ffn_op_type {
  8517. LLM_FFN_SILU,
  8518. LLM_FFN_GELU,
  8519. LLM_FFN_RELU,
  8520. LLM_FFN_RELU_SQR,
  8521. LLM_FFN_SWIGLU,
  8522. };
  8523. enum llm_ffn_gate_type {
  8524. LLM_FFN_SEQ,
  8525. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  8526. };
  8527. enum llm_norm_type {
  8528. LLM_NORM,
  8529. LLM_NORM_RMS,
  8530. };
  8531. static struct ggml_tensor * llm_build_inp_embd(
  8532. struct ggml_context * ctx,
  8533. struct llama_context & lctx,
  8534. const llama_hparams & hparams,
  8535. const llama_ubatch & batch,
  8536. struct ggml_tensor * tok_embd,
  8537. const llm_build_cb & cb) {
  8538. const int64_t n_embd = hparams.n_embd;
  8539. struct ggml_tensor * inpL;
  8540. if (batch.token) {
  8541. lctx.inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  8542. cb(lctx.inp_tokens, "inp_tokens", -1);
  8543. ggml_set_input(lctx.inp_tokens);
  8544. inpL = ggml_get_rows(ctx, tok_embd, lctx.inp_tokens);
  8545. } else {
  8546. lctx.inp_embd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  8547. inpL = lctx.inp_embd;
  8548. ggml_set_input(lctx.inp_embd);
  8549. }
  8550. // For Granite architecture
  8551. if (hparams.f_embedding_scale != 0.0f) {
  8552. inpL = ggml_scale(ctx, inpL, hparams.f_embedding_scale);
  8553. }
  8554. cb(inpL, "inp_embd", -1);
  8555. return inpL;
  8556. }
  8557. static struct ggml_tensor * llm_build_inp_cross_attn_state(
  8558. struct ggml_context * ctx,
  8559. struct llama_context & lctx,
  8560. const llama_hparams & hparams,
  8561. const llm_build_cb & cb) {
  8562. const int64_t n_embd = hparams.n_embd;
  8563. struct ggml_tensor * inpCAS = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n_embd, 1601, 4);
  8564. cb(inpCAS, "inp_cross_attn_state", -1);
  8565. ggml_set_input(inpCAS);
  8566. lctx.inp_cross_attn_state = inpCAS;
  8567. return inpCAS;
  8568. }
  8569. static void llm_build_kv_store(
  8570. struct ggml_context * ctx,
  8571. const llama_hparams & hparams,
  8572. const llama_cparams & cparams,
  8573. const llama_kv_cache & kv,
  8574. struct ggml_cgraph * graph,
  8575. struct ggml_tensor * k_cur,
  8576. struct ggml_tensor * v_cur,
  8577. int32_t n_tokens,
  8578. int32_t kv_head,
  8579. const llm_build_cb & cb,
  8580. int64_t il) {
  8581. const int64_t n_ctx = cparams.n_ctx;
  8582. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  8583. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  8584. GGML_ASSERT(kv.size == n_ctx);
  8585. 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);
  8586. cb(k_cache_view, "k_cache_view", il);
  8587. // note: storing RoPE-ed version of K in the KV cache
  8588. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  8589. assert(v_cur->ne[0] == n_embd_v_gqa && v_cur->ne[1] == n_tokens);
  8590. struct ggml_tensor * v_cache_view = nullptr;
  8591. if (cparams.flash_attn) {
  8592. 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);
  8593. } else {
  8594. // note: the V cache is transposed when not using flash attention
  8595. v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  8596. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  8597. (kv_head)*ggml_element_size(kv.v_l[il]));
  8598. v_cur = ggml_transpose(ctx, v_cur);
  8599. }
  8600. cb(v_cache_view, "v_cache_view", il);
  8601. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur, v_cache_view));
  8602. }
  8603. // do mat_mul, while optionally apply lora
  8604. static struct ggml_tensor * llm_build_lora_mm(
  8605. struct llama_context & lctx,
  8606. struct ggml_context * ctx0,
  8607. struct ggml_tensor * w,
  8608. struct ggml_tensor * cur) {
  8609. struct ggml_tensor * res = ggml_mul_mat(ctx0, w, cur);
  8610. for (auto & it : lctx.lora_adapters) {
  8611. struct llama_lora_weight * lora = it.first->get_weight(w);
  8612. if (lora == nullptr) {
  8613. continue;
  8614. }
  8615. const float alpha = it.first->alpha;
  8616. const float rank = (float) lora->b->ne[0];
  8617. const float scale = alpha ? it.second * alpha / rank : it.second;
  8618. struct ggml_tensor * ab_cur = ggml_mul_mat(
  8619. ctx0, lora->b,
  8620. ggml_mul_mat(ctx0, lora->a, cur)
  8621. );
  8622. ab_cur = ggml_scale(ctx0, ab_cur, scale);
  8623. res = ggml_add(ctx0, res, ab_cur);
  8624. }
  8625. return res;
  8626. }
  8627. // do mat_mul_id, while optionally apply lora
  8628. static struct ggml_tensor * llm_build_lora_mm_id(
  8629. struct llama_context & lctx,
  8630. struct ggml_context * ctx0,
  8631. struct ggml_tensor * w, // struct ggml_tensor * as
  8632. struct ggml_tensor * cur, // struct ggml_tensor * b
  8633. struct ggml_tensor * ids) {
  8634. struct ggml_tensor * res = ggml_mul_mat_id(ctx0, w, cur, ids);
  8635. for (auto & it : lctx.lora_adapters) {
  8636. struct llama_lora_weight * lora = it.first->get_weight(w);
  8637. if (lora == nullptr) {
  8638. continue;
  8639. }
  8640. const float alpha = it.first->alpha;
  8641. const float rank = (float) lora->b->ne[0];
  8642. const float scale = alpha ? it.second * alpha / rank : it.second;
  8643. struct ggml_tensor * ab_cur = ggml_mul_mat_id(
  8644. ctx0, lora->b,
  8645. ggml_mul_mat_id(ctx0, lora->a, cur, ids),
  8646. ids
  8647. );
  8648. ab_cur = ggml_scale(ctx0, ab_cur, scale);
  8649. res = ggml_add(ctx0, res, ab_cur);
  8650. }
  8651. return res;
  8652. }
  8653. static struct ggml_tensor * llm_build_norm(
  8654. struct ggml_context * ctx,
  8655. struct ggml_tensor * cur,
  8656. const llama_hparams & hparams,
  8657. struct ggml_tensor * mw,
  8658. struct ggml_tensor * mb,
  8659. llm_norm_type type,
  8660. const llm_build_cb & cb,
  8661. int il) {
  8662. switch (type) {
  8663. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  8664. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  8665. }
  8666. if (mw || mb) {
  8667. cb(cur, "norm", il);
  8668. }
  8669. if (mw) {
  8670. cur = ggml_mul(ctx, cur, mw);
  8671. if (mb) {
  8672. cb(cur, "norm_w", il);
  8673. }
  8674. }
  8675. if (mb) {
  8676. cur = ggml_add(ctx, cur, mb);
  8677. }
  8678. return cur;
  8679. }
  8680. static struct ggml_tensor * llm_build_ffn(
  8681. struct ggml_context * ctx,
  8682. struct llama_context & lctx,
  8683. struct ggml_tensor * cur,
  8684. struct ggml_tensor * up,
  8685. struct ggml_tensor * up_b,
  8686. struct ggml_tensor * up_s,
  8687. struct ggml_tensor * gate,
  8688. struct ggml_tensor * gate_b,
  8689. struct ggml_tensor * gate_s,
  8690. struct ggml_tensor * down,
  8691. struct ggml_tensor * down_b,
  8692. struct ggml_tensor * down_s,
  8693. struct ggml_tensor * act_scales,
  8694. llm_ffn_op_type type_op,
  8695. llm_ffn_gate_type type_gate,
  8696. const llm_build_cb & cb,
  8697. int il) {
  8698. struct ggml_tensor * tmp = up ? llm_build_lora_mm(lctx, ctx, up, cur) : cur;
  8699. cb(tmp, "ffn_up", il);
  8700. if (up_b) {
  8701. tmp = ggml_add(ctx, tmp, up_b);
  8702. cb(tmp, "ffn_up_b", il);
  8703. }
  8704. if (up_s) {
  8705. tmp = ggml_mul(ctx, tmp, up_s);
  8706. cb(tmp, "ffn_up_s", il);
  8707. }
  8708. if (gate) {
  8709. switch (type_gate) {
  8710. case LLM_FFN_SEQ:
  8711. {
  8712. cur = llm_build_lora_mm(lctx, ctx, gate, tmp);
  8713. cb(cur, "ffn_gate", il);
  8714. } break;
  8715. case LLM_FFN_PAR:
  8716. {
  8717. cur = llm_build_lora_mm(lctx, ctx, gate, cur);
  8718. cb(cur, "ffn_gate", il);
  8719. } break;
  8720. }
  8721. if (gate_b) {
  8722. cur = ggml_add(ctx, cur, gate_b);
  8723. cb(cur, "ffn_gate_b", il);
  8724. }
  8725. if (gate_s) {
  8726. cur = ggml_mul(ctx, cur, gate_s);
  8727. cb(cur, "ffn_gate_s", il);
  8728. }
  8729. } else {
  8730. cur = tmp;
  8731. }
  8732. switch (type_op) {
  8733. case LLM_FFN_SILU:
  8734. {
  8735. cur = ggml_silu(ctx, cur);
  8736. cb(cur, "ffn_silu", il);
  8737. } break;
  8738. case LLM_FFN_GELU:
  8739. {
  8740. cur = ggml_gelu(ctx, cur);
  8741. cb(cur, "ffn_gelu", il);
  8742. if (act_scales != NULL) {
  8743. cur = ggml_div(ctx, cur, act_scales);
  8744. cb(cur, "ffn_act", il);
  8745. }
  8746. } break;
  8747. case LLM_FFN_RELU:
  8748. {
  8749. cur = ggml_relu(ctx, cur);
  8750. cb(cur, "ffn_relu", il);
  8751. } break;
  8752. case LLM_FFN_RELU_SQR:
  8753. {
  8754. cur = ggml_relu(ctx, cur);
  8755. cb(cur, "ffn_relu", il);
  8756. cur = ggml_sqr(ctx, cur);
  8757. cb(cur, "ffn_sqr(relu)", il);
  8758. } break;
  8759. case LLM_FFN_SWIGLU:
  8760. {
  8761. // Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf
  8762. int64_t split_point = cur->ne[0] / 2;
  8763. struct ggml_tensor * x0 = ggml_cont(ctx, ggml_view_2d(ctx, cur, split_point, cur->ne[1], cur->nb[1], 0));
  8764. 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)));
  8765. x0 = ggml_silu(ctx, x0);
  8766. cb(cur, "ffn_silu", il);
  8767. cur = ggml_mul(ctx, x0, x1);
  8768. cb(cur, "ffn_mul", il);
  8769. } break;
  8770. }
  8771. if (type_gate == LLM_FFN_PAR) {
  8772. cur = ggml_mul(ctx, cur, tmp);
  8773. cb(cur, "ffn_gate_par", il);
  8774. }
  8775. if (down) {
  8776. cur = llm_build_lora_mm(lctx, ctx, down, cur);
  8777. }
  8778. if (down_b) {
  8779. cb(cur, "ffn_down", il);
  8780. }
  8781. if (down_b) {
  8782. cur = ggml_add(ctx, cur, down_b);
  8783. }
  8784. if (down_s) {
  8785. cur = ggml_mul(ctx, cur, down_s);
  8786. cb(cur, "ffn_down_s", il);
  8787. }
  8788. return cur;
  8789. }
  8790. static struct ggml_tensor * llm_build_moe_ffn(
  8791. struct ggml_context * ctx,
  8792. struct llama_context & lctx,
  8793. struct ggml_tensor * cur,
  8794. struct ggml_tensor * gate_inp,
  8795. struct ggml_tensor * up_exps,
  8796. struct ggml_tensor * gate_exps,
  8797. struct ggml_tensor * down_exps,
  8798. int64_t n_expert,
  8799. int64_t n_expert_used,
  8800. llm_ffn_op_type type_op,
  8801. bool norm_w,
  8802. bool scale_w,
  8803. float w_scale,
  8804. const llm_build_cb & cb,
  8805. int il) {
  8806. int64_t n_embd = cur->ne[0];
  8807. int64_t n_tokens = cur->ne[1];
  8808. ggml_tensor * logits = llm_build_lora_mm(lctx, ctx, gate_inp, cur); // [n_expert, n_tokens]
  8809. cb(logits, "ffn_moe_logits", il);
  8810. ggml_tensor * probs = ggml_soft_max(ctx, logits); // [n_expert, n_tokens]
  8811. cb(probs, "ffn_moe_probs", il);
  8812. // select experts
  8813. ggml_tensor * selected_experts = ggml_top_k(ctx, probs, n_expert_used); // [n_expert_used, n_tokens]
  8814. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  8815. cb(selected_experts, "ffn_moe_topk", il);
  8816. ggml_tensor * weights = ggml_get_rows(ctx,
  8817. ggml_reshape_3d(ctx, probs, 1, n_expert, n_tokens), selected_experts); // [1, n_expert_used, n_tokens]
  8818. cb(weights, "ffn_moe_weights", il);
  8819. if (norm_w) {
  8820. weights = ggml_reshape_2d(ctx, weights, n_expert_used, n_tokens);
  8821. ggml_tensor * weights_sum = ggml_sum_rows(ctx, weights); // [1, n_tokens]
  8822. cb(weights_sum, "ffn_moe_weights_sum", il);
  8823. weights = ggml_div(ctx, weights, weights_sum); // [n_expert_used, n_tokens]
  8824. cb(weights, "ffn_moe_weights_norm", il);
  8825. weights = ggml_reshape_3d(ctx, weights, 1, n_expert_used, n_tokens);
  8826. }
  8827. if (scale_w) {
  8828. weights = ggml_scale(ctx, weights, w_scale);
  8829. cb(weights, "ffn_moe_weights_scaled", il);
  8830. }
  8831. cur = ggml_reshape_3d(ctx, cur, n_embd, 1, n_tokens);
  8832. ggml_tensor * up = llm_build_lora_mm_id(lctx, ctx, up_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  8833. cb(up, "ffn_moe_up", il);
  8834. ggml_tensor * gate = llm_build_lora_mm_id(lctx, ctx, gate_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  8835. cb(gate, "ffn_moe_gate", il);
  8836. switch (type_op) {
  8837. case LLM_FFN_SILU:
  8838. {
  8839. gate = ggml_silu(ctx, gate);
  8840. cb(gate, "ffn_moe_silu", il);
  8841. } break;
  8842. case LLM_FFN_GELU:
  8843. {
  8844. gate = ggml_gelu(ctx, gate);
  8845. cb(gate, "ffn_moe_gelu", il);
  8846. } break;
  8847. default:
  8848. GGML_ABORT("fatal error");
  8849. }
  8850. ggml_tensor * par = ggml_mul(ctx, up, gate); // [n_ff, n_expert_used, n_tokens]
  8851. cb(par, "ffn_moe_gate_par", il);
  8852. ggml_tensor * experts = llm_build_lora_mm_id(lctx, ctx, down_exps, par, selected_experts); // [n_embd, n_expert_used, n_tokens]
  8853. cb(experts, "ffn_moe_down", il);
  8854. experts = ggml_mul(ctx, experts, weights);
  8855. // aggregate experts
  8856. ggml_tensor * moe_out = nullptr;
  8857. for (int i = 0; i < n_expert_used; ++i) {
  8858. ggml_tensor * cur_expert = ggml_view_2d(ctx, experts, n_embd, n_tokens,
  8859. experts->nb[2], i*experts->nb[1]);
  8860. if (i == 0) {
  8861. moe_out = cur_expert;
  8862. } else {
  8863. moe_out = ggml_add(ctx, moe_out, cur_expert);
  8864. }
  8865. }
  8866. if (n_expert_used == 1) {
  8867. // avoid returning a non-contiguous tensor
  8868. moe_out = ggml_cont(ctx, moe_out);
  8869. }
  8870. return moe_out;
  8871. }
  8872. static struct ggml_tensor * llm_build_kqv(
  8873. struct ggml_context * ctx,
  8874. struct llama_context & lctx,
  8875. const llama_kv_cache & kv,
  8876. struct ggml_cgraph * graph,
  8877. struct ggml_tensor * wo,
  8878. struct ggml_tensor * wo_b,
  8879. struct ggml_tensor * q_cur,
  8880. struct ggml_tensor * kq_mask,
  8881. int32_t n_tokens,
  8882. int32_t n_kv,
  8883. float kq_scale,
  8884. const llm_build_cb & cb,
  8885. int il) {
  8886. const llama_model & model = lctx.model;
  8887. const llama_hparams & hparams = lctx.model.hparams;
  8888. const llama_cparams & cparams = lctx.cparams;
  8889. const int64_t n_ctx = cparams.n_ctx;
  8890. const int64_t n_head = hparams.n_head(il);
  8891. const int64_t n_head_kv = hparams.n_head_kv(il);
  8892. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  8893. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  8894. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  8895. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  8896. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  8897. cb(q, "q", il);
  8898. struct ggml_tensor * k =
  8899. ggml_view_3d(ctx, kv.k_l[il],
  8900. n_embd_head_k, n_kv, n_head_kv,
  8901. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  8902. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  8903. 0);
  8904. cb(k, "k", il);
  8905. struct ggml_tensor * cur;
  8906. if (cparams.flash_attn) {
  8907. GGML_UNUSED(model);
  8908. GGML_UNUSED(n_ctx);
  8909. // split cached v into n_head heads (not transposed)
  8910. struct ggml_tensor * v =
  8911. ggml_view_3d(ctx, kv.v_l[il],
  8912. n_embd_head_v, n_kv, n_head_kv,
  8913. ggml_row_size(kv.v_l[il]->type, n_embd_v_gqa),
  8914. ggml_row_size(kv.v_l[il]->type, n_embd_head_v),
  8915. 0);
  8916. cb(v, "v", il);
  8917. cur = ggml_flash_attn_ext(ctx, q, k, v, kq_mask, kq_scale, hparams.f_max_alibi_bias,
  8918. hparams.attn_soft_cap ? hparams.f_attn_logit_softcapping : 0.0f);
  8919. ggml_flash_attn_ext_set_prec(cur, GGML_PREC_F32);
  8920. cur = ggml_reshape_2d(ctx, cur, n_embd_head_v*n_head, n_tokens);
  8921. } else {
  8922. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  8923. cb(kq, "kq", il);
  8924. // note: this op tends to require high floating point range
  8925. // while for some models F16 is enough, for others it is not, so we default to F32 here
  8926. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  8927. if (model.arch == LLM_ARCH_GROK) {
  8928. // need to do the following:
  8929. // multiply by attn_output_multiplyer of 0.08838834764831845
  8930. // and then :
  8931. // kq = 30 * tanh(kq / 30)
  8932. // before the softmax below
  8933. kq = ggml_tanh(ctx, ggml_scale(ctx, kq, 0.08838834764831845f/30.0f));
  8934. kq = ggml_scale(ctx, kq, 30);
  8935. }
  8936. if (hparams.attn_soft_cap) {
  8937. kq = ggml_scale(ctx, kq, 1.0f / hparams.f_attn_logit_softcapping);
  8938. kq = ggml_tanh(ctx, kq);
  8939. kq = ggml_scale(ctx, kq, hparams.f_attn_logit_softcapping);
  8940. }
  8941. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_scale, hparams.f_max_alibi_bias);
  8942. cb(kq, "kq_soft_max_ext", il);
  8943. GGML_ASSERT(kv.size == n_ctx);
  8944. // split cached v into n_head heads
  8945. struct ggml_tensor * v =
  8946. ggml_view_3d(ctx, kv.v_l[il],
  8947. n_kv, n_embd_head_v, n_head_kv,
  8948. ggml_element_size(kv.v_l[il])*n_ctx,
  8949. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  8950. 0);
  8951. cb(v, "v", il);
  8952. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  8953. cb(kqv, "kqv", il);
  8954. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  8955. cb(kqv_merged, "kqv_merged", il);
  8956. cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_v*n_head, n_tokens);
  8957. cb(cur, "kqv_merged_cont", il);
  8958. }
  8959. ggml_build_forward_expand(graph, cur);
  8960. if (wo) {
  8961. cur = llm_build_lora_mm(lctx, ctx, wo, cur);
  8962. }
  8963. if (wo_b) {
  8964. cb(cur, "kqv_wo", il);
  8965. }
  8966. if (wo_b) {
  8967. cur = ggml_add(ctx, cur, wo_b);
  8968. }
  8969. return cur;
  8970. }
  8971. static struct ggml_tensor * llm_build_kv(
  8972. struct ggml_context * ctx,
  8973. struct llama_context & lctx,
  8974. const llama_kv_cache & kv,
  8975. struct ggml_cgraph * graph,
  8976. struct ggml_tensor * wo,
  8977. struct ggml_tensor * wo_b,
  8978. struct ggml_tensor * k_cur,
  8979. struct ggml_tensor * v_cur,
  8980. struct ggml_tensor * q_cur,
  8981. struct ggml_tensor * kq_mask,
  8982. int32_t n_tokens,
  8983. int32_t kv_head,
  8984. int32_t n_kv,
  8985. float kq_scale,
  8986. const llm_build_cb & cb,
  8987. int il) {
  8988. const llama_hparams & hparams = lctx.model.hparams;
  8989. const llama_cparams & cparams = lctx.cparams;
  8990. // these nodes are added to the graph together so that they are not reordered
  8991. // by doing so, the number of splits in the graph is reduced
  8992. ggml_build_forward_expand(graph, q_cur);
  8993. ggml_build_forward_expand(graph, k_cur);
  8994. ggml_build_forward_expand(graph, v_cur);
  8995. llm_build_kv_store(ctx, hparams, cparams, kv, graph, k_cur, v_cur, n_tokens, kv_head, cb, il);
  8996. struct ggml_tensor * cur;
  8997. cur = llm_build_kqv(ctx, lctx, kv, graph, wo, wo_b, q_cur, kq_mask, n_tokens, n_kv, kq_scale, cb, il);
  8998. cb(cur, "kqv_out", il);
  8999. return cur;
  9000. }
  9001. static struct ggml_tensor * llm_build_copy_mask_state(
  9002. struct ggml_context * ctx,
  9003. struct ggml_cgraph * graph,
  9004. struct ggml_tensor * s,
  9005. struct ggml_tensor * state_copy,
  9006. struct ggml_tensor * state_mask,
  9007. int32_t n_state,
  9008. int32_t kv_size,
  9009. int32_t kv_head,
  9010. int32_t n_kv,
  9011. int32_t n_seqs) {
  9012. struct ggml_tensor * states = ggml_reshape_2d(ctx, s, n_state, kv_size);
  9013. // copy states
  9014. // NOTE: assuming the copy destinations are ALL contained between kv_head and kv_head + n_kv
  9015. // this shrinks the tensors's ne[1] to n_kv
  9016. states = ggml_get_rows(ctx, states, state_copy);
  9017. // clear states of sequences which are starting at the beginning of this batch
  9018. // FIXME: zero-out NANs?
  9019. states = ggml_mul(ctx, states, state_mask);
  9020. // copy states which won't be changed further (between n_seqs and n_kv)
  9021. ggml_build_forward_expand(graph,
  9022. ggml_cpy(ctx,
  9023. ggml_view_1d(ctx, states, n_state*(n_kv - n_seqs), n_seqs*n_state*ggml_element_size(states)),
  9024. ggml_view_1d(ctx, s, n_state*(n_kv - n_seqs), (kv_head + n_seqs)*n_state*ggml_element_size(s))));
  9025. // the part of the states that will be used and modified
  9026. return ggml_view_2d(ctx, states, n_state, n_seqs, states->nb[1], 0);
  9027. }
  9028. // TODO: split
  9029. static struct ggml_tensor * llm_build_mamba(
  9030. struct ggml_context * ctx,
  9031. struct llama_context & lctx,
  9032. const llama_ubatch & batch,
  9033. struct ggml_cgraph * graph,
  9034. struct ggml_tensor * cur,
  9035. struct ggml_tensor * state_copy,
  9036. struct ggml_tensor * state_mask,
  9037. int32_t kv_head,
  9038. int32_t n_kv,
  9039. const llm_build_cb & cb,
  9040. int il) {
  9041. const llama_model & model = lctx.model;
  9042. const llama_hparams & hparams = model.hparams;
  9043. const llama_kv_cache & kv = lctx.kv_self;
  9044. const int64_t d_conv = hparams.ssm_d_conv;
  9045. const int64_t d_inner = hparams.ssm_d_inner;
  9046. const int64_t d_state = hparams.ssm_d_state;
  9047. const int64_t dt_rank = hparams.ssm_dt_rank;
  9048. const int64_t n_seqs = batch.n_seqs;
  9049. // Some variants of Mamba arch (e.g. FalconMamba do apply layer norm on B and Dt layers)
  9050. const bool ssm_dt_b_c_rms = hparams.ssm_dt_b_c_rms;
  9051. // Use the same RMS norm as the final layer norm
  9052. const float norm_rms_eps = hparams.f_norm_rms_eps;
  9053. const int64_t n_seq_tokens = batch.n_seq_tokens;
  9054. GGML_ASSERT(n_seqs != 0);
  9055. GGML_ASSERT(batch.equal_seqs);
  9056. GGML_ASSERT(batch.n_tokens == n_seq_tokens * n_seqs);
  9057. struct ggml_tensor * conv_states_all = kv.k_l[il];
  9058. struct ggml_tensor * ssm_states_all = kv.v_l[il];
  9059. // (ab)using the KV cache to store the states
  9060. struct ggml_tensor * conv = llm_build_copy_mask_state(ctx,
  9061. graph, conv_states_all, state_copy, state_mask,
  9062. hparams.n_embd_k_s(), kv.size, kv_head, n_kv, n_seqs);
  9063. conv = ggml_reshape_3d(ctx, conv, d_conv - 1, d_inner, n_seqs);
  9064. struct ggml_tensor * ssm = llm_build_copy_mask_state(ctx,
  9065. graph, ssm_states_all, state_copy, state_mask,
  9066. hparams.n_embd_v_s(), kv.size, kv_head, n_kv, n_seqs);
  9067. ssm = ggml_reshape_3d(ctx, ssm, d_state, d_inner, n_seqs);
  9068. // {n_embd, n_tokens} => {n_embd, n_seq_tokens, n_seqs}
  9069. cur = ggml_reshape_3d(ctx, cur, cur->ne[0], n_seq_tokens, n_seqs);
  9070. // {n_embd, 2*d_inner} @ {n_embd, n_seq_tokens, n_seqs} => {2*d_inner, n_seq_tokens, n_seqs}
  9071. struct ggml_tensor * xz = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_in, cur);
  9072. // split the above in two
  9073. // => {d_inner, n_seq_tokens, n_seqs}
  9074. struct ggml_tensor * x = ggml_view_3d(ctx, xz, d_inner, xz->ne[1], xz->ne[2], xz->nb[1], xz->nb[2], 0);
  9075. 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));
  9076. // conv
  9077. {
  9078. // => {d_conv - 1 + n_seq_tokens, d_inner, n_seqs}
  9079. struct ggml_tensor * conv_x = ggml_concat(ctx, conv, ggml_transpose(ctx, x), 0);
  9080. // copy last (d_conv - 1) columns back into the state cache
  9081. 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]));
  9082. ggml_build_forward_expand(graph,
  9083. ggml_cpy(ctx, last_conv,
  9084. ggml_view_1d(ctx, conv_states_all,
  9085. (d_conv - 1)*(d_inner)*(n_seqs),
  9086. kv_head*(d_conv - 1)*(d_inner)*ggml_element_size(conv_states_all))));
  9087. // 1D convolution
  9088. // The equivalent is to make a self-overlapping view of conv_x
  9089. // over d_conv columns at each stride in the 3rd dimension,
  9090. // then element-wise multiply that with the conv1d weight,
  9091. // then sum the elements of each row,
  9092. // (the last two steps are a dot product over rows (also doable with mul_mat))
  9093. // then permute away the ne[0] dimension,
  9094. // and then you're left with the resulting x tensor.
  9095. // For simultaneous sequences, all sequences need to have the same length.
  9096. x = ggml_ssm_conv(ctx, conv_x, model.layers[il].ssm_conv1d);
  9097. // bias
  9098. x = ggml_add(ctx, x, model.layers[il].ssm_conv1d_b);
  9099. x = ggml_silu(ctx, x);
  9100. }
  9101. // ssm
  9102. {
  9103. // {d_inner, dt_rank + 2*d_state} @ {d_inner, n_seq_tokens, n_seqs} => {dt_rank + 2*d_state, n_seq_tokens, n_seqs}
  9104. struct ggml_tensor * x_db = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_x, x);
  9105. // split
  9106. 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);
  9107. 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);
  9108. 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));
  9109. // Some Mamba variants (e.g. FalconMamba) apply RMS norm in B, C & Dt layers
  9110. if (ssm_dt_b_c_rms) {
  9111. dt = ggml_rms_norm(ctx, dt, norm_rms_eps);
  9112. B = ggml_rms_norm(ctx, B, norm_rms_eps);
  9113. C = ggml_rms_norm(ctx, C, norm_rms_eps);
  9114. }
  9115. // {dt_rank, d_inner} @ {dt_rank, n_seq_tokens, n_seqs} => {d_inner, n_seq_tokens, n_seqs}
  9116. dt = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_dt, dt);
  9117. dt = ggml_add(ctx, dt, model.layers[il].ssm_dt_b);
  9118. // Custom operator to optimize the parallel associative scan
  9119. // as described in the Annex D of the Mamba paper.
  9120. // => {d_inner, n_seq_tokens, n_seqs} and {d_state, d_inner, n_seqs}
  9121. struct ggml_tensor * y_ssm = ggml_ssm_scan(ctx, ssm, x, dt, model.layers[il].ssm_a, B, C);
  9122. // store last states
  9123. ggml_build_forward_expand(graph,
  9124. ggml_cpy(ctx,
  9125. ggml_view_1d(ctx, y_ssm, d_state*d_inner*n_seqs, x->nb[3]),
  9126. 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))));
  9127. struct ggml_tensor * y = ggml_view_3d(ctx, y_ssm, d_inner, n_seq_tokens, n_seqs, x->nb[1], x->nb[2], 0);
  9128. // TODO: skip computing output earlier for unused tokens
  9129. // {d_inner, n_seq_tokens, n_seqs} * {d_inner} => {d_inner, n_seq_tokens, n_seqs}
  9130. y = ggml_add(ctx, y, ggml_mul(ctx, x, model.layers[il].ssm_d));
  9131. y = ggml_mul(ctx, y, ggml_silu(ctx, ggml_cont(ctx, z)));
  9132. // {d_inner, n_embd} @ {d_inner, n_seq_tokens, n_seqs} => {n_embd, n_seq_tokens, n_seqs}
  9133. cur = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_out, y);
  9134. }
  9135. // {n_embd, n_seq_tokens, n_seqs} => {n_embd, n_tokens}
  9136. cur = ggml_reshape_2d(ctx, cur, cur->ne[0], n_seq_tokens * n_seqs);
  9137. cb(cur, "mamba_out", il);
  9138. return cur;
  9139. }
  9140. static struct ggml_tensor * llm_build_rwkv6_time_mix(
  9141. struct llama_context & lctx,
  9142. struct ggml_context * ctx,
  9143. const struct llama_layer * layer,
  9144. struct ggml_tensor * cur,
  9145. struct ggml_tensor * x_prev,
  9146. struct ggml_tensor ** wkv_state) {
  9147. size_t n_embd = cur->ne[0];
  9148. size_t n_seq_tokens = cur->ne[1];
  9149. size_t n_seqs = cur->ne[2];
  9150. size_t head_size = layer->time_mix_first->ne[0];
  9151. size_t head_count = layer->time_mix_first->ne[1];
  9152. size_t n_tokens = n_seqs * n_seq_tokens;
  9153. struct ggml_tensor * sx = ggml_sub(ctx, x_prev, cur);
  9154. sx = ggml_reshape_2d(ctx, sx, n_embd, n_tokens);
  9155. cur = ggml_reshape_2d(ctx, cur, n_embd, n_tokens);
  9156. struct ggml_tensor * xxx = ggml_add(ctx, ggml_mul(ctx, sx, layer->time_mix_lerp_x), cur);
  9157. xxx = ggml_reshape_4d(
  9158. ctx,
  9159. ggml_tanh(
  9160. ctx,
  9161. ggml_mul_mat(ctx, layer->time_mix_w1, xxx)
  9162. ),
  9163. layer->time_mix_w1->ne[1] / 5, 1, 5, n_tokens
  9164. );
  9165. xxx = ggml_cont(ctx, ggml_permute(ctx, xxx, 0, 1, 3, 2));
  9166. xxx = ggml_mul_mat(
  9167. ctx,
  9168. ggml_reshape_4d(
  9169. ctx,
  9170. layer->time_mix_w2,
  9171. layer->time_mix_w2->ne[0], layer->time_mix_w2->ne[1], 1, 5
  9172. ),
  9173. xxx
  9174. );
  9175. struct ggml_tensor *mw = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], 0);
  9176. struct ggml_tensor *mk = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * sizeof(float));
  9177. struct ggml_tensor *mv = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * 2 * sizeof(float));
  9178. struct ggml_tensor *mr = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * 3 * sizeof(float));
  9179. struct ggml_tensor *mg = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * 4 * sizeof(float));
  9180. struct ggml_tensor * xw = ggml_add(
  9181. ctx,
  9182. ggml_mul(
  9183. ctx,
  9184. ggml_add(ctx, mw, layer->time_mix_lerp_w),
  9185. sx
  9186. ),
  9187. cur
  9188. );
  9189. struct ggml_tensor * xk = ggml_add(
  9190. ctx,
  9191. ggml_mul(
  9192. ctx,
  9193. ggml_add(ctx, mk, layer->time_mix_lerp_k),
  9194. sx
  9195. ),
  9196. cur
  9197. );
  9198. struct ggml_tensor * xv = ggml_add(
  9199. ctx,
  9200. ggml_mul(
  9201. ctx,
  9202. ggml_add(ctx, mv, layer->time_mix_lerp_v),
  9203. sx
  9204. ),
  9205. cur
  9206. );
  9207. struct ggml_tensor * xr = ggml_add(
  9208. ctx,
  9209. ggml_mul(
  9210. ctx,
  9211. ggml_add(ctx, mr, layer->time_mix_lerp_r),
  9212. sx
  9213. ),
  9214. cur
  9215. );
  9216. struct ggml_tensor * xg = ggml_add(
  9217. ctx,
  9218. ggml_mul(
  9219. ctx,
  9220. ggml_add(ctx, mg, layer->time_mix_lerp_g),
  9221. sx
  9222. ),
  9223. cur
  9224. );
  9225. 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);
  9226. 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);
  9227. 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);
  9228. struct ggml_tensor * g = ggml_silu(
  9229. ctx,
  9230. llm_build_lora_mm(lctx, ctx, layer->time_mix_gate, xg)
  9231. );
  9232. struct ggml_tensor * w = ggml_mul_mat(
  9233. ctx,
  9234. layer->time_mix_decay_w2,
  9235. ggml_tanh(
  9236. ctx,
  9237. ggml_mul_mat(ctx, layer->time_mix_decay_w1, xw)
  9238. )
  9239. );
  9240. w = ggml_add(ctx, w, ggml_reshape_1d(ctx, layer->time_mix_decay, n_embd));
  9241. w = ggml_exp(ctx, ggml_neg(ctx, ggml_exp(ctx, w)));
  9242. w = ggml_reshape_4d(ctx, w, 1, head_size, head_count, n_tokens);
  9243. k = ggml_transpose(ctx, k);
  9244. v = ggml_transpose(ctx, v);
  9245. r = ggml_transpose(ctx, r);
  9246. struct ggml_tensor * wkv_output = ggml_rwkv_wkv6(ctx, k, v, r, layer->time_mix_first, w, *wkv_state);
  9247. cur = ggml_view_1d(ctx, wkv_output, n_embd * n_tokens, 0);
  9248. *wkv_state = ggml_view_1d(ctx, wkv_output, n_embd * head_size * n_seqs, n_embd * n_tokens * sizeof(float));
  9249. // group norm with head_count groups
  9250. cur = ggml_reshape_3d(ctx, cur, n_embd / head_count, head_count, n_tokens);
  9251. cur = ggml_norm(ctx, cur, 64e-5f);
  9252. // Convert back to regular vectors.
  9253. cur = ggml_reshape_2d(ctx, cur, n_embd, n_tokens);
  9254. cur = ggml_add(ctx, ggml_mul(ctx, cur, layer->time_mix_ln), layer->time_mix_ln_b);
  9255. cur = ggml_mul(ctx, cur, g);
  9256. cur = llm_build_lora_mm(lctx, ctx, layer->time_mix_output, cur);
  9257. return ggml_reshape_3d(ctx, cur, n_embd, n_seq_tokens, n_seqs);
  9258. }
  9259. static struct ggml_tensor * llm_build_rwkv6_channel_mix(
  9260. struct llama_context & lctx,
  9261. struct ggml_context * ctx,
  9262. const struct llama_layer * layer,
  9263. struct ggml_tensor * cur,
  9264. struct ggml_tensor * x_prev) {
  9265. struct ggml_tensor * sx = ggml_sub(ctx, x_prev, cur);
  9266. struct ggml_tensor * xk = ggml_add(ctx, ggml_mul(ctx, sx, layer->channel_mix_lerp_k), cur);
  9267. struct ggml_tensor * xr = ggml_add(ctx, ggml_mul(ctx, sx, layer->channel_mix_lerp_r), cur);
  9268. struct ggml_tensor * r = ggml_sigmoid(ctx, llm_build_lora_mm(lctx, ctx, layer->channel_mix_receptance, xr));
  9269. struct ggml_tensor * k = ggml_sqr(
  9270. ctx,
  9271. ggml_relu(
  9272. ctx,
  9273. llm_build_lora_mm(lctx, ctx, layer->channel_mix_key, xk)
  9274. )
  9275. );
  9276. return ggml_mul(ctx, r, llm_build_lora_mm(lctx, ctx, layer->channel_mix_value, k));
  9277. }
  9278. struct llm_build_context {
  9279. const llama_model & model;
  9280. llama_context & lctx;
  9281. const llama_hparams & hparams;
  9282. const llama_cparams & cparams;
  9283. const llama_ubatch & ubatch;
  9284. const llama_kv_cache & kv_self;
  9285. const int64_t n_embd;
  9286. const int64_t n_layer;
  9287. const int64_t n_rot;
  9288. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  9289. const int64_t n_head;
  9290. const int64_t n_head_kv;
  9291. const int64_t n_embd_head_k;
  9292. const int64_t n_embd_k_gqa;
  9293. const int64_t n_embd_head_v;
  9294. const int64_t n_embd_v_gqa;
  9295. const int64_t n_expert;
  9296. const int64_t n_expert_used;
  9297. const float freq_base;
  9298. const float freq_scale;
  9299. const float ext_factor;
  9300. const float attn_factor;
  9301. const float beta_fast;
  9302. const float beta_slow;
  9303. const float norm_eps;
  9304. const float norm_rms_eps;
  9305. const int32_t n_tokens;
  9306. const int32_t n_kv; // size of KV cache to consider (n_kv <= kv_self.size)
  9307. const int32_t n_outputs;
  9308. const int32_t n_outputs_enc;
  9309. const int32_t kv_head; // index of where we store new KV data in the cache
  9310. const int32_t n_ctx_orig;
  9311. const bool flash_attn;
  9312. const enum llama_pooling_type pooling_type;
  9313. const enum llama_rope_type rope_type;
  9314. const llm_build_cb & cb;
  9315. std::vector<uint8_t> & buf_compute_meta;
  9316. struct ggml_context * ctx0 = nullptr;
  9317. // TODO: consider making the entire interface noexcept
  9318. llm_build_context(
  9319. llama_context & lctx,
  9320. const llama_ubatch & ubatch,
  9321. const llm_build_cb & cb,
  9322. bool worst_case) :
  9323. model (lctx.model),
  9324. lctx (lctx),
  9325. hparams (model.hparams),
  9326. cparams (lctx.cparams),
  9327. ubatch (ubatch),
  9328. kv_self (lctx.kv_self),
  9329. n_embd (hparams.n_embd),
  9330. n_layer (hparams.n_layer),
  9331. n_rot (hparams.n_rot),
  9332. n_ctx (cparams.n_ctx),
  9333. n_head (hparams.n_head()),
  9334. n_head_kv (hparams.n_head_kv()),
  9335. n_embd_head_k (hparams.n_embd_head_k),
  9336. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  9337. n_embd_head_v (hparams.n_embd_head_v),
  9338. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  9339. n_expert (hparams.n_expert),
  9340. n_expert_used (hparams.n_expert_used),
  9341. freq_base (cparams.rope_freq_base),
  9342. freq_scale (cparams.rope_freq_scale),
  9343. ext_factor (cparams.yarn_ext_factor),
  9344. attn_factor (cparams.yarn_attn_factor),
  9345. beta_fast (cparams.yarn_beta_fast),
  9346. beta_slow (cparams.yarn_beta_slow),
  9347. norm_eps (hparams.f_norm_eps),
  9348. norm_rms_eps (hparams.f_norm_rms_eps),
  9349. n_tokens (ubatch.n_tokens),
  9350. n_kv (worst_case ? kv_self.size : kv_self.n),
  9351. n_outputs (worst_case ? n_tokens : lctx.n_outputs),
  9352. n_outputs_enc (worst_case ? n_tokens : lctx.embd_enc.size() / hparams.n_embd),
  9353. kv_head (worst_case ? (kv_self.recurrent ? 0 : kv_self.size - n_tokens) : kv_self.head),
  9354. n_ctx_orig (cparams.n_ctx_orig_yarn),
  9355. flash_attn (cparams.flash_attn),
  9356. pooling_type (cparams.pooling_type),
  9357. rope_type (hparams.rope_type),
  9358. cb (cb),
  9359. buf_compute_meta (lctx.buf_compute_meta) {
  9360. // all initializations should be done in init()
  9361. }
  9362. void init() {
  9363. struct ggml_init_params params = {
  9364. /*.mem_size =*/ buf_compute_meta.size(),
  9365. /*.mem_buffer =*/ buf_compute_meta.data(),
  9366. /*.no_alloc =*/ true,
  9367. };
  9368. ctx0 = ggml_init(params);
  9369. lctx.inp_tokens = nullptr;
  9370. lctx.inp_embd = nullptr;
  9371. lctx.inp_pos = nullptr;
  9372. lctx.inp_out_ids = nullptr;
  9373. lctx.inp_KQ_mask = nullptr;
  9374. lctx.inp_KQ_mask_swa = nullptr;
  9375. lctx.inp_K_shift = nullptr;
  9376. lctx.inp_mean = nullptr;
  9377. lctx.inp_cls = nullptr;
  9378. lctx.inp_s_copy = nullptr;
  9379. lctx.inp_s_mask = nullptr;
  9380. lctx.inp_s_seq = nullptr;
  9381. lctx.inp_pos_bucket = nullptr;
  9382. lctx.inp_embd_enc = nullptr;
  9383. lctx.inp_KQ_mask_cross = nullptr;
  9384. lctx.inp_cross_attn_state = nullptr;
  9385. }
  9386. void free() {
  9387. ggml_free(ctx0);
  9388. ctx0 = nullptr;
  9389. }
  9390. struct ggml_cgraph * build_k_shift() {
  9391. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9392. GGML_ASSERT(kv_self.size == n_ctx);
  9393. lctx.inp_K_shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_ctx);
  9394. cb(lctx.inp_K_shift, "K_shift", -1);
  9395. ggml_set_input(lctx.inp_K_shift);
  9396. for (int il = 0; il < n_layer; ++il) {
  9397. const int64_t n_head_kv = hparams.n_head_kv(il);
  9398. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  9399. struct ggml_tensor * rope_factors = build_rope_factors(il);
  9400. struct ggml_tensor * k =
  9401. ggml_view_3d(ctx0, kv_self.k_l[il],
  9402. n_embd_head_k, n_head_kv, n_ctx,
  9403. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  9404. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  9405. 0);
  9406. struct ggml_tensor * tmp;
  9407. if (ggml_is_quantized(k->type)) {
  9408. // dequantize to f32 -> RoPE -> quantize back
  9409. tmp = ggml_cast(ctx0, k, GGML_TYPE_F32);
  9410. cb(tmp, "K_f32", il);
  9411. for (auto & backend : lctx.backends) {
  9412. // Figure out which backend KV cache belongs to
  9413. if (ggml_backend_supports_buft(backend.get(), ggml_backend_buffer_get_type(kv_self.k_l[il]->buffer))) {
  9414. ggml_backend_sched_set_tensor_backend(lctx.sched.get(), tmp, backend.get());
  9415. break;
  9416. }
  9417. }
  9418. tmp = ggml_rope_ext_inplace(ctx0, tmp,
  9419. lctx.inp_K_shift, rope_factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9420. ext_factor, attn_factor, beta_fast, beta_slow);
  9421. cb(tmp, "K_shifted_f32", il);
  9422. tmp = ggml_cpy(ctx0, tmp, k);
  9423. } else {
  9424. // we rotate only the first n_rot dimensions
  9425. tmp = ggml_rope_ext_inplace(ctx0, k,
  9426. lctx.inp_K_shift, rope_factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9427. ext_factor, attn_factor, beta_fast, beta_slow);
  9428. }
  9429. cb(tmp, "K_shifted", il);
  9430. ggml_build_forward_expand(gf, tmp);
  9431. }
  9432. return gf;
  9433. }
  9434. struct ggml_cgraph * build_defrag(const std::vector<struct llama_kv_defrag_move> & moves) {
  9435. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9436. for (const auto & move : moves) {
  9437. for (int il = 0; il < n_layer; ++il) {
  9438. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  9439. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  9440. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  9441. n_embd_k_gqa, move.len,
  9442. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  9443. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*move.src));
  9444. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  9445. n_embd_k_gqa, move.len,
  9446. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  9447. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*move.dst));
  9448. ggml_tensor * view_v_src;
  9449. ggml_tensor * view_v_dst;
  9450. if (flash_attn) {
  9451. // NOTE: the V cache is not transposed when using flash attention
  9452. view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  9453. n_embd_v_gqa, move.len,
  9454. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa),
  9455. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*move.src));
  9456. view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  9457. n_embd_v_gqa, move.len,
  9458. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa),
  9459. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*move.dst));
  9460. } else {
  9461. view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  9462. move.len, n_embd_v_gqa,
  9463. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  9464. ggml_row_size(kv_self.v_l[il]->type, move.src));
  9465. view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  9466. move.len, n_embd_v_gqa,
  9467. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  9468. ggml_row_size(kv_self.v_l[il]->type, move.dst));
  9469. }
  9470. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  9471. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  9472. }
  9473. }
  9474. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  9475. return gf;
  9476. }
  9477. struct ggml_tensor * build_inp_pos() {
  9478. lctx.inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  9479. cb(lctx.inp_pos, "inp_pos", -1);
  9480. ggml_set_input(lctx.inp_pos);
  9481. return lctx.inp_pos;
  9482. }
  9483. struct ggml_tensor * build_rope_factors(int il) {
  9484. // choose long/short freq factors based on the context size
  9485. const auto n_ctx_pre_seq = cparams.n_ctx / cparams.n_seq_max;
  9486. if (model.layers[il].rope_freqs != nullptr) {
  9487. return model.layers[il].rope_freqs;
  9488. }
  9489. if (n_ctx_pre_seq > hparams.n_ctx_orig_yarn) {
  9490. return model.layers[il].rope_long;
  9491. }
  9492. return model.layers[il].rope_short;
  9493. }
  9494. struct ggml_tensor * build_inp_out_ids() {
  9495. lctx.inp_out_ids = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_outputs);
  9496. cb(lctx.inp_out_ids, "inp_out_ids", -1);
  9497. ggml_set_input(lctx.inp_out_ids);
  9498. return lctx.inp_out_ids;
  9499. }
  9500. struct ggml_tensor * build_inp_KQ_mask(bool causal = true) {
  9501. lctx.inp_KQ_mask = causal
  9502. ? ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD))
  9503. : ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  9504. cb(lctx.inp_KQ_mask, "KQ_mask", -1);
  9505. ggml_set_input(lctx.inp_KQ_mask);
  9506. return flash_attn ? ggml_cast(ctx0, lctx.inp_KQ_mask, GGML_TYPE_F16) : lctx.inp_KQ_mask;
  9507. }
  9508. struct ggml_tensor * build_inp_KQ_mask_swa(bool causal = true) {
  9509. GGML_ASSERT(hparams.n_swa > 0);
  9510. lctx.inp_KQ_mask_swa = causal
  9511. ? ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD))
  9512. : ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  9513. cb(lctx.inp_KQ_mask_swa, "KQ_mask_swa", -1);
  9514. ggml_set_input(lctx.inp_KQ_mask_swa);
  9515. return flash_attn ? ggml_cast(ctx0, lctx.inp_KQ_mask_swa, GGML_TYPE_F16) : lctx.inp_KQ_mask_swa;
  9516. }
  9517. struct ggml_tensor * build_inp_mean() {
  9518. lctx.inp_mean = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  9519. cb(lctx.inp_mean, "inp_mean", -1);
  9520. ggml_set_input(lctx.inp_mean);
  9521. return lctx.inp_mean;
  9522. }
  9523. struct ggml_tensor * build_inp_cls() {
  9524. lctx.inp_cls = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  9525. cb(lctx.inp_cls, "inp_cls", -1);
  9526. ggml_set_input(lctx.inp_cls);
  9527. return lctx.inp_cls;
  9528. }
  9529. struct ggml_tensor * build_inp_s_copy() {
  9530. lctx.inp_s_copy = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_kv);
  9531. cb(lctx.inp_s_copy, "inp_s_copy", -1);
  9532. ggml_set_input(lctx.inp_s_copy);
  9533. return lctx.inp_s_copy;
  9534. }
  9535. struct ggml_tensor * build_inp_s_mask() {
  9536. lctx.inp_s_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_kv);
  9537. cb(lctx.inp_s_mask, "inp_s_mask", -1);
  9538. ggml_set_input(lctx.inp_s_mask);
  9539. return lctx.inp_s_mask;
  9540. }
  9541. struct ggml_cgraph * append_pooling(struct ggml_cgraph * gf) {
  9542. // find result_norm tensor for input
  9543. struct ggml_tensor * inp = nullptr;
  9544. for (int i = ggml_graph_n_nodes(gf) - 1; i >= 0; --i) {
  9545. inp = ggml_graph_node(gf, i);
  9546. if (strcmp(inp->name, "result_norm") == 0 || strcmp(inp->name, "result_embd") == 0) {
  9547. break;
  9548. } else {
  9549. inp = nullptr;
  9550. }
  9551. }
  9552. GGML_ASSERT(inp != nullptr && "missing result_norm/result_embd tensor");
  9553. struct ggml_tensor * cur;
  9554. switch (pooling_type) {
  9555. case LLAMA_POOLING_TYPE_NONE:
  9556. {
  9557. cur = inp;
  9558. } break;
  9559. case LLAMA_POOLING_TYPE_MEAN:
  9560. {
  9561. struct ggml_tensor * inp_mean = build_inp_mean();
  9562. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, inp)), inp_mean);
  9563. } break;
  9564. case LLAMA_POOLING_TYPE_CLS:
  9565. case LLAMA_POOLING_TYPE_LAST:
  9566. {
  9567. struct ggml_tensor * inp_cls = build_inp_cls();
  9568. cur = ggml_get_rows(ctx0, inp, inp_cls);
  9569. } break;
  9570. case LLAMA_POOLING_TYPE_RANK:
  9571. {
  9572. struct ggml_tensor * inp_cls = build_inp_cls();
  9573. inp = ggml_get_rows(ctx0, inp, inp_cls);
  9574. // classification head
  9575. // https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/roberta/modeling_roberta.py#L1566
  9576. GGML_ASSERT(model.cls != nullptr);
  9577. GGML_ASSERT(model.cls_b != nullptr);
  9578. cur = ggml_add (ctx0, ggml_mul_mat(ctx0, model.cls, inp), model.cls_b);
  9579. cur = ggml_tanh(ctx0, cur);
  9580. // some models don't have `cls_out`, for example: https://huggingface.co/jinaai/jina-reranker-v1-tiny-en
  9581. // https://huggingface.co/jinaai/jina-reranker-v1-tiny-en/blob/cb5347e43979c3084a890e3f99491952603ae1b7/modeling_bert.py#L884-L896
  9582. if (model.cls_out) {
  9583. GGML_ASSERT(model.cls_out_b != nullptr);
  9584. cur = ggml_add (ctx0, ggml_mul_mat(ctx0, model.cls_out, cur), model.cls_out_b);
  9585. }
  9586. } break;
  9587. default:
  9588. {
  9589. GGML_ABORT("unknown pooling type");
  9590. }
  9591. }
  9592. cb(cur, "result_embd_pooled", -1);
  9593. ggml_build_forward_expand(gf, cur);
  9594. return gf;
  9595. }
  9596. struct ggml_tensor * llm_build_pos_bucket(bool causal) {
  9597. if (causal) {
  9598. lctx.inp_pos_bucket = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  9599. } else {
  9600. lctx.inp_pos_bucket = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_tokens);
  9601. }
  9602. ggml_set_input(lctx.inp_pos_bucket);
  9603. cb(lctx.inp_pos_bucket, "pos_bucket", -1);
  9604. return lctx.inp_pos_bucket;
  9605. }
  9606. struct ggml_tensor * llm_build_pos_bias(struct ggml_tensor * pos_bucket, struct ggml_tensor * attn_rel_b) {
  9607. struct ggml_tensor * pos_bucket_1d = ggml_view_1d(ctx0, pos_bucket, pos_bucket->ne[0] * pos_bucket->ne[1], 0);
  9608. cb(pos_bucket_1d, "pos_bucket_1d", -1);
  9609. struct ggml_tensor * pos_bias = ggml_get_rows(ctx0, attn_rel_b, pos_bucket_1d);
  9610. cb(pos_bias, "pos_bias", -1);
  9611. 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);
  9612. cb(pos_bias, "pos_bias", -1);
  9613. pos_bias = ggml_permute(ctx0, pos_bias, 2, 0, 1, 3);
  9614. cb(pos_bias, "pos_bias", -1);
  9615. pos_bias = ggml_cont(ctx0, pos_bias);
  9616. cb(pos_bias, "pos_bias", -1);
  9617. return pos_bias;
  9618. }
  9619. struct ggml_tensor * llm_build_inp_embd_enc() {
  9620. const int64_t n_embd = hparams.n_embd;
  9621. lctx.inp_embd_enc = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, n_outputs_enc);
  9622. ggml_set_input(lctx.inp_embd_enc);
  9623. cb(lctx.inp_embd_enc, "embd_enc", -1);
  9624. return lctx.inp_embd_enc;
  9625. }
  9626. struct ggml_tensor * llm_build_inp_KQ_mask_cross() {
  9627. lctx.inp_KQ_mask_cross = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_outputs_enc, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  9628. ggml_set_input(lctx.inp_KQ_mask_cross);
  9629. cb(lctx.inp_KQ_mask_cross, "KQ_mask_cross", -1);
  9630. return lctx.inp_KQ_mask_cross;
  9631. }
  9632. struct ggml_cgraph * build_llama() {
  9633. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9634. // mutable variable, needed during the last layer of the computation to skip unused tokens
  9635. int32_t n_tokens = this->n_tokens;
  9636. const int64_t n_embd_head = hparams.n_embd_head_v;
  9637. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9638. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9639. struct ggml_tensor * cur;
  9640. struct ggml_tensor * inpL;
  9641. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  9642. // inp_pos - contains the positions
  9643. struct ggml_tensor * inp_pos = build_inp_pos();
  9644. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9645. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9646. const float kq_scale = hparams.f_attention_scale == 0.0f ? 1.0f/sqrtf(float(n_embd_head)) : hparams.f_attention_scale;
  9647. for (int il = 0; il < n_layer; ++il) {
  9648. struct ggml_tensor * inpSA = inpL;
  9649. // norm
  9650. cur = llm_build_norm(ctx0, inpL, hparams,
  9651. model.layers[il].attn_norm, NULL,
  9652. LLM_NORM_RMS, cb, il);
  9653. cb(cur, "attn_norm", il);
  9654. // self-attention
  9655. {
  9656. // rope freq factors for llama3; may return nullptr for llama2 and other models
  9657. struct ggml_tensor * rope_factors = build_rope_factors(il);
  9658. // compute Q and K and RoPE them
  9659. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9660. cb(Qcur, "Qcur", il);
  9661. if (model.layers[il].bq) {
  9662. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9663. cb(Qcur, "Qcur", il);
  9664. }
  9665. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9666. cb(Kcur, "Kcur", il);
  9667. if (model.layers[il].bk) {
  9668. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9669. cb(Kcur, "Kcur", il);
  9670. }
  9671. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9672. cb(Vcur, "Vcur", il);
  9673. if (model.layers[il].bv) {
  9674. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9675. cb(Vcur, "Vcur", il);
  9676. }
  9677. Qcur = ggml_rope_ext(
  9678. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  9679. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9680. ext_factor, attn_factor, beta_fast, beta_slow
  9681. );
  9682. cb(Qcur, "Qcur", il);
  9683. Kcur = ggml_rope_ext(
  9684. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  9685. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9686. ext_factor, attn_factor, beta_fast, beta_slow
  9687. );
  9688. cb(Kcur, "Kcur", il);
  9689. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9690. model.layers[il].wo, model.layers[il].bo,
  9691. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  9692. }
  9693. if (il == n_layer - 1) {
  9694. // skip computing output for unused tokens
  9695. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9696. n_tokens = n_outputs;
  9697. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9698. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9699. }
  9700. // For Granite architecture
  9701. if (hparams.f_residual_scale) {
  9702. cur = ggml_scale(ctx0, cur, hparams.f_residual_scale);
  9703. }
  9704. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9705. cb(ffn_inp, "ffn_inp", il);
  9706. // feed-forward network
  9707. if (model.layers[il].ffn_gate_inp == nullptr) {
  9708. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9709. model.layers[il].ffn_norm, NULL,
  9710. LLM_NORM_RMS, cb, il);
  9711. cb(cur, "ffn_norm", il);
  9712. cur = llm_build_ffn(ctx0, lctx, cur,
  9713. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9714. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  9715. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9716. NULL,
  9717. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9718. cb(cur, "ffn_out", il);
  9719. } else {
  9720. // MoE branch
  9721. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9722. model.layers[il].ffn_norm, NULL,
  9723. LLM_NORM_RMS, cb, il);
  9724. cb(cur, "ffn_norm", il);
  9725. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  9726. model.layers[il].ffn_gate_inp,
  9727. model.layers[il].ffn_up_exps,
  9728. model.layers[il].ffn_gate_exps,
  9729. model.layers[il].ffn_down_exps,
  9730. n_expert, n_expert_used,
  9731. LLM_FFN_SILU, true,
  9732. false, 0.0,
  9733. cb, il);
  9734. cb(cur, "ffn_moe_out", il);
  9735. }
  9736. // For Granite architecture
  9737. if (hparams.f_residual_scale) {
  9738. cur = ggml_scale(ctx0, cur, hparams.f_residual_scale);
  9739. }
  9740. cur = ggml_add(ctx0, cur, ffn_inp);
  9741. cb(cur, "ffn_out", il);
  9742. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9743. cb(cur, "l_out", il);
  9744. // input for next layer
  9745. inpL = cur;
  9746. }
  9747. cur = inpL;
  9748. cur = llm_build_norm(ctx0, cur, hparams,
  9749. model.output_norm, NULL,
  9750. LLM_NORM_RMS, cb, -1);
  9751. cb(cur, "result_norm", -1);
  9752. // lm_head
  9753. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9754. // For Granite architecture
  9755. if (hparams.f_logit_scale) {
  9756. cur = ggml_scale(ctx0, cur, 1.0f / hparams.f_logit_scale);
  9757. }
  9758. cb(cur, "result_output", -1);
  9759. ggml_build_forward_expand(gf, cur);
  9760. return gf;
  9761. }
  9762. struct ggml_cgraph * build_mllama() {
  9763. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9764. // mutable variable, needed during the last layer of the computation to skip unused tokens
  9765. int32_t n_tokens = this->n_tokens;
  9766. const int64_t n_embd_head = hparams.n_embd_head_v;
  9767. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9768. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9769. struct ggml_tensor * cur;
  9770. struct ggml_tensor * inpL;
  9771. struct ggml_tensor * inpCAS;
  9772. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  9773. inpCAS = llm_build_inp_cross_attn_state(ctx0, lctx, hparams, cb);
  9774. // inp_pos - contains the positions
  9775. struct ggml_tensor * inp_pos = build_inp_pos();
  9776. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9777. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9778. for (int il = 0; il < n_layer; ++il) {
  9779. struct ggml_tensor * inpSA = inpL;
  9780. // norm
  9781. cur = llm_build_norm(ctx0, inpL, hparams,
  9782. model.layers[il].attn_norm, NULL,
  9783. LLM_NORM_RMS, cb, il);
  9784. cb(cur, "attn_norm", il);
  9785. if (hparams.cross_attention_layers(il)) {
  9786. if (!ubatch.embd && !cparams.cross_attn) {
  9787. continue;
  9788. }
  9789. // cross attention layer
  9790. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].cross_attn_q_proj, cur);
  9791. cb(Qcur, "Qcur", il);
  9792. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9793. cb(Qcur, "Qcur", il);
  9794. Qcur = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 0, 2, 1, 3));
  9795. cb(Qcur, "Qcur", il);
  9796. Qcur = llm_build_norm(ctx0, Qcur, hparams, model.layers[il].cross_attn_q_norm, NULL, LLM_NORM_RMS, cb, il);
  9797. cb(Qcur, "Qcur", il);
  9798. struct ggml_tensor * Kcur, * Vcur;
  9799. if (ubatch.embd) {
  9800. Kcur = ggml_mul_mat(ctx0, model.layers[il].cross_attn_k_proj, inpCAS);
  9801. cb(Kcur, "Kcur", il);
  9802. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, 6404);
  9803. cb(Kcur, "Kcur", il);
  9804. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  9805. cb(Kcur, "Kcur", il);
  9806. Kcur = llm_build_norm(ctx0, Kcur, hparams, model.layers[il].cross_attn_k_norm, NULL, LLM_NORM_RMS, cb, il);
  9807. cb(Kcur, "Kcur", il);
  9808. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, kv_self.k_l[il]));
  9809. Vcur = ggml_mul_mat(ctx0, model.layers[il].cross_attn_v_proj, inpCAS);
  9810. cb(Vcur, "Vcur", il);
  9811. Vcur = ggml_reshape_3d(ctx0, Vcur, n_embd_head, n_head_kv, 6404);
  9812. cb(Vcur, "Vcur", il);
  9813. Vcur = ggml_permute(ctx0, Vcur, 0, 2, 1, 3);
  9814. cb(Vcur, "Vcur", il);
  9815. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, kv_self.v_l[il]));
  9816. } else {
  9817. Kcur = ggml_view_tensor(ctx0, kv_self.k_l[il]);
  9818. cb(Kcur, "Kcur (view)", il);
  9819. Vcur = ggml_view_tensor(ctx0, kv_self.v_l[il]);
  9820. cb(Vcur, "Vcur (view)", il);
  9821. }
  9822. struct ggml_tensor * kq = ggml_mul_mat(ctx0, Kcur, Qcur);
  9823. cb(kq, "kq", il);
  9824. // TODO: apply causal masks
  9825. 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);
  9826. cb(kq_soft_max, "kq_soft_max", il);
  9827. Vcur = ggml_cont(ctx0, ggml_transpose(ctx0, Vcur));
  9828. cb(Vcur, "Vcur", il);
  9829. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, Vcur, kq_soft_max);
  9830. cb(kqv, "kqv", il);
  9831. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  9832. cb(kqv_merged, "kqv_merged", il);
  9833. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_head_v*n_head, n_tokens);
  9834. cb(cur, "kqv_merged_cont", il);
  9835. cur = ggml_mul_mat(ctx0, model.layers[il].cross_attn_o_proj, cur);
  9836. cb(cur, "cur", il);
  9837. // TODO: do this in place once?
  9838. cur = ggml_mul(ctx0, cur, ggml_tanh(ctx0, model.layers[il].cross_attn_attn_gate));
  9839. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9840. cb(ffn_inp, "ffn_inp", il);
  9841. // feed-forward network
  9842. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9843. model.layers[il].ffn_norm, NULL,
  9844. LLM_NORM_RMS, cb, il);
  9845. cb(cur, "ffn_norm", il);
  9846. cur = llm_build_ffn(ctx0, lctx, cur,
  9847. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9848. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  9849. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9850. NULL,
  9851. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9852. cb(cur, "ffn_out", il);
  9853. // TODO: do this inplace once?
  9854. cur = ggml_add_inplace(ctx0, ggml_mul_inplace(ctx0, cur, ggml_tanh(ctx0, model.layers[il].cross_attn_mlp_gate)), ffn_inp);
  9855. cb(cur, "ffn_out", il);
  9856. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9857. cb(cur, "l_out", il);
  9858. // input for next layer
  9859. inpL = cur;
  9860. } else {
  9861. // self attention layer
  9862. // rope freq factors for llama3; may return nullptr for llama2 and other models
  9863. struct ggml_tensor * rope_factors = build_rope_factors(il);
  9864. // compute Q and K and RoPE them
  9865. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9866. cb(Qcur, "Qcur", il);
  9867. if (model.layers[il].bq) {
  9868. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9869. cb(Qcur, "Qcur", il);
  9870. }
  9871. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9872. cb(Kcur, "Kcur", il);
  9873. if (model.layers[il].bk) {
  9874. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9875. cb(Kcur, "Kcur", il);
  9876. }
  9877. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9878. cb(Vcur, "Vcur", il);
  9879. if (model.layers[il].bv) {
  9880. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9881. cb(Vcur, "Vcur", il);
  9882. }
  9883. Qcur = ggml_rope_ext(
  9884. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  9885. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9886. ext_factor, attn_factor, beta_fast, beta_slow
  9887. );
  9888. cb(Qcur, "Qcur", il);
  9889. Kcur = ggml_rope_ext(
  9890. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  9891. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9892. ext_factor, attn_factor, beta_fast, beta_slow
  9893. );
  9894. cb(Kcur, "Kcur", il);
  9895. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9896. model.layers[il].wo, model.layers[il].bo,
  9897. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9898. if (il == n_layer - 1) {
  9899. // skip computing output for unused tokens
  9900. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9901. n_tokens = n_outputs;
  9902. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9903. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9904. }
  9905. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9906. cb(ffn_inp, "ffn_inp", il);
  9907. // feed-forward network
  9908. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9909. model.layers[il].ffn_norm, NULL,
  9910. LLM_NORM_RMS, cb, il);
  9911. cb(cur, "ffn_norm", il);
  9912. cur = llm_build_ffn(ctx0, lctx, cur,
  9913. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9914. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  9915. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9916. NULL,
  9917. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9918. cb(cur, "ffn_out", il);
  9919. cur = ggml_add(ctx0, cur, ffn_inp);
  9920. cb(cur, "ffn_out", il);
  9921. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9922. cb(cur, "l_out", il);
  9923. // input for next layer
  9924. inpL = cur;
  9925. }
  9926. }
  9927. cur = inpL;
  9928. cur = llm_build_norm(ctx0, cur, hparams,
  9929. model.output_norm, NULL,
  9930. LLM_NORM_RMS, cb, -1);
  9931. cb(cur, "result_norm", -1);
  9932. // lm_head
  9933. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9934. cb(cur, "result_output", -1);
  9935. ggml_build_forward_expand(gf, cur);
  9936. return gf;
  9937. }
  9938. struct ggml_cgraph * build_baichuan() {
  9939. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9940. const int64_t n_embd_head = hparams.n_embd_head_v;
  9941. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9942. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9943. struct ggml_tensor * cur;
  9944. struct ggml_tensor * inpL;
  9945. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  9946. // inp_pos - contains the positions
  9947. struct ggml_tensor * inp_pos = model.type == MODEL_7B ? build_inp_pos() : nullptr;
  9948. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9949. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9950. for (int il = 0; il < n_layer; ++il) {
  9951. struct ggml_tensor * inpSA = inpL;
  9952. cur = llm_build_norm(ctx0, inpL, hparams,
  9953. model.layers[il].attn_norm, NULL,
  9954. LLM_NORM_RMS, cb, il);
  9955. cb(cur, "attn_norm", il);
  9956. // self-attention
  9957. {
  9958. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9959. cb(Qcur, "Qcur", il);
  9960. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9961. cb(Kcur, "Kcur", il);
  9962. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9963. cb(Vcur, "Vcur", il);
  9964. switch (model.type) {
  9965. case MODEL_7B:
  9966. Qcur = ggml_rope_ext(
  9967. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9968. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9969. ext_factor, attn_factor, beta_fast, beta_slow
  9970. );
  9971. Kcur = ggml_rope_ext(
  9972. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9973. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9974. ext_factor, attn_factor, beta_fast, beta_slow
  9975. );
  9976. break;
  9977. case MODEL_13B:
  9978. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  9979. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  9980. break;
  9981. default:
  9982. GGML_ABORT("fatal error");
  9983. }
  9984. cb(Qcur, "Qcur", il);
  9985. cb(Kcur, "Kcur", il);
  9986. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9987. model.layers[il].wo, NULL,
  9988. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9989. }
  9990. if (il == n_layer - 1) {
  9991. // skip computing output for unused tokens
  9992. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9993. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9994. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9995. }
  9996. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9997. cb(ffn_inp, "ffn_inp", il);
  9998. // feed-forward network
  9999. {
  10000. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10001. model.layers[il].ffn_norm, NULL,
  10002. LLM_NORM_RMS, cb, il);
  10003. cb(cur, "ffn_norm", il);
  10004. cur = llm_build_ffn(ctx0, lctx, cur,
  10005. model.layers[il].ffn_up, NULL, NULL,
  10006. model.layers[il].ffn_gate, NULL, NULL,
  10007. model.layers[il].ffn_down, NULL, NULL,
  10008. NULL,
  10009. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10010. cb(cur, "ffn_out", il);
  10011. }
  10012. cur = ggml_add(ctx0, cur, ffn_inp);
  10013. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10014. cb(cur, "l_out", il);
  10015. // input for next layer
  10016. inpL = cur;
  10017. }
  10018. cur = inpL;
  10019. cur = llm_build_norm(ctx0, cur, hparams,
  10020. model.output_norm, NULL,
  10021. LLM_NORM_RMS, cb, -1);
  10022. cb(cur, "result_norm", -1);
  10023. // lm_head
  10024. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10025. cb(cur, "result_output", -1);
  10026. ggml_build_forward_expand(gf, cur);
  10027. return gf;
  10028. }
  10029. struct ggml_cgraph * build_xverse() {
  10030. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10031. const int64_t n_embd_head = hparams.n_embd_head_v;
  10032. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10033. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10034. struct ggml_tensor * cur;
  10035. struct ggml_tensor * inpL;
  10036. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10037. // inp_pos - contains the positions
  10038. struct ggml_tensor * inp_pos = build_inp_pos();
  10039. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10040. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10041. for (int il = 0; il < n_layer; ++il) {
  10042. struct ggml_tensor * inpSA = inpL;
  10043. cur = llm_build_norm(ctx0, inpL, hparams,
  10044. model.layers[il].attn_norm, NULL,
  10045. LLM_NORM_RMS, cb, il);
  10046. cb(cur, "attn_norm", il);
  10047. // self-attention
  10048. {
  10049. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10050. cb(Qcur, "Qcur", il);
  10051. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10052. cb(Kcur, "Kcur", il);
  10053. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10054. cb(Vcur, "Vcur", il);
  10055. Qcur = ggml_rope_ext(
  10056. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10057. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10058. ext_factor, attn_factor, beta_fast, beta_slow
  10059. );
  10060. cb(Qcur, "Qcur", il);
  10061. Kcur = ggml_rope_ext(
  10062. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10063. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10064. ext_factor, attn_factor, beta_fast, beta_slow
  10065. );
  10066. cb(Kcur, "Kcur", il);
  10067. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10068. model.layers[il].wo, NULL,
  10069. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10070. }
  10071. if (il == n_layer - 1) {
  10072. // skip computing output for unused tokens
  10073. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10074. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10075. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10076. }
  10077. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10078. cb(ffn_inp, "ffn_inp", il);
  10079. // feed-forward network
  10080. {
  10081. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10082. model.layers[il].ffn_norm, NULL,
  10083. LLM_NORM_RMS, cb, il);
  10084. cb(cur, "ffn_norm", il);
  10085. cur = llm_build_ffn(ctx0, lctx, cur,
  10086. model.layers[il].ffn_up, NULL, NULL,
  10087. model.layers[il].ffn_gate, NULL, NULL,
  10088. model.layers[il].ffn_down, NULL, NULL,
  10089. NULL,
  10090. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10091. cb(cur, "ffn_out", il);
  10092. }
  10093. cur = ggml_add(ctx0, cur, ffn_inp);
  10094. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10095. cb(cur, "l_out", il);
  10096. // input for next layer
  10097. inpL = cur;
  10098. }
  10099. cur = inpL;
  10100. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, NULL, LLM_NORM_RMS, cb, -1);
  10101. cb(cur, "result_norm", -1);
  10102. // lm_head
  10103. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10104. cb(cur, "result_output", -1);
  10105. ggml_build_forward_expand(gf, cur);
  10106. return gf;
  10107. }
  10108. struct ggml_cgraph * build_falcon() {
  10109. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10110. const int64_t n_embd_head = hparams.n_embd_head_v;
  10111. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10112. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10113. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10114. struct ggml_tensor * cur;
  10115. struct ggml_tensor * inpL;
  10116. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10117. // inp_pos - contains the positions
  10118. struct ggml_tensor * inp_pos = build_inp_pos();
  10119. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10120. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10121. for (int il = 0; il < n_layer; ++il) {
  10122. struct ggml_tensor * attn_norm;
  10123. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  10124. model.layers[il].attn_norm,
  10125. model.layers[il].attn_norm_b,
  10126. LLM_NORM, cb, il);
  10127. cb(attn_norm, "attn_norm", il);
  10128. // self-attention
  10129. {
  10130. if (model.layers[il].attn_norm_2) {
  10131. // Falcon-40B
  10132. cur = llm_build_norm(ctx0, inpL, hparams,
  10133. model.layers[il].attn_norm_2,
  10134. model.layers[il].attn_norm_2_b,
  10135. LLM_NORM, cb, il);
  10136. cb(cur, "attn_norm_2", il);
  10137. } else {
  10138. cur = attn_norm;
  10139. }
  10140. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10141. cb(cur, "wqkv", il);
  10142. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10143. 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)));
  10144. 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)));
  10145. cb(Qcur, "Qcur", il);
  10146. cb(Kcur, "Kcur", il);
  10147. cb(Vcur, "Vcur", il);
  10148. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10149. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10150. // using mode = 2 for neox mode
  10151. Qcur = ggml_rope_ext(
  10152. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  10153. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  10154. );
  10155. cb(Qcur, "Qcur", il);
  10156. Kcur = ggml_rope_ext(
  10157. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  10158. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  10159. );
  10160. cb(Kcur, "Kcur", il);
  10161. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10162. model.layers[il].wo, NULL,
  10163. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10164. }
  10165. if (il == n_layer - 1) {
  10166. // skip computing output for unused tokens
  10167. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10168. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10169. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10170. attn_norm = ggml_get_rows(ctx0, attn_norm, inp_out_ids);
  10171. }
  10172. struct ggml_tensor * ffn_inp = cur;
  10173. // feed forward
  10174. {
  10175. cur = llm_build_ffn(ctx0, lctx, attn_norm, // !! use the attn norm, not the result
  10176. model.layers[il].ffn_up, NULL, NULL,
  10177. NULL, NULL, NULL,
  10178. model.layers[il].ffn_down, NULL, NULL,
  10179. NULL,
  10180. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10181. cb(cur, "ffn_out", il);
  10182. }
  10183. cur = ggml_add(ctx0, cur, ffn_inp);
  10184. cur = ggml_add(ctx0, cur, inpL);
  10185. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10186. cb(cur, "l_out", il);
  10187. // input for next layer
  10188. inpL = cur;
  10189. }
  10190. cur = inpL;
  10191. // norm
  10192. cur = llm_build_norm(ctx0, cur, hparams,
  10193. model.output_norm,
  10194. model.output_norm_b,
  10195. LLM_NORM, cb, -1);
  10196. cb(cur, "result_norm", -1);
  10197. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10198. cb(cur, "result_output", -1);
  10199. ggml_build_forward_expand(gf, cur);
  10200. return gf;
  10201. }
  10202. struct ggml_cgraph * build_grok() {
  10203. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10204. // mutable variable, needed during the last layer of the computation to skip unused tokens
  10205. int32_t n_tokens = this->n_tokens;
  10206. const int64_t n_embd_head = hparams.n_embd_head_v;
  10207. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10208. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10209. struct ggml_tensor * cur;
  10210. struct ggml_tensor * inpL;
  10211. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10212. // multiply by embedding_multiplier_scale of 78.38367176906169
  10213. inpL = ggml_scale(ctx0, inpL, 78.38367176906169f);
  10214. // inp_pos - contains the positions
  10215. struct ggml_tensor * inp_pos = build_inp_pos();
  10216. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10217. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10218. for (int il = 0; il < n_layer; ++il) {
  10219. struct ggml_tensor * inpSA = inpL;
  10220. // norm
  10221. cur = llm_build_norm(ctx0, inpL, hparams,
  10222. model.layers[il].attn_norm, NULL,
  10223. LLM_NORM_RMS, cb, il);
  10224. cb(cur, "attn_norm", il);
  10225. // self-attention
  10226. {
  10227. // compute Q and K and RoPE them
  10228. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10229. cb(Qcur, "Qcur", il);
  10230. if (model.layers[il].bq) {
  10231. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10232. cb(Qcur, "Qcur", il);
  10233. }
  10234. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10235. cb(Kcur, "Kcur", il);
  10236. if (model.layers[il].bk) {
  10237. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10238. cb(Kcur, "Kcur", il);
  10239. }
  10240. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10241. cb(Vcur, "Vcur", il);
  10242. if (model.layers[il].bv) {
  10243. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  10244. cb(Vcur, "Vcur", il);
  10245. }
  10246. Qcur = ggml_rope_ext(
  10247. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10248. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10249. ext_factor, attn_factor, beta_fast, beta_slow
  10250. );
  10251. cb(Qcur, "Qcur", il);
  10252. Kcur = ggml_rope_ext(
  10253. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10254. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10255. ext_factor, attn_factor, beta_fast, beta_slow
  10256. );
  10257. cb(Kcur, "Kcur", il);
  10258. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10259. model.layers[il].wo, model.layers[il].bo,
  10260. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  10261. }
  10262. if (il == n_layer - 1) {
  10263. // skip computing output for unused tokens
  10264. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10265. n_tokens = n_outputs;
  10266. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10267. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10268. }
  10269. // Grok
  10270. // if attn_out_norm is present then apply it before adding the input
  10271. if (model.layers[il].attn_out_norm) {
  10272. cur = llm_build_norm(ctx0, cur, hparams,
  10273. model.layers[il].attn_out_norm, NULL,
  10274. LLM_NORM_RMS, cb, il);
  10275. cb(cur, "attn_out_norm", il);
  10276. }
  10277. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10278. cb(ffn_inp, "ffn_inp", il);
  10279. // feed-forward network
  10280. // MoE branch
  10281. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10282. model.layers[il].ffn_norm, NULL,
  10283. LLM_NORM_RMS, cb, il);
  10284. cb(cur, "ffn_norm", il);
  10285. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  10286. model.layers[il].ffn_gate_inp,
  10287. model.layers[il].ffn_up_exps,
  10288. model.layers[il].ffn_gate_exps,
  10289. model.layers[il].ffn_down_exps,
  10290. n_expert, n_expert_used,
  10291. LLM_FFN_GELU, true,
  10292. false, 0.0,
  10293. cb, il);
  10294. cb(cur, "ffn_moe_out", il);
  10295. // Grok
  10296. // if layer_out_norm is present then apply it before adding the input
  10297. // Idea: maybe ffn_out_norm is a better name
  10298. if (model.layers[il].layer_out_norm) {
  10299. cur = llm_build_norm(ctx0, cur, hparams,
  10300. model.layers[il].layer_out_norm, NULL,
  10301. LLM_NORM_RMS, cb, il);
  10302. cb(cur, "layer_out_norm", il);
  10303. }
  10304. cur = ggml_add(ctx0, cur, ffn_inp);
  10305. cb(cur, "ffn_out", il);
  10306. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10307. cb(cur, "l_out", il);
  10308. // input for next layer
  10309. inpL = cur;
  10310. }
  10311. cur = inpL;
  10312. cur = llm_build_norm(ctx0, cur, hparams,
  10313. model.output_norm, NULL,
  10314. LLM_NORM_RMS, cb, -1);
  10315. cb(cur, "result_norm", -1);
  10316. // lm_head
  10317. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10318. // Grok
  10319. // multiply logits by output_multiplier_scale of 0.5773502691896257
  10320. cur = ggml_scale(ctx0, cur, 0.5773502691896257f);
  10321. cb(cur, "result_output", -1);
  10322. ggml_build_forward_expand(gf, cur);
  10323. return gf;
  10324. }
  10325. struct ggml_cgraph * build_dbrx() {
  10326. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10327. // mutable variable, needed during the last layer of the computation to skip unused tokens
  10328. int32_t n_tokens = this->n_tokens;
  10329. const int64_t n_embd_head = hparams.n_embd_head_v;
  10330. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10331. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10332. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10333. struct ggml_tensor * cur;
  10334. struct ggml_tensor * inpL;
  10335. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10336. // inp_pos - contains the positions
  10337. struct ggml_tensor * inp_pos = build_inp_pos();
  10338. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10339. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10340. for (int il = 0; il < n_layer; ++il) {
  10341. struct ggml_tensor * inpSA = inpL;
  10342. // norm
  10343. cur = llm_build_norm(ctx0, inpL, hparams,
  10344. model.layers[il].attn_norm, NULL,
  10345. LLM_NORM, cb, il);
  10346. cb(cur, "attn_norm", il);
  10347. // self-attention
  10348. {
  10349. struct ggml_tensor * Qcur = nullptr;
  10350. struct ggml_tensor * Kcur = nullptr;
  10351. struct ggml_tensor * Vcur = nullptr;
  10352. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10353. cb(cur, "wqkv", il);
  10354. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  10355. cb(cur, "wqkv_clamped", il);
  10356. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10357. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  10358. 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)));
  10359. cb(Qcur, "Qcur", il);
  10360. cb(Kcur, "Kcur", il);
  10361. cb(Vcur, "Vcur", il);
  10362. Qcur = ggml_rope_ext(
  10363. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10364. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10365. ext_factor, attn_factor, beta_fast, beta_slow
  10366. );
  10367. cb(Qcur, "Qcur", il);
  10368. Kcur = ggml_rope_ext(
  10369. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10370. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10371. ext_factor, attn_factor, beta_fast, beta_slow
  10372. );
  10373. cb(Kcur, "Kcur", il);
  10374. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10375. model.layers[il].wo, NULL,
  10376. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10377. }
  10378. if (il == n_layer - 1) {
  10379. // skip computing output for unused tokens
  10380. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10381. n_tokens = n_outputs;
  10382. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10383. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10384. }
  10385. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10386. cb(ffn_inp, "ffn_inp", il);
  10387. // feed-forward network
  10388. // MoE branch
  10389. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10390. model.layers[il].attn_out_norm, NULL,
  10391. LLM_NORM, cb, il);
  10392. cb(cur, "attn_out_norm", il);
  10393. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  10394. model.layers[il].ffn_gate_inp,
  10395. model.layers[il].ffn_up_exps,
  10396. model.layers[il].ffn_gate_exps,
  10397. model.layers[il].ffn_down_exps,
  10398. n_expert, n_expert_used,
  10399. LLM_FFN_SILU, true,
  10400. false, 0.0,
  10401. cb, il);
  10402. cb(cur, "ffn_moe_out", il);
  10403. cur = ggml_add(ctx0, cur, ffn_inp);
  10404. cb(cur, "ffn_out", il);
  10405. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10406. cb(cur, "l_out", il);
  10407. // input for next layer
  10408. inpL = cur;
  10409. }
  10410. cur = inpL;
  10411. cur = llm_build_norm(ctx0, cur, hparams,
  10412. model.output_norm, NULL,
  10413. LLM_NORM, cb, -1);
  10414. cb(cur, "result_norm", -1);
  10415. // lm_head
  10416. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10417. cb(cur, "result_output", -1);
  10418. ggml_build_forward_expand(gf, cur);
  10419. return gf;
  10420. }
  10421. struct ggml_cgraph * build_starcoder() {
  10422. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10423. const int64_t n_embd_head = hparams.n_embd_head_v;
  10424. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10425. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10426. struct ggml_tensor * cur;
  10427. struct ggml_tensor * inpL;
  10428. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10429. // inp_pos - contains the positions
  10430. struct ggml_tensor * inp_pos = build_inp_pos();
  10431. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10432. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10433. struct ggml_tensor * pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  10434. cb(pos, "pos_embd", -1);
  10435. inpL = ggml_add(ctx0, inpL, pos);
  10436. cb(inpL, "inpL", -1);
  10437. for (int il = 0; il < n_layer; ++il) {
  10438. cur = llm_build_norm(ctx0, inpL, hparams,
  10439. model.layers[il].attn_norm,
  10440. model.layers[il].attn_norm_b,
  10441. LLM_NORM, cb, il);
  10442. cb(cur, "attn_norm", il);
  10443. // self-attention
  10444. {
  10445. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10446. cb(cur, "wqkv", il);
  10447. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10448. cb(cur, "bqkv", il);
  10449. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10450. 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)));
  10451. 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)));
  10452. cb(Qcur, "Qcur", il);
  10453. cb(Kcur, "Kcur", il);
  10454. cb(Vcur, "Vcur", il);
  10455. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10456. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10457. model.layers[il].wo, model.layers[il].bo,
  10458. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10459. }
  10460. if (il == n_layer - 1) {
  10461. // skip computing output for unused tokens
  10462. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10463. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10464. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10465. }
  10466. // add the input
  10467. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10468. cb(ffn_inp, "ffn_inp", il);
  10469. // FF
  10470. {
  10471. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10472. model.layers[il].ffn_norm,
  10473. model.layers[il].ffn_norm_b,
  10474. LLM_NORM, cb, il);
  10475. cb(cur, "ffn_norm", il);
  10476. cur = llm_build_ffn(ctx0, lctx, cur,
  10477. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10478. NULL, NULL, NULL,
  10479. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10480. NULL,
  10481. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10482. cb(cur, "ffn_out", il);
  10483. }
  10484. cur = ggml_add(ctx0, cur, ffn_inp);
  10485. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10486. cb(cur, "l_out", il);
  10487. // input for next layer
  10488. inpL = cur;
  10489. }
  10490. cur = llm_build_norm(ctx0, inpL, hparams,
  10491. model.output_norm,
  10492. model.output_norm_b,
  10493. LLM_NORM, cb, -1);
  10494. cb(cur, "result_norm", -1);
  10495. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10496. cb(cur, "result_output", -1);
  10497. ggml_build_forward_expand(gf, cur);
  10498. return gf;
  10499. }
  10500. struct ggml_cgraph * build_refact() {
  10501. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10502. const int64_t n_embd_head = hparams.n_embd_head_v;
  10503. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10504. struct ggml_tensor * cur;
  10505. struct ggml_tensor * inpL;
  10506. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10507. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10508. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10509. for (int il = 0; il < n_layer; ++il) {
  10510. struct ggml_tensor * inpSA = inpL;
  10511. cur = llm_build_norm(ctx0, inpL, hparams,
  10512. model.layers[il].attn_norm, NULL,
  10513. LLM_NORM_RMS, cb, il);
  10514. cb(cur, "attn_norm", il);
  10515. // self-attention
  10516. {
  10517. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10518. cb(Qcur, "Qcur", il);
  10519. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10520. cb(Kcur, "Kcur", il);
  10521. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10522. cb(Vcur, "Vcur", il);
  10523. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10524. cb(Kcur, "Kcur", il);
  10525. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10526. cb(Qcur, "Qcur", il);
  10527. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10528. model.layers[il].wo, NULL,
  10529. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10530. }
  10531. if (il == n_layer - 1) {
  10532. // skip computing output for unused tokens
  10533. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10534. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10535. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10536. }
  10537. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10538. cb(ffn_inp, "ffn_inp", il);
  10539. // feed-forward network
  10540. {
  10541. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10542. model.layers[il].ffn_norm, NULL,
  10543. LLM_NORM_RMS, cb, il);
  10544. cb(cur, "ffn_norm", il);
  10545. cur = llm_build_ffn(ctx0, lctx, cur,
  10546. model.layers[il].ffn_up, NULL, NULL,
  10547. model.layers[il].ffn_gate, NULL, NULL,
  10548. model.layers[il].ffn_down, NULL, NULL,
  10549. NULL,
  10550. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10551. cb(cur, "ffn_out", il);
  10552. }
  10553. cur = ggml_add(ctx0, cur, ffn_inp);
  10554. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10555. cb(cur, "l_out", il);
  10556. // input for next layer
  10557. inpL = cur;
  10558. }
  10559. cur = inpL;
  10560. cur = llm_build_norm(ctx0, cur, hparams,
  10561. model.output_norm, NULL,
  10562. LLM_NORM_RMS, cb, -1);
  10563. cb(cur, "result_norm", -1);
  10564. // lm_head
  10565. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10566. cb(cur, "result_output", -1);
  10567. ggml_build_forward_expand(gf, cur);
  10568. return gf;
  10569. }
  10570. struct ggml_cgraph * build_bert() {
  10571. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10572. const int64_t n_embd_head = hparams.n_embd_head_v;
  10573. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10574. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10575. struct ggml_tensor * cur;
  10576. struct ggml_tensor * inpL;
  10577. struct ggml_tensor * inp_pos = nullptr;
  10578. if (model.arch != LLM_ARCH_JINA_BERT_V2) {
  10579. inp_pos = build_inp_pos();
  10580. }
  10581. // construct input embeddings (token, type, position)
  10582. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10583. // token types are hardcoded to zero ("Sentence A")
  10584. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  10585. inpL = ggml_add(ctx0, inpL, type_row0);
  10586. if (model.arch == LLM_ARCH_BERT) {
  10587. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  10588. }
  10589. cb(inpL, "inp_embd", -1);
  10590. // embed layer norm
  10591. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  10592. cb(inpL, "inp_norm", -1);
  10593. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10594. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(false);
  10595. // iterate layers
  10596. for (int il = 0; il < n_layer; ++il) {
  10597. struct ggml_tensor * cur = inpL;
  10598. struct ggml_tensor * Qcur;
  10599. struct ggml_tensor * Kcur;
  10600. struct ggml_tensor * Vcur;
  10601. // self-attention
  10602. if (model.arch == LLM_ARCH_BERT || model.arch == LLM_ARCH_JINA_BERT_V2) {
  10603. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  10604. cb(Qcur, "Qcur", il);
  10605. if (model.layers[il].attn_q_norm) {
  10606. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  10607. model.layers[il].attn_q_norm,
  10608. model.layers[il].attn_q_norm_b,
  10609. LLM_NORM, cb, il);
  10610. }
  10611. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  10612. cb(Kcur, "Kcur", il);
  10613. if (model.layers[il].attn_k_norm) {
  10614. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  10615. model.layers[il].attn_k_norm,
  10616. model.layers[il].attn_k_norm_b,
  10617. LLM_NORM, cb, il);
  10618. }
  10619. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  10620. cb(Vcur, "Vcur", il);
  10621. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10622. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10623. } else {
  10624. // compute Q and K and RoPE them
  10625. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10626. cb(cur, "wqkv", il);
  10627. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10628. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  10629. 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)));
  10630. cb(Qcur, "Qcur", il);
  10631. cb(Kcur, "Kcur", il);
  10632. cb(Vcur, "Vcur", il);
  10633. Qcur = ggml_rope_ext(
  10634. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10635. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10636. ext_factor, attn_factor, beta_fast, beta_slow
  10637. );
  10638. cb(Qcur, "Qcur", il);
  10639. Kcur = ggml_rope_ext(
  10640. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10641. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10642. ext_factor, attn_factor, beta_fast, beta_slow
  10643. );
  10644. cb(Kcur, "Kcur", il);
  10645. }
  10646. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  10647. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  10648. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  10649. cb(kq, "kq", il);
  10650. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask, 1.0f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  10651. cb(kq, "kq_soft_max_ext", il);
  10652. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  10653. cb(v, "v", il);
  10654. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  10655. cb(kqv, "kqv", il);
  10656. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  10657. cb(kqv_merged, "kqv_merged", il);
  10658. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  10659. cb(cur, "kqv_merged_cont", il);
  10660. ggml_build_forward_expand(gf, cur);
  10661. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  10662. if (model.layers[il].bo) {
  10663. cb(cur, "kqv_wo", il);
  10664. }
  10665. if (model.layers[il].bo) {
  10666. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  10667. }
  10668. cb(cur, "kqv_out", il);
  10669. if (il == n_layer - 1 && pooling_type == LLAMA_POOLING_TYPE_NONE) {
  10670. // skip computing output for unused tokens
  10671. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10672. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10673. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10674. }
  10675. // re-add the layer input
  10676. cur = ggml_add(ctx0, cur, inpL);
  10677. // attention layer norm
  10678. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  10679. if (model.layers[il].attn_norm_2 != nullptr) {
  10680. cur = ggml_add(ctx0, cur, inpL); // re-add the layer input
  10681. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_norm_2, model.layers[il].attn_norm_2_b, LLM_NORM, cb, il);
  10682. }
  10683. struct ggml_tensor * ffn_inp = cur;
  10684. cb(ffn_inp, "ffn_inp", il);
  10685. // feed-forward network
  10686. if (model.arch == LLM_ARCH_BERT) {
  10687. cur = llm_build_ffn(ctx0, lctx, cur,
  10688. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10689. NULL, NULL, NULL,
  10690. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10691. NULL,
  10692. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10693. } else if (model.arch == LLM_ARCH_JINA_BERT_V2) {
  10694. cur = llm_build_ffn(ctx0, lctx, cur,
  10695. model.layers[il].ffn_up, NULL, NULL,
  10696. model.layers[il].ffn_gate, NULL, NULL,
  10697. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10698. NULL,
  10699. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  10700. } else {
  10701. cur = llm_build_ffn(ctx0, lctx, cur,
  10702. model.layers[il].ffn_up, NULL, NULL,
  10703. model.layers[il].ffn_gate, NULL, NULL,
  10704. model.layers[il].ffn_down, NULL, NULL,
  10705. NULL,
  10706. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10707. }
  10708. cb(cur, "ffn_out", il);
  10709. // attentions bypass the intermediate layer
  10710. cur = ggml_add(ctx0, cur, ffn_inp);
  10711. // output layer norm
  10712. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  10713. // input for next layer
  10714. inpL = cur;
  10715. }
  10716. cur = inpL;
  10717. cb(cur, "result_embd", -1);
  10718. ggml_build_forward_expand(gf, cur);
  10719. return gf;
  10720. }
  10721. struct ggml_cgraph * build_bloom() {
  10722. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10723. const int64_t n_embd_head = hparams.n_embd_head_v;
  10724. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10725. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10726. struct ggml_tensor * cur;
  10727. struct ggml_tensor * inpL;
  10728. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10729. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10730. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10731. inpL = llm_build_norm(ctx0, inpL, hparams,
  10732. model.tok_norm,
  10733. model.tok_norm_b,
  10734. LLM_NORM, cb, -1);
  10735. cb(inpL, "inp_norm", -1);
  10736. for (int il = 0; il < n_layer; ++il) {
  10737. cur = llm_build_norm(ctx0, inpL, hparams,
  10738. model.layers[il].attn_norm,
  10739. model.layers[il].attn_norm_b,
  10740. LLM_NORM, cb, il);
  10741. cb(cur, "attn_norm", il);
  10742. // self-attention
  10743. {
  10744. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10745. cb(cur, "wqkv", il);
  10746. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10747. cb(cur, "bqkv", il);
  10748. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10749. 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)));
  10750. 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)));
  10751. cb(Qcur, "Qcur", il);
  10752. cb(Kcur, "Kcur", il);
  10753. cb(Vcur, "Vcur", il);
  10754. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10755. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10756. model.layers[il].wo, model.layers[il].bo,
  10757. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10758. }
  10759. if (il == n_layer - 1) {
  10760. // skip computing output for unused tokens
  10761. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10762. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10763. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10764. }
  10765. // Add the input
  10766. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10767. cb(ffn_inp, "ffn_inp", il);
  10768. // FF
  10769. {
  10770. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10771. model.layers[il].ffn_norm,
  10772. model.layers[il].ffn_norm_b,
  10773. LLM_NORM, cb, il);
  10774. cb(cur, "ffn_norm", il);
  10775. cur = llm_build_ffn(ctx0, lctx, cur,
  10776. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10777. NULL, NULL, NULL,
  10778. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10779. NULL,
  10780. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10781. cb(cur, "ffn_out", il);
  10782. }
  10783. cur = ggml_add(ctx0, cur, ffn_inp);
  10784. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10785. cb(cur, "l_out", il);
  10786. // input for next layer
  10787. inpL = cur;
  10788. }
  10789. cur = llm_build_norm(ctx0, inpL, hparams,
  10790. model.output_norm,
  10791. model.output_norm_b,
  10792. LLM_NORM, cb, -1);
  10793. cb(cur, "result_norm", -1);
  10794. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10795. cb(cur, "result_output", -1);
  10796. ggml_build_forward_expand(gf, cur);
  10797. return gf;
  10798. }
  10799. struct ggml_cgraph * build_mpt() {
  10800. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10801. const int64_t n_embd_head = hparams.n_embd_head_v;
  10802. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10803. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10804. struct ggml_tensor * cur;
  10805. struct ggml_tensor * pos;
  10806. struct ggml_tensor * inpL;
  10807. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10808. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10809. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10810. if (model.pos_embd) {
  10811. // inp_pos - contains the positions
  10812. struct ggml_tensor * inp_pos = build_inp_pos();
  10813. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  10814. cb(pos, "pos_embd", -1);
  10815. inpL = ggml_add(ctx0, inpL, pos);
  10816. cb(inpL, "inpL", -1);
  10817. }
  10818. for (int il = 0; il < n_layer; ++il) {
  10819. struct ggml_tensor * attn_norm;
  10820. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  10821. model.layers[il].attn_norm,
  10822. model.layers[il].attn_norm_b,
  10823. LLM_NORM, cb, il);
  10824. cb(attn_norm, "attn_norm", il);
  10825. // self-attention
  10826. {
  10827. cur = attn_norm;
  10828. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10829. cb(cur, "wqkv", il);
  10830. if (model.layers[il].bqkv){
  10831. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10832. cb(cur, "bqkv", il);
  10833. }
  10834. if (hparams.f_clamp_kqv > 0.0f) {
  10835. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  10836. cb(cur, "wqkv_clamped", il);
  10837. }
  10838. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10839. 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)));
  10840. 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)));
  10841. cb(Qcur, "Qcur", il);
  10842. cb(Kcur, "Kcur", il);
  10843. cb(Vcur, "Vcur", il);
  10844. // Q/K Layernorm
  10845. if (model.layers[il].attn_q_norm) {
  10846. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  10847. model.layers[il].attn_q_norm,
  10848. model.layers[il].attn_q_norm_b,
  10849. LLM_NORM, cb, il);
  10850. cb(Qcur, "Qcur", il);
  10851. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  10852. model.layers[il].attn_k_norm,
  10853. model.layers[il].attn_k_norm_b,
  10854. LLM_NORM, cb, il);
  10855. cb(Kcur, "Kcur", il);
  10856. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10857. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10858. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10859. model.layers[il].wo, model.layers[il].bo,
  10860. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10861. } else {
  10862. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10863. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10864. model.layers[il].wo, model.layers[il].bo,
  10865. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10866. }
  10867. }
  10868. if (il == n_layer - 1) {
  10869. // skip computing output for unused tokens
  10870. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10871. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10872. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10873. }
  10874. // Add the input
  10875. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10876. cb(ffn_inp, "ffn_inp", il);
  10877. // feed forward
  10878. {
  10879. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10880. model.layers[il].ffn_norm,
  10881. model.layers[il].ffn_norm_b,
  10882. LLM_NORM, cb, il);
  10883. cb(cur, "ffn_norm", il);
  10884. cur = llm_build_ffn(ctx0, lctx, cur,
  10885. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10886. NULL, NULL, NULL,
  10887. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10888. model.layers[il].ffn_act,
  10889. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10890. cb(cur, "ffn_out", il);
  10891. }
  10892. cur = ggml_add(ctx0, cur, ffn_inp);
  10893. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10894. cb(cur, "l_out", il);
  10895. // input for next layer
  10896. inpL = cur;
  10897. }
  10898. cur = inpL;
  10899. cur = llm_build_norm(ctx0, cur, hparams,
  10900. model.output_norm,
  10901. model.output_norm_b,
  10902. LLM_NORM, cb, -1);
  10903. cb(cur, "result_norm", -1);
  10904. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10905. cb(cur, "result_output", -1);
  10906. ggml_build_forward_expand(gf, cur);
  10907. return gf;
  10908. }
  10909. struct ggml_cgraph * build_stablelm() {
  10910. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  10911. const int64_t n_embd_head = hparams.n_embd_head_v;
  10912. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10913. struct ggml_tensor * cur;
  10914. struct ggml_tensor * inpL;
  10915. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10916. // inp_pos - contains the positions
  10917. struct ggml_tensor * inp_pos = build_inp_pos();
  10918. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10919. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10920. for (int il = 0; il < n_layer; ++il) {
  10921. // norm
  10922. cur = llm_build_norm(ctx0, inpL, hparams,
  10923. model.layers[il].attn_norm,
  10924. model.layers[il].attn_norm_b,
  10925. LLM_NORM, cb, il);
  10926. cb(cur, "attn_norm", il);
  10927. struct ggml_tensor * inpSA = cur;
  10928. // self-attention
  10929. {
  10930. // compute Q and K and RoPE them
  10931. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10932. cb(Qcur, "Qcur", il);
  10933. if (model.layers[il].bq) {
  10934. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10935. cb(Qcur, "Qcur", il);
  10936. }
  10937. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10938. cb(Kcur, "Kcur", il);
  10939. if (model.layers[il].bk) {
  10940. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10941. cb(Kcur, "Kcur", il);
  10942. }
  10943. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10944. cb(Vcur, "Vcur", il);
  10945. if (model.layers[il].bv) {
  10946. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  10947. cb(Vcur, "Vcur", il);
  10948. }
  10949. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10950. cb(Qcur, "Qcur", il);
  10951. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10952. cb(Kcur, "Kcur", il);
  10953. if (model.layers[il].attn_q_norm) {
  10954. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  10955. model.layers[il].attn_q_norm,
  10956. NULL,
  10957. LLM_NORM, cb, il);
  10958. cb(Qcur, "Qcur", il);
  10959. }
  10960. if (model.layers[il].attn_k_norm) {
  10961. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  10962. model.layers[il].attn_k_norm,
  10963. NULL,
  10964. LLM_NORM, cb, il);
  10965. cb(Kcur, "Kcur", il);
  10966. }
  10967. Qcur = ggml_rope_ext(
  10968. ctx0, Qcur, inp_pos, nullptr,
  10969. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10970. ext_factor, attn_factor, beta_fast, beta_slow
  10971. );
  10972. cb(Qcur, "Qcur", il);
  10973. Kcur = ggml_rope_ext(
  10974. ctx0, Kcur, inp_pos, nullptr,
  10975. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10976. ext_factor, attn_factor, beta_fast, beta_slow
  10977. );
  10978. cb(Kcur, "Kcur", il);
  10979. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10980. model.layers[il].wo, NULL,
  10981. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10982. }
  10983. if (il == n_layer - 1) {
  10984. // skip computing output for unused tokens
  10985. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10986. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10987. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10988. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10989. }
  10990. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10991. cb(ffn_inp, "ffn_inp", il);
  10992. // feed-forward network
  10993. {
  10994. if (model.layers[il].ffn_norm) {
  10995. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10996. model.layers[il].ffn_norm,
  10997. model.layers[il].ffn_norm_b,
  10998. LLM_NORM, cb, il);
  10999. cb(cur, "ffn_norm", il);
  11000. } else {
  11001. // parallel residual
  11002. cur = inpSA;
  11003. }
  11004. cur = llm_build_ffn(ctx0, lctx, cur,
  11005. model.layers[il].ffn_up, NULL, NULL,
  11006. model.layers[il].ffn_gate, NULL, NULL,
  11007. model.layers[il].ffn_down, NULL, NULL,
  11008. NULL,
  11009. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11010. cb(cur, "ffn_out", il);
  11011. }
  11012. cur = ggml_add(ctx0, cur, ffn_inp);
  11013. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11014. cb(cur, "l_out", il);
  11015. // input for next layer
  11016. inpL = cur;
  11017. }
  11018. cur = inpL;
  11019. cur = llm_build_norm(ctx0, cur, hparams,
  11020. model.output_norm,
  11021. model.output_norm_b,
  11022. LLM_NORM, cb, -1);
  11023. cb(cur, "result_norm", -1);
  11024. // lm_head
  11025. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11026. cb(cur, "result_output", -1);
  11027. ggml_build_forward_expand(gf, cur);
  11028. return gf;
  11029. }
  11030. struct ggml_cgraph * build_qwen() {
  11031. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11032. const int64_t n_embd_head = hparams.n_embd_head_v;
  11033. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11034. struct ggml_tensor * cur;
  11035. struct ggml_tensor * inpL;
  11036. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11037. // inp_pos - contains the positions
  11038. struct ggml_tensor * inp_pos = build_inp_pos();
  11039. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11040. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11041. for (int il = 0; il < n_layer; ++il) {
  11042. struct ggml_tensor * inpSA = inpL;
  11043. cur = llm_build_norm(ctx0, inpL, hparams,
  11044. model.layers[il].attn_norm, NULL,
  11045. LLM_NORM_RMS, cb, il);
  11046. cb(cur, "attn_norm", il);
  11047. // self-attention
  11048. {
  11049. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  11050. cb(cur, "wqkv", il);
  11051. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  11052. cb(cur, "bqkv", il);
  11053. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  11054. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  11055. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  11056. cb(Qcur, "Qcur", il);
  11057. cb(Kcur, "Kcur", il);
  11058. cb(Vcur, "Vcur", il);
  11059. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11060. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  11061. // using mode = 2 for neox mode
  11062. Qcur = ggml_rope_ext(
  11063. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  11064. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  11065. );
  11066. cb(Qcur, "Qcur", il);
  11067. Kcur = ggml_rope_ext(
  11068. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  11069. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  11070. );
  11071. cb(Kcur, "Kcur", il);
  11072. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11073. model.layers[il].wo, NULL,
  11074. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11075. }
  11076. if (il == n_layer - 1) {
  11077. // skip computing output for unused tokens
  11078. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11079. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11080. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11081. }
  11082. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11083. cb(ffn_inp, "ffn_inp", il);
  11084. // feed-forward forward
  11085. {
  11086. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11087. model.layers[il].ffn_norm, NULL,
  11088. LLM_NORM_RMS, cb, il);
  11089. cb(cur, "ffn_norm", il);
  11090. cur = llm_build_ffn(ctx0, lctx, cur,
  11091. model.layers[il].ffn_up, NULL, NULL,
  11092. model.layers[il].ffn_gate, NULL, NULL,
  11093. model.layers[il].ffn_down, NULL, NULL,
  11094. NULL,
  11095. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11096. cb(cur, "ffn_out", il);
  11097. }
  11098. cur = ggml_add(ctx0, cur, ffn_inp);
  11099. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11100. cb(cur, "l_out", il);
  11101. // input for next layer
  11102. inpL = cur;
  11103. }
  11104. cur = inpL;
  11105. cur = llm_build_norm(ctx0, cur, hparams,
  11106. model.output_norm, NULL,
  11107. LLM_NORM_RMS, cb, -1);
  11108. cb(cur, "result_norm", -1);
  11109. // lm_head
  11110. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11111. cb(cur, "result_output", -1);
  11112. ggml_build_forward_expand(gf, cur);
  11113. return gf;
  11114. }
  11115. struct ggml_cgraph * build_qwen2() {
  11116. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11117. const int64_t n_embd_head = hparams.n_embd_head_v;
  11118. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11119. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11120. struct ggml_tensor * cur;
  11121. struct ggml_tensor * inpL;
  11122. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11123. // inp_pos - contains the positions
  11124. struct ggml_tensor * inp_pos = build_inp_pos();
  11125. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11126. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11127. for (int il = 0; il < n_layer; ++il) {
  11128. struct ggml_tensor * inpSA = inpL;
  11129. // norm
  11130. cur = llm_build_norm(ctx0, inpL, hparams,
  11131. model.layers[il].attn_norm, NULL,
  11132. LLM_NORM_RMS, cb, il);
  11133. cb(cur, "attn_norm", il);
  11134. // self-attention
  11135. {
  11136. // compute Q and K and RoPE them
  11137. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11138. cb(Qcur, "Qcur", il);
  11139. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  11140. cb(Qcur, "Qcur", il);
  11141. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11142. cb(Kcur, "Kcur", il);
  11143. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  11144. cb(Kcur, "Kcur", il);
  11145. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11146. cb(Vcur, "Vcur", il);
  11147. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11148. cb(Vcur, "Vcur", il);
  11149. Qcur = ggml_rope_ext(
  11150. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11151. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11152. ext_factor, attn_factor, beta_fast, beta_slow
  11153. );
  11154. cb(Qcur, "Qcur", il);
  11155. Kcur = ggml_rope_ext(
  11156. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11157. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11158. ext_factor, attn_factor, beta_fast, beta_slow
  11159. );
  11160. cb(Kcur, "Kcur", il);
  11161. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11162. model.layers[il].wo, model.layers[il].bo,
  11163. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11164. }
  11165. if (il == n_layer - 1) {
  11166. // skip computing output for unused tokens
  11167. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11168. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11169. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11170. }
  11171. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11172. cb(ffn_inp, "ffn_inp", il);
  11173. // feed-forward network
  11174. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11175. model.layers[il].ffn_norm, NULL,
  11176. LLM_NORM_RMS, cb, il);
  11177. cb(cur, "ffn_norm", il);
  11178. cur = llm_build_ffn(ctx0, lctx, cur,
  11179. model.layers[il].ffn_up, NULL, NULL,
  11180. model.layers[il].ffn_gate, NULL, NULL,
  11181. model.layers[il].ffn_down, NULL, NULL,
  11182. NULL,
  11183. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11184. cb(cur, "ffn_out", il);
  11185. cur = ggml_add(ctx0, cur, ffn_inp);
  11186. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11187. cb(cur, "l_out", il);
  11188. // input for next layer
  11189. inpL = cur;
  11190. }
  11191. cur = inpL;
  11192. cur = llm_build_norm(ctx0, cur, hparams,
  11193. model.output_norm, NULL,
  11194. LLM_NORM_RMS, cb, -1);
  11195. cb(cur, "result_norm", -1);
  11196. // lm_head
  11197. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11198. cb(cur, "result_output", -1);
  11199. ggml_build_forward_expand(gf, cur);
  11200. return gf;
  11201. }
  11202. struct ggml_cgraph * build_qwen2vl() {
  11203. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11204. const int64_t n_embd_head = hparams.n_embd_head_v;
  11205. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11206. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11207. struct ggml_tensor * cur;
  11208. struct ggml_tensor * inpL;
  11209. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11210. // inp_pos - contains the positions
  11211. lctx.inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens * 4);
  11212. cb(lctx.inp_pos, "inp_pos", -1);
  11213. ggml_set_input(lctx.inp_pos);
  11214. struct ggml_tensor * inp_pos = lctx.inp_pos;
  11215. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11216. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11217. int sections[4];
  11218. std::copy(std::begin(hparams.rope_sections), std::begin(hparams.rope_sections) + 4, sections);
  11219. for (int il = 0; il < n_layer; ++il) {
  11220. struct ggml_tensor * inpSA = inpL;
  11221. // norm
  11222. cur = llm_build_norm(ctx0, inpL, hparams,
  11223. model.layers[il].attn_norm, NULL,
  11224. LLM_NORM_RMS, cb, il);
  11225. cb(cur, "attn_norm", il);
  11226. // self-attention
  11227. {
  11228. // compute Q and K and RoPE them
  11229. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11230. cb(Qcur, "Qcur", il);
  11231. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  11232. cb(Qcur, "Qcur", il);
  11233. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11234. cb(Kcur, "Kcur", il);
  11235. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  11236. cb(Kcur, "Kcur", il);
  11237. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11238. cb(Vcur, "Vcur", il);
  11239. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11240. cb(Vcur, "Vcur", il);
  11241. Qcur = ggml_rope_multi(
  11242. ctx0,
  11243. ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11244. n_rot, sections, rope_type, n_ctx_orig, freq_base, freq_scale,
  11245. ext_factor, attn_factor, beta_fast, beta_slow
  11246. );
  11247. cb(Qcur, "Qcur", il);
  11248. Kcur = ggml_rope_multi(
  11249. ctx0,
  11250. ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11251. n_rot, sections, rope_type, n_ctx_orig, freq_base, freq_scale,
  11252. ext_factor, attn_factor, beta_fast, beta_slow
  11253. );
  11254. cb(Kcur, "Kcur", il);
  11255. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11256. model.layers[il].wo, model.layers[il].bo,
  11257. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11258. }
  11259. if (il == n_layer - 1) {
  11260. // skip computing output for unused tokens
  11261. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11262. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11263. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11264. }
  11265. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11266. cb(ffn_inp, "ffn_inp", il);
  11267. // feed-forward network
  11268. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11269. model.layers[il].ffn_norm, NULL,
  11270. LLM_NORM_RMS, cb, il);
  11271. cb(cur, "ffn_norm", il);
  11272. cur = llm_build_ffn(ctx0, lctx, cur,
  11273. model.layers[il].ffn_up, NULL, NULL,
  11274. model.layers[il].ffn_gate, NULL, NULL,
  11275. model.layers[il].ffn_down, NULL, NULL,
  11276. NULL,
  11277. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11278. cb(cur, "ffn_out", il);
  11279. cur = ggml_add(ctx0, cur, ffn_inp);
  11280. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11281. cb(cur, "l_out", il);
  11282. // input for next layer
  11283. inpL = cur;
  11284. }
  11285. cur = inpL;
  11286. cur = llm_build_norm(ctx0, cur, hparams,
  11287. model.output_norm, NULL,
  11288. LLM_NORM_RMS, cb, -1);
  11289. cb(cur, "result_norm", -1);
  11290. // lm_head
  11291. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11292. cb(cur, "result_output", -1);
  11293. ggml_build_forward_expand(gf, cur);
  11294. return gf;
  11295. }
  11296. struct ggml_cgraph * build_qwen2moe() {
  11297. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11298. // mutable variable, needed during the last layer of the computation to skip unused tokens
  11299. int32_t n_tokens = this->n_tokens;
  11300. const int64_t n_embd_head = hparams.n_embd_head_v;
  11301. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11302. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11303. struct ggml_tensor * cur;
  11304. struct ggml_tensor * inpL;
  11305. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11306. // inp_pos - contains the positions
  11307. struct ggml_tensor * inp_pos = build_inp_pos();
  11308. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11309. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11310. for (int il = 0; il < n_layer; ++il) {
  11311. struct ggml_tensor * inpSA = inpL;
  11312. // norm
  11313. cur = llm_build_norm(ctx0, inpL, hparams,
  11314. model.layers[il].attn_norm, NULL,
  11315. LLM_NORM_RMS, cb, il);
  11316. cb(cur, "attn_norm", il);
  11317. // self_attention
  11318. {
  11319. // compute Q and K and RoPE them
  11320. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11321. cb(Qcur, "Qcur", il);
  11322. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  11323. cb(Qcur, "Qcur", il);
  11324. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11325. cb(Kcur, "Kcur", il);
  11326. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  11327. cb(Kcur, "Kcur", il);
  11328. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11329. cb(Vcur, "Vcur", il);
  11330. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11331. cb(Vcur, "Vcur", il);
  11332. Qcur = ggml_rope_ext(
  11333. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11334. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11335. ext_factor, attn_factor, beta_fast, beta_slow
  11336. );
  11337. cb(Qcur, "Qcur", il);
  11338. Kcur = ggml_rope_ext(
  11339. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11340. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11341. ext_factor, attn_factor, beta_fast, beta_slow
  11342. );
  11343. cb(Kcur, "Kcur", il);
  11344. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11345. model.layers[il].wo, model.layers[il].bo,
  11346. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11347. }
  11348. if (il == n_layer - 1) {
  11349. // skip computing output for unused tokens
  11350. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11351. n_tokens = n_outputs;
  11352. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11353. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11354. }
  11355. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11356. cb(ffn_inp, "ffn_inp", il);
  11357. // MoE branch
  11358. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11359. model.layers[il].ffn_norm, NULL,
  11360. LLM_NORM_RMS, cb, il);
  11361. cb(cur, "ffn_norm", il);
  11362. ggml_tensor * moe_out =
  11363. llm_build_moe_ffn(ctx0, lctx, cur,
  11364. model.layers[il].ffn_gate_inp,
  11365. model.layers[il].ffn_up_exps,
  11366. model.layers[il].ffn_gate_exps,
  11367. model.layers[il].ffn_down_exps,
  11368. n_expert, n_expert_used,
  11369. LLM_FFN_SILU, false,
  11370. false, 0.0,
  11371. cb, il);
  11372. cb(cur, "ffn_moe_out", il);
  11373. // FFN shared expert
  11374. {
  11375. ggml_tensor * cur_gate_inp = llm_build_lora_mm(lctx, ctx0, model.layers[il].ffn_gate_inp_shexp, cur);
  11376. cb(cur_gate_inp, "ffn_shexp_gate_inp", il);
  11377. // sigmoid
  11378. ggml_tensor * cur_gate = ggml_div(ctx0, ggml_silu(ctx0, cur_gate_inp), cur_gate_inp);
  11379. cb(cur_gate, "ffn_shexp_gate", il);
  11380. ggml_tensor * cur_ffn = llm_build_ffn(ctx0, lctx, cur,
  11381. model.layers[il].ffn_up_shexp, NULL, NULL,
  11382. model.layers[il].ffn_gate_shexp, NULL, NULL,
  11383. model.layers[il].ffn_down_shexp, NULL, NULL,
  11384. NULL,
  11385. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11386. cb(cur_ffn, "ffn_shexp", il);
  11387. ggml_tensor * ffn_shexp_out = ggml_mul(ctx0, cur_ffn, cur_gate);
  11388. cb(ffn_shexp_out, "ffn_shexp_out", il);
  11389. moe_out = ggml_add(ctx0, moe_out, ffn_shexp_out);
  11390. cb(moe_out, "ffn_out", il);
  11391. cur = moe_out;
  11392. }
  11393. cur = ggml_add(ctx0, cur, ffn_inp);
  11394. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11395. cb(cur, "l_out", il);
  11396. // input for next layer
  11397. inpL = cur;
  11398. }
  11399. cur = inpL;
  11400. cur = llm_build_norm(ctx0, cur, hparams,
  11401. model.output_norm, NULL,
  11402. LLM_NORM_RMS, cb, -1);
  11403. cb(cur, "result_norm", -1);
  11404. // lm_head
  11405. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11406. cb(cur, "result_output", -1);
  11407. ggml_build_forward_expand(gf, cur);
  11408. return gf;
  11409. }
  11410. struct ggml_cgraph * build_phi2() {
  11411. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11412. const int64_t n_embd_head = hparams.n_embd_head_v;
  11413. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11414. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11415. struct ggml_tensor * cur;
  11416. struct ggml_tensor * attn_norm_output;
  11417. struct ggml_tensor * ffn_output;
  11418. struct ggml_tensor * inpL;
  11419. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11420. // inp_pos - contains the positions
  11421. struct ggml_tensor * inp_pos = build_inp_pos();
  11422. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11423. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11424. for (int il = 0; il < n_layer; ++il) {
  11425. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  11426. model.layers[il].attn_norm,
  11427. model.layers[il].attn_norm_b,
  11428. LLM_NORM, cb, il);
  11429. cb(attn_norm_output, "attn_norm", il);
  11430. // self-attention
  11431. {
  11432. struct ggml_tensor * Qcur = nullptr;
  11433. struct ggml_tensor * Kcur = nullptr;
  11434. struct ggml_tensor * Vcur = nullptr;
  11435. if (model.layers[il].wqkv) {
  11436. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, attn_norm_output);
  11437. cb(cur, "wqkv", il);
  11438. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  11439. cb(cur, "bqkv", il);
  11440. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  11441. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  11442. 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)));
  11443. } else {
  11444. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  11445. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  11446. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  11447. }
  11448. cb(Qcur, "Qcur", il);
  11449. cb(Kcur, "Kcur", il);
  11450. cb(Vcur, "Vcur", il);
  11451. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11452. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  11453. Qcur = ggml_rope_ext(
  11454. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  11455. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  11456. );
  11457. cb(Qcur, "Qcur", il);
  11458. // with phi2, we scale the Q to avoid precision issues
  11459. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  11460. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  11461. cb(Qcur, "Qcur", il);
  11462. Kcur = ggml_rope_ext(
  11463. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  11464. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  11465. );
  11466. cb(Kcur, "Kcur", il);
  11467. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11468. model.layers[il].wo, model.layers[il].bo,
  11469. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  11470. }
  11471. if (il == n_layer - 1) {
  11472. // skip computing output for unused tokens
  11473. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11474. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11475. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11476. attn_norm_output = ggml_get_rows(ctx0, attn_norm_output, inp_out_ids);
  11477. }
  11478. // FF
  11479. {
  11480. ffn_output = llm_build_ffn(ctx0, lctx, attn_norm_output,
  11481. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  11482. NULL, NULL, NULL,
  11483. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  11484. NULL,
  11485. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  11486. cb(ffn_output, "ffn_out", il);
  11487. }
  11488. cur = ggml_add(ctx0, cur, ffn_output);
  11489. cur = ggml_add(ctx0, cur, inpL);
  11490. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11491. cb(cur, "l_out", il);
  11492. // input for next layer
  11493. inpL = cur;
  11494. }
  11495. cur = llm_build_norm(ctx0, inpL, hparams,
  11496. model.output_norm,
  11497. model.output_norm_b,
  11498. LLM_NORM, cb, -1);
  11499. cb(cur, "result_norm", -1);
  11500. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11501. cb(cur, "result_output_no_bias", -1);
  11502. cur = ggml_add(ctx0, cur, model.output_b);
  11503. cb(cur, "result_output", -1);
  11504. ggml_build_forward_expand(gf, cur);
  11505. return gf;
  11506. }
  11507. struct ggml_cgraph * build_phi3() {
  11508. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11509. const int64_t n_embd_head = hparams.n_embd_head_v;
  11510. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11511. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11512. struct ggml_tensor * cur;
  11513. struct ggml_tensor * inpL;
  11514. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11515. // inp_pos - contains the positions
  11516. struct ggml_tensor * inp_pos = build_inp_pos();
  11517. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11518. struct ggml_tensor * KQ_mask_swa = build_inp_KQ_mask_swa();
  11519. for (int il = 0; il < n_layer; ++il) {
  11520. auto residual = inpL;
  11521. // self-attention
  11522. {
  11523. // rope freq factors for 128k context
  11524. struct ggml_tensor * rope_factors = build_rope_factors(il);
  11525. struct ggml_tensor* attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  11526. model.layers[il].attn_norm,
  11527. NULL,
  11528. LLM_NORM_RMS, cb, il);
  11529. cb(attn_norm_output, "attn_norm", il);
  11530. struct ggml_tensor * Qcur = nullptr;
  11531. struct ggml_tensor * Kcur = nullptr;
  11532. struct ggml_tensor * Vcur = nullptr;
  11533. if (model.layers[il].wqkv) {
  11534. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, attn_norm_output);
  11535. cb(cur, "wqkv", il);
  11536. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0 * sizeof(float) * (n_embd)));
  11537. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1 * sizeof(float) * (n_embd)));
  11538. 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)));
  11539. }
  11540. else {
  11541. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  11542. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  11543. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  11544. }
  11545. cb(Qcur, "Qcur", il);
  11546. cb(Kcur, "Kcur", il);
  11547. cb(Vcur, "Vcur", il);
  11548. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11549. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  11550. Qcur = ggml_rope_ext(
  11551. ctx0, Qcur, inp_pos, rope_factors, n_rot, rope_type, n_ctx_orig,
  11552. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  11553. );
  11554. cb(Qcur, "Qcur", il);
  11555. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head)));
  11556. cb(Qcur, "Qcur", il);
  11557. Kcur = ggml_rope_ext(
  11558. ctx0, Kcur, inp_pos, rope_factors, n_rot, rope_type, n_ctx_orig,
  11559. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  11560. );
  11561. cb(Kcur, "Kcur", il);
  11562. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11563. model.layers[il].wo, model.layers[il].bo,
  11564. Kcur, Vcur, Qcur, KQ_mask_swa, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  11565. }
  11566. if (il == n_layer - 1) {
  11567. // skip computing output for unused tokens
  11568. struct ggml_tensor* inp_out_ids = build_inp_out_ids();
  11569. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11570. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  11571. }
  11572. cur = ggml_add(ctx0, cur, residual);
  11573. residual = cur;
  11574. cur = llm_build_norm(ctx0, cur, hparams,
  11575. model.layers[il].ffn_norm, NULL,
  11576. LLM_NORM_RMS, cb, il);
  11577. cb(cur, "ffn_norm", il);
  11578. // FF
  11579. // special-case: the up and gate tensors are merged into a single tensor
  11580. // TOOD: support into llm_build_ffn
  11581. {
  11582. cur = llm_build_ffn(ctx0, lctx, cur,
  11583. model.layers[il].ffn_up, NULL, NULL,
  11584. NULL, NULL, NULL,
  11585. model.layers[il].ffn_down, NULL, NULL,
  11586. NULL,
  11587. LLM_FFN_SWIGLU, LLM_FFN_SEQ, cb, il);
  11588. cb(cur, "ffn_out", il);
  11589. }
  11590. cur = ggml_add(ctx0, residual, cur);
  11591. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11592. cb(cur, "l_out", il);
  11593. // input for next layer
  11594. inpL = cur;
  11595. }
  11596. cur = llm_build_norm(ctx0, inpL, hparams,
  11597. model.output_norm,
  11598. NULL,
  11599. LLM_NORM_RMS, cb, -1);
  11600. cb(cur, "result_norm", -1);
  11601. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11602. cb(cur, "result_output", -1);
  11603. ggml_build_forward_expand(gf, cur);
  11604. return gf;
  11605. }
  11606. struct ggml_cgraph * build_plamo() {
  11607. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  11608. const int64_t n_embd_head = hparams.n_embd_head_v;
  11609. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11610. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11611. struct ggml_tensor * cur;
  11612. struct ggml_tensor * inpL;
  11613. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11614. // inp_pos - contains the positions
  11615. struct ggml_tensor * inp_pos = build_inp_pos();
  11616. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11617. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11618. for (int il = 0; il < n_layer; ++il) {
  11619. // norm
  11620. cur = llm_build_norm(ctx0, inpL, hparams,
  11621. model.layers[il].attn_norm, NULL,
  11622. LLM_NORM_RMS, cb, il);
  11623. cb(cur, "attn_norm", il);
  11624. struct ggml_tensor * attention_norm = cur;
  11625. // self-attention
  11626. {
  11627. // compute Q and K and RoPE them
  11628. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11629. cb(Qcur, "Qcur", il);
  11630. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11631. cb(Kcur, "Kcur", il);
  11632. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11633. cb(Vcur, "Vcur", il);
  11634. Qcur = ggml_rope_ext(
  11635. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos, nullptr,
  11636. n_embd_head, rope_type, n_ctx_orig, freq_base, freq_scale,
  11637. ext_factor, attn_factor, beta_fast, beta_slow);
  11638. cb(Qcur, "Qcur", il);
  11639. Kcur = ggml_rope_ext(
  11640. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos, nullptr,
  11641. n_embd_head, rope_type, n_ctx_orig, freq_base, freq_scale,
  11642. ext_factor, attn_factor, beta_fast, beta_slow);
  11643. cb(Kcur, "Kcur", il);
  11644. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11645. model.layers[il].wo, NULL,
  11646. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11647. }
  11648. struct ggml_tensor * sa_out = cur;
  11649. cur = attention_norm;
  11650. if (il == n_layer - 1) {
  11651. // skip computing output for unused tokens
  11652. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11653. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11654. sa_out = ggml_get_rows(ctx0, sa_out, inp_out_ids);
  11655. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11656. }
  11657. // feed-forward network
  11658. {
  11659. cur = llm_build_ffn(ctx0, lctx, cur,
  11660. model.layers[il].ffn_up, NULL, NULL,
  11661. model.layers[il].ffn_gate, NULL, NULL,
  11662. model.layers[il].ffn_down, NULL, NULL,
  11663. NULL,
  11664. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11665. cb(cur, "ffn_out", il);
  11666. }
  11667. cur = ggml_add(ctx0, cur, sa_out);
  11668. cur = ggml_add(ctx0, cur, inpL);
  11669. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11670. cb(cur, "l_out", il);
  11671. // input for next layer
  11672. inpL = cur;
  11673. }
  11674. cur = inpL;
  11675. cur = llm_build_norm(ctx0, cur, hparams,
  11676. model.output_norm, NULL,
  11677. LLM_NORM_RMS, cb, -1);
  11678. cb(cur, "result_norm", -1);
  11679. // lm_head
  11680. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11681. cb(cur, "result_output", -1);
  11682. ggml_build_forward_expand(gf, cur);
  11683. return gf;
  11684. }
  11685. struct ggml_cgraph * build_gpt2() {
  11686. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11687. const int64_t n_embd_head = hparams.n_embd_head_v;
  11688. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11689. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11690. struct ggml_tensor * cur;
  11691. struct ggml_tensor * pos;
  11692. struct ggml_tensor * inpL;
  11693. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11694. // inp_pos - contains the positions
  11695. struct ggml_tensor * inp_pos = build_inp_pos();
  11696. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11697. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11698. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  11699. cb(pos, "pos_embd", -1);
  11700. inpL = ggml_add(ctx0, inpL, pos);
  11701. cb(inpL, "inpL", -1);
  11702. for (int il = 0; il < n_layer; ++il) {
  11703. cur = llm_build_norm(ctx0, inpL, hparams,
  11704. model.layers[il].attn_norm,
  11705. model.layers[il].attn_norm_b,
  11706. LLM_NORM, cb, il);
  11707. cb(cur, "attn_norm", il);
  11708. // self-attention
  11709. {
  11710. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  11711. cb(cur, "wqkv", il);
  11712. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  11713. cb(cur, "bqkv", il);
  11714. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  11715. 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)));
  11716. 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)));
  11717. cb(Qcur, "Qcur", il);
  11718. cb(Kcur, "Kcur", il);
  11719. cb(Vcur, "Vcur", il);
  11720. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11721. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11722. model.layers[il].wo, model.layers[il].bo,
  11723. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11724. }
  11725. if (il == n_layer - 1) {
  11726. // skip computing output for unused tokens
  11727. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11728. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11729. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11730. }
  11731. // add the input
  11732. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  11733. cb(ffn_inp, "ffn_inp", il);
  11734. // FF
  11735. {
  11736. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11737. model.layers[il].ffn_norm,
  11738. model.layers[il].ffn_norm_b,
  11739. LLM_NORM, cb, il);
  11740. cb(cur, "ffn_norm", il);
  11741. cur = llm_build_ffn(ctx0, lctx, cur,
  11742. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  11743. NULL, NULL, NULL,
  11744. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  11745. NULL,
  11746. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  11747. cb(cur, "ffn_out", il);
  11748. }
  11749. cur = ggml_add(ctx0, cur, ffn_inp);
  11750. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11751. cb(cur, "l_out", il);
  11752. // input for next layer
  11753. inpL = cur;
  11754. }
  11755. cur = llm_build_norm(ctx0, inpL, hparams,
  11756. model.output_norm,
  11757. model.output_norm_b,
  11758. LLM_NORM, cb, -1);
  11759. cb(cur, "result_norm", -1);
  11760. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11761. cb(cur, "result_output", -1);
  11762. ggml_build_forward_expand(gf, cur);
  11763. return gf;
  11764. }
  11765. struct ggml_cgraph * build_codeshell() {
  11766. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11767. const int64_t n_embd_head = hparams.n_embd_head_v;
  11768. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11769. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11770. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11771. struct ggml_tensor * cur;
  11772. struct ggml_tensor * inpL;
  11773. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11774. // inp_pos - contains the positions
  11775. struct ggml_tensor * inp_pos = build_inp_pos();
  11776. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11777. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11778. for (int il = 0; il < n_layer; ++il) {
  11779. cur = llm_build_norm(ctx0, inpL, hparams,
  11780. model.layers[il].attn_norm,
  11781. model.layers[il].attn_norm_b,
  11782. LLM_NORM, cb, il);
  11783. cb(cur, "attn_norm", il);
  11784. // self-attention
  11785. {
  11786. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  11787. cb(cur, "wqkv", il);
  11788. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  11789. cb(cur, "bqkv", il);
  11790. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  11791. 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)));
  11792. 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)));
  11793. cb(tmpq, "tmpq", il);
  11794. cb(tmpk, "tmpk", il);
  11795. cb(Vcur, "Vcur", il);
  11796. struct ggml_tensor * Qcur = ggml_rope_ext(
  11797. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11798. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11799. ext_factor, attn_factor, beta_fast, beta_slow
  11800. );
  11801. cb(Qcur, "Qcur", il);
  11802. struct ggml_tensor * Kcur = ggml_rope_ext(
  11803. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11804. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11805. ext_factor, attn_factor, beta_fast, beta_slow
  11806. );
  11807. cb(Kcur, "Kcur", il);
  11808. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11809. model.layers[il].wo, model.layers[il].bo,
  11810. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11811. }
  11812. if (il == n_layer - 1) {
  11813. // skip computing output for unused tokens
  11814. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11815. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11816. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11817. }
  11818. // add the input
  11819. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  11820. cb(ffn_inp, "ffn_inp", il);
  11821. // FF
  11822. {
  11823. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11824. model.layers[il].ffn_norm,
  11825. model.layers[il].ffn_norm_b,
  11826. LLM_NORM, cb, il);
  11827. cb(cur, "ffn_norm", il);
  11828. cur = llm_build_ffn(ctx0, lctx, cur,
  11829. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  11830. NULL, NULL, NULL,
  11831. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  11832. NULL,
  11833. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  11834. cb(cur, "ffn_out", il);
  11835. }
  11836. cur = ggml_add(ctx0, cur, ffn_inp);
  11837. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11838. cb(cur, "l_out", il);
  11839. // input for next layer
  11840. inpL = cur;
  11841. }
  11842. cur = llm_build_norm(ctx0, inpL, hparams,
  11843. model.output_norm,
  11844. model.output_norm_b,
  11845. LLM_NORM, cb, -1);
  11846. cb(cur, "result_norm", -1);
  11847. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11848. cb(cur, "result_output", -1);
  11849. ggml_build_forward_expand(gf, cur);
  11850. return gf;
  11851. }
  11852. struct ggml_cgraph * build_orion() {
  11853. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11854. const int64_t n_embd_head = hparams.n_embd_head_v;
  11855. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11856. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11857. struct ggml_tensor * cur;
  11858. struct ggml_tensor * inpL;
  11859. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11860. // inp_pos - contains the positions
  11861. struct ggml_tensor * inp_pos = build_inp_pos();
  11862. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11863. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11864. for (int il = 0; il < n_layer; ++il) {
  11865. struct ggml_tensor * inpSA = inpL;
  11866. // norm
  11867. cur = llm_build_norm(ctx0, inpL, hparams,
  11868. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  11869. LLM_NORM, cb, il);
  11870. cb(cur, "attn_norm", il);
  11871. // self-attention
  11872. {
  11873. // compute Q and K and RoPE them
  11874. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11875. cb(Qcur, "Qcur", il);
  11876. // if (model.layers[il].bq) {
  11877. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  11878. // cb(Qcur, "Qcur", il);
  11879. // }
  11880. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11881. cb(Kcur, "Kcur", il);
  11882. // if (model.layers[il].bk) {
  11883. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  11884. // cb(Kcur, "Kcur", il);
  11885. // }
  11886. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11887. cb(Vcur, "Vcur", il);
  11888. // if (model.layers[il].bv) {
  11889. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11890. // cb(Vcur, "Vcur", il);
  11891. // }
  11892. Qcur = ggml_rope_ext(
  11893. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11894. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11895. ext_factor, attn_factor, beta_fast, beta_slow
  11896. );
  11897. cb(Qcur, "Qcur", il);
  11898. Kcur = ggml_rope_ext(
  11899. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11900. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11901. ext_factor, attn_factor, beta_fast, beta_slow
  11902. );
  11903. cb(Kcur, "Kcur", il);
  11904. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11905. model.layers[il].wo, NULL,
  11906. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11907. }
  11908. if (il == n_layer - 1) {
  11909. // skip computing output for unused tokens
  11910. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11911. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11912. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11913. }
  11914. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11915. cb(ffn_inp, "ffn_inp", il);
  11916. // feed-forward network
  11917. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11918. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  11919. LLM_NORM, cb, il);
  11920. cb(cur, "ffn_norm", il);
  11921. cur = llm_build_ffn(ctx0, lctx, cur,
  11922. model.layers[il].ffn_up, NULL, NULL,
  11923. model.layers[il].ffn_gate, NULL, NULL,
  11924. model.layers[il].ffn_down, NULL, NULL,
  11925. NULL,
  11926. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11927. cb(cur, "ffn_out", il);
  11928. cur = ggml_add(ctx0, cur, ffn_inp);
  11929. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11930. cb(cur, "l_out", il);
  11931. // input for next layer
  11932. inpL = cur;
  11933. }
  11934. cur = inpL;
  11935. cur = llm_build_norm(ctx0, cur, hparams,
  11936. model.output_norm, model.output_norm_b,
  11937. LLM_NORM, cb, -1);
  11938. cb(cur, "result_norm", -1);
  11939. // lm_head
  11940. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11941. cb(cur, "result_output", -1);
  11942. ggml_build_forward_expand(gf, cur);
  11943. return gf;
  11944. }
  11945. struct ggml_cgraph * build_internlm2() {
  11946. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11947. const int64_t n_embd_head = hparams.n_embd_head_v;
  11948. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11949. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11950. struct ggml_tensor * cur;
  11951. struct ggml_tensor * inpL;
  11952. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11953. // inp_pos - contains the positions
  11954. struct ggml_tensor * inp_pos = build_inp_pos();
  11955. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11956. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11957. for (int il = 0; il < n_layer; ++il) {
  11958. struct ggml_tensor * inpSA = inpL;
  11959. // norm
  11960. cur = llm_build_norm(ctx0, inpL, hparams,
  11961. model.layers[il].attn_norm, NULL,
  11962. LLM_NORM_RMS, cb, il);
  11963. cb(cur, "attn_norm", il);
  11964. // self-attention
  11965. {
  11966. // compute Q and K and RoPE them
  11967. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11968. cb(Qcur, "Qcur", il);
  11969. if (model.layers[il].bq) {
  11970. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  11971. cb(Qcur, "Qcur", il);
  11972. }
  11973. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11974. cb(Kcur, "Kcur", il);
  11975. if (model.layers[il].bk) {
  11976. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  11977. cb(Kcur, "Kcur", il);
  11978. }
  11979. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11980. cb(Vcur, "Vcur", il);
  11981. if (model.layers[il].bv) {
  11982. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11983. cb(Vcur, "Vcur", il);
  11984. }
  11985. Qcur = ggml_rope_ext(
  11986. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11987. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11988. ext_factor, attn_factor, beta_fast, beta_slow
  11989. );
  11990. cb(Qcur, "Qcur", il);
  11991. Kcur = ggml_rope_ext(
  11992. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11993. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11994. ext_factor, attn_factor, beta_fast, beta_slow
  11995. );
  11996. cb(Kcur, "Kcur", il);
  11997. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11998. model.layers[il].wo, model.layers[il].bo,
  11999. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12000. }
  12001. if (il == n_layer - 1) {
  12002. // skip computing output for unused tokens
  12003. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12004. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12005. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12006. }
  12007. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12008. cb(ffn_inp, "ffn_inp", il);
  12009. // feed-forward network
  12010. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12011. model.layers[il].ffn_norm, NULL,
  12012. LLM_NORM_RMS, cb, il);
  12013. cb(cur, "ffn_norm", il);
  12014. cur = llm_build_ffn(ctx0, lctx, cur,
  12015. model.layers[il].ffn_up, NULL, NULL,
  12016. model.layers[il].ffn_gate, NULL, NULL,
  12017. model.layers[il].ffn_down, NULL, NULL,
  12018. NULL,
  12019. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12020. cb(cur, "ffn_out", il);
  12021. cur = ggml_add(ctx0, cur, ffn_inp);
  12022. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12023. cb(cur, "l_out", il);
  12024. // input for next layer
  12025. inpL = cur;
  12026. }
  12027. cur = inpL;
  12028. cur = llm_build_norm(ctx0, cur, hparams,
  12029. model.output_norm, NULL,
  12030. LLM_NORM_RMS, cb, -1);
  12031. cb(cur, "result_norm", -1);
  12032. // lm_head
  12033. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12034. cb(cur, "result_output", -1);
  12035. ggml_build_forward_expand(gf, cur);
  12036. return gf;
  12037. }
  12038. struct ggml_cgraph * build_minicpm3() {
  12039. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12040. //TODO: if the model varies, these parameters need to be read from the model
  12041. const int64_t n_embd_base = 256;
  12042. const float scale_embd = 12.0f;
  12043. const float scale_depth = 1.4f;
  12044. const float kq_scale = 1.0f / sqrtf(float(hparams.n_embd_head_k));
  12045. const uint32_t n_embd_head_qk_rope = hparams.n_rot;
  12046. const uint32_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  12047. const uint32_t kv_lora_rank = hparams.n_lora_kv;
  12048. struct ggml_tensor * cur;
  12049. struct ggml_tensor * inpL;
  12050. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12051. // scale the input embeddings
  12052. inpL = ggml_scale(ctx0, inpL, scale_embd);
  12053. cb(inpL, "inp_scaled", -1);
  12054. // inp_pos - contains the positions
  12055. struct ggml_tensor * inp_pos = build_inp_pos();
  12056. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12057. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12058. for (int il = 0; il < n_layer; ++il) {
  12059. struct ggml_tensor * inpSA = inpL;
  12060. struct ggml_tensor * rope_factors = build_rope_factors(il);
  12061. // norm
  12062. cur = llm_build_norm(ctx0, inpL, hparams,
  12063. model.layers[il].attn_norm, NULL,
  12064. LLM_NORM_RMS, cb, il);
  12065. cb(cur, "attn_norm", il);
  12066. // self_attention
  12067. {
  12068. struct ggml_tensor * q = NULL;
  12069. // {n_embd, q_lora_rank} * {n_embd, n_tokens} -> {q_lora_rank, n_tokens}
  12070. q = ggml_mul_mat(ctx0, model.layers[il].wq_a, cur);
  12071. cb(q, "q", il);
  12072. q = llm_build_norm(ctx0, q, hparams,
  12073. model.layers[il].attn_q_a_norm, NULL,
  12074. LLM_NORM_RMS, cb, il);
  12075. cb(q, "q", il);
  12076. // {q_lora_rank, n_head * hparams.n_embd_head_k} * {q_lora_rank, n_tokens} -> {n_head * hparams.n_embd_head_k, n_tokens}
  12077. q = ggml_mul_mat(ctx0, model.layers[il].wq_b, q);
  12078. cb(q, "q", il);
  12079. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  12080. struct ggml_tensor * q_nope = ggml_view_3d(ctx0, q, n_embd_head_qk_nope, n_head, n_tokens,
  12081. ggml_row_size(q->type, hparams.n_embd_head_k),
  12082. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  12083. 0);
  12084. cb(q_nope, "q_nope", il);
  12085. // and {n_head * n_embd_head_qk_rope, n_tokens}
  12086. struct ggml_tensor * q_pe = ggml_view_3d(ctx0, q, n_embd_head_qk_rope, n_head, n_tokens,
  12087. ggml_row_size(q->type, hparams.n_embd_head_k),
  12088. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  12089. ggml_row_size(q->type, n_embd_head_qk_nope));
  12090. cb(q_pe, "q_pe", il);
  12091. // {n_embd, kv_lora_rank + n_embd_head_qk_rope} * {n_embd, n_tokens} -> {kv_lora_rank + n_embd_head_qk_rope, n_tokens}
  12092. struct ggml_tensor * kv_pe_compresseed = ggml_mul_mat(ctx0, model.layers[il].wkv_a_mqa, cur);
  12093. cb(kv_pe_compresseed, "kv_pe_compresseed", il);
  12094. // split into {kv_lora_rank, n_tokens}
  12095. struct ggml_tensor * kv_compressed = ggml_view_2d(ctx0, kv_pe_compresseed, kv_lora_rank, n_tokens,
  12096. kv_pe_compresseed->nb[1],
  12097. 0);
  12098. cb(kv_compressed, "kv_compressed", il);
  12099. // and {n_embd_head_qk_rope, n_tokens}
  12100. struct ggml_tensor * k_pe = ggml_view_3d(ctx0, kv_pe_compresseed, n_embd_head_qk_rope, 1, n_tokens,
  12101. kv_pe_compresseed->nb[1],
  12102. kv_pe_compresseed->nb[1],
  12103. ggml_row_size(kv_pe_compresseed->type, kv_lora_rank));
  12104. cb(k_pe, "k_pe", il);
  12105. kv_compressed = ggml_cont(ctx0, kv_compressed); // TODO: the CUDA backend does not support non-contiguous norm
  12106. kv_compressed = llm_build_norm(ctx0, kv_compressed, hparams,
  12107. model.layers[il].attn_kv_a_norm, NULL,
  12108. LLM_NORM_RMS, cb, il);
  12109. cb(kv_compressed, "kv_compressed", il);
  12110. // {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}
  12111. struct ggml_tensor * kv = ggml_mul_mat(ctx0, model.layers[il].wkv_b, kv_compressed);
  12112. cb(kv, "kv", il);
  12113. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  12114. struct ggml_tensor * k_nope = ggml_view_3d(ctx0, kv, n_embd_head_qk_nope, n_head, n_tokens,
  12115. ggml_row_size(kv->type, n_embd_head_qk_nope + hparams.n_embd_head_v),
  12116. ggml_row_size(kv->type, n_head * (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  12117. 0);
  12118. cb(k_nope, "k_nope", il);
  12119. // and {n_head * n_embd_head_v, n_tokens}
  12120. struct ggml_tensor * v_states = ggml_view_3d(ctx0, kv, hparams.n_embd_head_v, n_head, n_tokens,
  12121. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  12122. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)*n_head),
  12123. ggml_row_size(kv->type, (n_embd_head_qk_nope)));
  12124. cb(v_states, "v_states", il);
  12125. v_states = ggml_cont(ctx0, v_states);
  12126. cb(v_states, "v_states", il);
  12127. v_states = ggml_view_2d(ctx0, v_states, hparams.n_embd_head_v * n_head, n_tokens,
  12128. ggml_row_size(kv->type, hparams.n_embd_head_v * n_head),
  12129. 0);
  12130. cb(v_states, "v_states", il);
  12131. q_pe = ggml_cont(ctx0, q_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  12132. q_pe = ggml_rope_ext(
  12133. ctx0, q_pe, inp_pos, rope_factors,
  12134. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12135. ext_factor, attn_factor, beta_fast, beta_slow
  12136. );
  12137. cb(q_pe, "q_pe", il);
  12138. // shared RoPE key
  12139. k_pe = ggml_cont(ctx0, k_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  12140. k_pe = ggml_rope_ext(
  12141. ctx0, k_pe, inp_pos, rope_factors,
  12142. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12143. ext_factor, attn_factor, beta_fast, beta_slow
  12144. );
  12145. cb(k_pe, "k_pe", il);
  12146. struct ggml_tensor * q_states = ggml_concat(ctx0, q_nope, q_pe, 0);
  12147. cb(q_states, "q_states", il);
  12148. struct ggml_tensor * k_states = ggml_concat(ctx0, k_nope, ggml_repeat(ctx0, k_pe, q_pe), 0);
  12149. cb(k_states, "k_states", il);
  12150. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12151. model.layers[il].wo, NULL,
  12152. k_states, v_states, q_states, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  12153. }
  12154. if (il == n_layer - 1) {
  12155. // skip computing output for unused tokens
  12156. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12157. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12158. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12159. }
  12160. // scale_res - scale the hidden states for residual connection
  12161. const float scale_res = scale_depth/sqrtf(float(n_layer));
  12162. cur = ggml_scale(ctx0, cur, scale_res);
  12163. cb(cur, "hidden_scaled", il);
  12164. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12165. cb(ffn_inp, "ffn_inp", il);
  12166. // feed-forward network
  12167. {
  12168. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12169. model.layers[il].ffn_norm, NULL,
  12170. LLM_NORM_RMS, cb, il);
  12171. cb(cur, "ffn_norm", il);
  12172. cur = llm_build_ffn(ctx0, lctx, cur,
  12173. model.layers[il].ffn_up, NULL, NULL,
  12174. model.layers[il].ffn_gate, NULL, NULL,
  12175. model.layers[il].ffn_down, NULL, NULL,
  12176. NULL,
  12177. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12178. cb(cur, "ffn_out", il);
  12179. }
  12180. // scale the hidden states for residual connection
  12181. cur = ggml_scale(ctx0, cur, scale_res);
  12182. cb(cur, "hidden_scaled_ffn", il);
  12183. cur = ggml_add(ctx0, cur, ffn_inp);
  12184. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12185. cb(cur, "l_out", il);
  12186. // input for next layer
  12187. inpL = cur;
  12188. }
  12189. cur = inpL;
  12190. cur = llm_build_norm(ctx0, cur, hparams,
  12191. model.output_norm, NULL,
  12192. LLM_NORM_RMS, cb, -1);
  12193. cb(cur, "result_norm", -1);
  12194. // lm_head scaling
  12195. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  12196. cur = ggml_scale(ctx0, cur, scale_lmhead);
  12197. cb(cur, "lmhead_scaling", -1);
  12198. // lm_head
  12199. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12200. cb(cur, "result_output", -1);
  12201. ggml_build_forward_expand(gf, cur);
  12202. return gf;
  12203. }
  12204. struct ggml_cgraph * build_gemma() {
  12205. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12206. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  12207. struct ggml_tensor * cur;
  12208. struct ggml_tensor * inpL;
  12209. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12210. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  12211. cb(inpL, "inp_scaled", -1);
  12212. // inp_pos - contains the positions
  12213. struct ggml_tensor * inp_pos = build_inp_pos();
  12214. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12215. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12216. for (int il = 0; il < n_layer; ++il) {
  12217. // norm
  12218. cur = llm_build_norm(ctx0, inpL, hparams,
  12219. model.layers[il].attn_norm, NULL,
  12220. LLM_NORM_RMS, cb, il);
  12221. cb(cur, "attn_norm", il);
  12222. // self-attention
  12223. {
  12224. // compute Q and K and RoPE them
  12225. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12226. cb(Qcur, "Qcur", il);
  12227. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12228. cb(Kcur, "Kcur", il);
  12229. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12230. cb(Vcur, "Vcur", il);
  12231. Qcur = ggml_rope_ext(
  12232. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos, nullptr,
  12233. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12234. ext_factor, attn_factor, beta_fast, beta_slow);
  12235. cb(Qcur, "Qcur", il);
  12236. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  12237. cb(Qcur, "Qcur_scaled", il);
  12238. Kcur = ggml_rope_ext(
  12239. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos, nullptr,
  12240. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12241. ext_factor, attn_factor, beta_fast, beta_slow);
  12242. cb(Kcur, "Kcur", il);
  12243. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12244. model.layers[il].wo, NULL,
  12245. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  12246. }
  12247. if (il == n_layer - 1) {
  12248. // skip computing output for unused tokens
  12249. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12250. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12251. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  12252. }
  12253. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  12254. cb(sa_out, "sa_out", il);
  12255. cur = llm_build_norm(ctx0, sa_out, hparams,
  12256. model.layers[il].ffn_norm, NULL,
  12257. LLM_NORM_RMS, cb, il);
  12258. cb(cur, "ffn_norm", il);
  12259. // feed-forward network
  12260. {
  12261. cur = llm_build_ffn(ctx0, lctx, cur,
  12262. model.layers[il].ffn_up, NULL, NULL,
  12263. model.layers[il].ffn_gate, NULL, NULL,
  12264. model.layers[il].ffn_down, NULL, NULL,
  12265. NULL,
  12266. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  12267. cb(cur, "ffn_out", il);
  12268. }
  12269. cur = ggml_add(ctx0, cur, sa_out);
  12270. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12271. cb(cur, "l_out", il);
  12272. // input for next layer
  12273. inpL = cur;
  12274. }
  12275. cur = inpL;
  12276. cur = llm_build_norm(ctx0, cur, hparams,
  12277. model.output_norm, NULL,
  12278. LLM_NORM_RMS, cb, -1);
  12279. cb(cur, "result_norm", -1);
  12280. // lm_head
  12281. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12282. cb(cur, "result_output", -1);
  12283. ggml_build_forward_expand(gf, cur);
  12284. return gf;
  12285. }
  12286. struct ggml_cgraph * build_gemma2() {
  12287. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12288. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  12289. struct ggml_tensor * cur;
  12290. struct ggml_tensor * inpL;
  12291. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12292. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  12293. cb(inpL, "inp_scaled", -1);
  12294. // inp_pos - contains the positions
  12295. struct ggml_tensor * inp_pos = build_inp_pos();
  12296. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12297. // gemma 2 requires different mask for layers using sliding window (SWA)
  12298. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(true);
  12299. struct ggml_tensor * KQ_mask_swa = build_inp_KQ_mask_swa(true);
  12300. for (int il = 0; il < n_layer; ++il) {
  12301. // (il % 2) layers use SWA
  12302. struct ggml_tensor * KQ_mask_l = (il % 2 == 0) ? KQ_mask_swa : KQ_mask;
  12303. // norm
  12304. cur = llm_build_norm(ctx0, inpL, hparams,
  12305. model.layers[il].attn_norm, NULL,
  12306. LLM_NORM_RMS, cb, il);
  12307. cb(cur, "attn_norm", il);
  12308. // self-attention
  12309. {
  12310. // compute Q and K and RoPE them
  12311. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12312. cb(Qcur, "Qcur", il);
  12313. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12314. cb(Kcur, "Kcur", il);
  12315. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12316. cb(Vcur, "Vcur", il);
  12317. Qcur = ggml_rope_ext(
  12318. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos, nullptr,
  12319. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12320. ext_factor, attn_factor, beta_fast, beta_slow);
  12321. cb(Qcur, "Qcur", il);
  12322. // ref: https://github.com/google/gemma_pytorch/commit/03e657582d17cb5a8617ebf333c1c16f3694670e
  12323. switch (model.type) {
  12324. case e_model::MODEL_2B:
  12325. case e_model::MODEL_9B: Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k))); break;
  12326. case e_model::MODEL_27B: Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd / n_head))); break;
  12327. default: GGML_ABORT("fatal error");
  12328. };
  12329. cb(Qcur, "Qcur_scaled", il);
  12330. Kcur = ggml_rope_ext(
  12331. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos, nullptr,
  12332. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12333. ext_factor, attn_factor, beta_fast, beta_slow);
  12334. cb(Kcur, "Kcur", il);
  12335. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12336. model.layers[il].wo, NULL,
  12337. Kcur, Vcur, Qcur, KQ_mask_l, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  12338. }
  12339. cur = llm_build_norm(ctx0, cur, hparams,
  12340. model.layers[il].attn_post_norm, NULL,
  12341. LLM_NORM_RMS, cb, il);
  12342. cb(cur, "attn_post_norm", il);
  12343. if (il == n_layer - 1) {
  12344. // skip computing output for unused tokens
  12345. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12346. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12347. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  12348. }
  12349. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  12350. cb(sa_out, "sa_out", il);
  12351. cur = llm_build_norm(ctx0, sa_out, hparams,
  12352. model.layers[il].ffn_norm, NULL,
  12353. LLM_NORM_RMS, cb, il);
  12354. cb(cur, "ffn_norm", il);
  12355. // feed-forward network
  12356. {
  12357. cur = llm_build_ffn(ctx0, lctx, cur,
  12358. model.layers[il].ffn_up, NULL, NULL,
  12359. model.layers[il].ffn_gate, NULL, NULL,
  12360. model.layers[il].ffn_down, NULL, NULL,
  12361. NULL,
  12362. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  12363. cb(cur, "ffn_out", il);
  12364. }
  12365. cur = llm_build_norm(ctx0, cur, hparams,
  12366. model.layers[il].ffn_post_norm, NULL,
  12367. LLM_NORM_RMS, cb, -1);
  12368. cb(cur, "ffn_post_norm", -1);
  12369. cur = ggml_add(ctx0, cur, sa_out);
  12370. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12371. cb(cur, "l_out", il);
  12372. // input for next layer
  12373. inpL = cur;
  12374. }
  12375. cur = inpL;
  12376. cur = llm_build_norm(ctx0, cur, hparams,
  12377. model.output_norm, NULL,
  12378. LLM_NORM_RMS, cb, -1);
  12379. cb(cur, "result_norm", -1);
  12380. // lm_head
  12381. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12382. // final logit soft-capping
  12383. cur = ggml_scale(ctx0, cur, 1.0f / hparams.f_final_logit_softcapping);
  12384. cur = ggml_tanh(ctx0, cur);
  12385. cur = ggml_scale(ctx0, cur, hparams.f_final_logit_softcapping);
  12386. cb(cur, "result_output", -1);
  12387. ggml_build_forward_expand(gf, cur);
  12388. return gf;
  12389. }
  12390. struct ggml_cgraph * build_starcoder2() {
  12391. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12392. const int64_t n_embd_head = hparams.n_embd_head_v;
  12393. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12394. GGML_ASSERT(n_embd_head == hparams.n_rot);
  12395. struct ggml_tensor * cur;
  12396. struct ggml_tensor * inpL;
  12397. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12398. // inp_pos - contains the positions
  12399. struct ggml_tensor * inp_pos = build_inp_pos();
  12400. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12401. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12402. for (int il = 0; il < n_layer; ++il) {
  12403. struct ggml_tensor * inpSA = inpL;
  12404. // norm
  12405. cur = llm_build_norm(ctx0, inpL, hparams,
  12406. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  12407. LLM_NORM, cb, il);
  12408. cb(cur, "attn_norm", il);
  12409. // self-attention
  12410. {
  12411. // compute Q and K and RoPE them
  12412. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12413. cb(Qcur, "Qcur", il);
  12414. if (model.layers[il].bq) {
  12415. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  12416. cb(Qcur, "Qcur", il);
  12417. }
  12418. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12419. cb(Kcur, "Kcur", il);
  12420. if (model.layers[il].bk) {
  12421. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  12422. cb(Kcur, "Kcur", il);
  12423. }
  12424. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12425. cb(Vcur, "Vcur", il);
  12426. if (model.layers[il].bv) {
  12427. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  12428. cb(Vcur, "Vcur", il);
  12429. }
  12430. Qcur = ggml_rope_ext(
  12431. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  12432. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12433. ext_factor, attn_factor, beta_fast, beta_slow
  12434. );
  12435. cb(Qcur, "Qcur", il);
  12436. Kcur = ggml_rope_ext(
  12437. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  12438. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12439. ext_factor, attn_factor, beta_fast, beta_slow
  12440. );
  12441. cb(Kcur, "Kcur", il);
  12442. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12443. model.layers[il].wo, model.layers[il].bo,
  12444. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12445. }
  12446. if (il == n_layer - 1) {
  12447. // skip computing output for unused tokens
  12448. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12449. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12450. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12451. }
  12452. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12453. cb(ffn_inp, "ffn_inp", il);
  12454. // feed-forward network
  12455. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12456. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  12457. LLM_NORM, cb, il);
  12458. cb(cur, "ffn_norm", il);
  12459. cur = llm_build_ffn(ctx0, lctx, cur,
  12460. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  12461. NULL, NULL, NULL,
  12462. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  12463. NULL,
  12464. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  12465. cb(cur, "ffn_out", il);
  12466. cur = ggml_add(ctx0, cur, ffn_inp);
  12467. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12468. cb(cur, "l_out", il);
  12469. // input for next layer
  12470. inpL = cur;
  12471. }
  12472. cur = inpL;
  12473. cur = llm_build_norm(ctx0, cur, hparams,
  12474. model.output_norm, model.output_norm_b,
  12475. LLM_NORM, cb, -1);
  12476. cb(cur, "result_norm", -1);
  12477. // lm_head
  12478. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12479. cb(cur, "result_output", -1);
  12480. ggml_build_forward_expand(gf, cur);
  12481. return gf;
  12482. }
  12483. struct ggml_cgraph * build_mamba() {
  12484. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12485. struct ggml_tensor * cur;
  12486. struct ggml_tensor * inpL;
  12487. // {n_embd, n_tokens}
  12488. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12489. struct ggml_tensor * state_copy = build_inp_s_copy();
  12490. struct ggml_tensor * state_mask = build_inp_s_mask();
  12491. for (int il = 0; il < n_layer; ++il) {
  12492. // norm
  12493. cur = llm_build_norm(ctx0, inpL, hparams,
  12494. model.layers[il].attn_norm, NULL,
  12495. LLM_NORM_RMS, cb, il);
  12496. cb(cur, "attn_norm", il);
  12497. cur = llm_build_mamba(ctx0, lctx, ubatch, gf, cur,
  12498. state_copy, state_mask,
  12499. kv_head, n_kv, cb, il);
  12500. if (il == n_layer - 1) {
  12501. // skip computing output for unused tokens
  12502. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12503. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12504. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  12505. }
  12506. // residual
  12507. cur = ggml_add(ctx0, cur, inpL);
  12508. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12509. cb(cur, "l_out", il);
  12510. // input for next layer
  12511. inpL = cur;
  12512. }
  12513. // final rmsnorm
  12514. cur = llm_build_norm(ctx0, inpL, hparams,
  12515. model.output_norm, NULL,
  12516. LLM_NORM_RMS, cb, -1);
  12517. cb(cur, "result_norm", -1);
  12518. // lm_head
  12519. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12520. cb(cur, "result_output", -1);
  12521. ggml_build_forward_expand(gf, cur);
  12522. return gf;
  12523. }
  12524. struct ggml_cgraph * build_command_r() {
  12525. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12526. const int64_t n_embd_head = hparams.n_embd_head_v;
  12527. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12528. const float f_logit_scale = hparams.f_logit_scale;
  12529. struct ggml_tensor * cur;
  12530. struct ggml_tensor * inpL;
  12531. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12532. // inp_pos - contains the positions
  12533. struct ggml_tensor * inp_pos = build_inp_pos();
  12534. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12535. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12536. for (int il = 0; il < n_layer; ++il) {
  12537. // norm
  12538. cur = llm_build_norm(ctx0, inpL, hparams,
  12539. model.layers[il].attn_norm, NULL,
  12540. LLM_NORM, cb, il);
  12541. cb(cur, "attn_norm", il);
  12542. struct ggml_tensor * ffn_inp = cur;
  12543. // self-attention
  12544. {
  12545. // compute Q and K and RoPE them
  12546. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12547. cb(Qcur, "Qcur", il);
  12548. if (model.layers[il].bq) {
  12549. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  12550. cb(Qcur, "Qcur", il);
  12551. }
  12552. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12553. cb(Kcur, "Kcur", il);
  12554. if (model.layers[il].bk) {
  12555. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  12556. cb(Kcur, "Kcur", il);
  12557. }
  12558. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12559. cb(Vcur, "Vcur", il);
  12560. if (model.layers[il].bv) {
  12561. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  12562. cb(Vcur, "Vcur", il);
  12563. }
  12564. if (model.layers[il].attn_q_norm) {
  12565. Qcur = ggml_view_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens,
  12566. ggml_element_size(Qcur) * n_embd_head,
  12567. ggml_element_size(Qcur) * n_embd_head * n_head,
  12568. 0);
  12569. cb(Qcur, "Qcur", il);
  12570. Kcur = ggml_view_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens,
  12571. ggml_element_size(Kcur) * n_embd_head,
  12572. ggml_element_size(Kcur) * n_embd_head * n_head_kv,
  12573. 0);
  12574. cb(Kcur, "Kcur", il);
  12575. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  12576. model.layers[il].attn_q_norm,
  12577. NULL,
  12578. LLM_NORM, cb, il);
  12579. cb(Qcur, "Qcur", il);
  12580. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  12581. model.layers[il].attn_k_norm,
  12582. NULL,
  12583. LLM_NORM, cb, il);
  12584. cb(Kcur, "Kcur", il);
  12585. }
  12586. Qcur = ggml_rope_ext(
  12587. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  12588. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12589. ext_factor, attn_factor, beta_fast, beta_slow
  12590. );
  12591. cb(Qcur, "Qcur", il);
  12592. Kcur = ggml_rope_ext(
  12593. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  12594. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12595. ext_factor, attn_factor, beta_fast, beta_slow
  12596. );
  12597. cb(Kcur, "Kcur", il);
  12598. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12599. model.layers[il].wo, model.layers[il].bo,
  12600. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12601. }
  12602. if (il == n_layer - 1) {
  12603. // skip computing output for unused tokens
  12604. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12605. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12606. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  12607. ffn_inp = ggml_get_rows(ctx0, ffn_inp, inp_out_ids);
  12608. }
  12609. struct ggml_tensor * attn_out = cur;
  12610. // feed-forward network
  12611. {
  12612. cur = llm_build_ffn(ctx0, lctx, ffn_inp,
  12613. model.layers[il].ffn_up, NULL, NULL,
  12614. model.layers[il].ffn_gate, NULL, NULL,
  12615. model.layers[il].ffn_down, NULL, NULL,
  12616. NULL,
  12617. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12618. cb(cur, "ffn_out", il);
  12619. }
  12620. // add together residual + FFN + self-attention
  12621. cur = ggml_add(ctx0, cur, inpL);
  12622. cur = ggml_add(ctx0, cur, attn_out);
  12623. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12624. cb(cur, "l_out", il);
  12625. // input for next layer
  12626. inpL = cur;
  12627. }
  12628. cur = inpL;
  12629. cur = llm_build_norm(ctx0, cur, hparams,
  12630. model.output_norm, NULL,
  12631. LLM_NORM, cb, -1);
  12632. cb(cur, "result_norm", -1);
  12633. // lm_head
  12634. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12635. if (f_logit_scale) {
  12636. cur = ggml_scale(ctx0, cur, f_logit_scale);
  12637. }
  12638. cb(cur, "result_output", -1);
  12639. ggml_build_forward_expand(gf, cur);
  12640. return gf;
  12641. }
  12642. // ref: https://allenai.org/olmo
  12643. // based on the original build_llama() function, changes:
  12644. // * non-parametric layer norm
  12645. // * clamp qkv
  12646. // * removed bias
  12647. // * removed MoE
  12648. struct ggml_cgraph * build_olmo() {
  12649. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12650. // mutable variable, needed during the last layer of the computation to skip unused tokens
  12651. int32_t n_tokens = this->n_tokens;
  12652. const int64_t n_embd_head = hparams.n_embd_head_v;
  12653. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12654. GGML_ASSERT(n_embd_head == hparams.n_rot);
  12655. struct ggml_tensor * cur;
  12656. struct ggml_tensor * inpL;
  12657. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12658. // inp_pos - contains the positions
  12659. struct ggml_tensor * inp_pos = build_inp_pos();
  12660. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12661. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12662. for (int il = 0; il < n_layer; ++il) {
  12663. struct ggml_tensor * inpSA = inpL;
  12664. // norm
  12665. cur = llm_build_norm(ctx0, inpL, hparams,
  12666. NULL, NULL,
  12667. LLM_NORM, cb, il);
  12668. cb(cur, "attn_norm", il);
  12669. // self-attention
  12670. {
  12671. // compute Q and K and RoPE them
  12672. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12673. cb(Qcur, "Qcur", il);
  12674. if (hparams.f_clamp_kqv > 0.0f) {
  12675. Qcur = ggml_clamp(ctx0, Qcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  12676. cb(Qcur, "Qcur", il);
  12677. }
  12678. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12679. cb(Kcur, "Kcur", il);
  12680. if (hparams.f_clamp_kqv > 0.0f) {
  12681. Kcur = ggml_clamp(ctx0, Kcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  12682. cb(Kcur, "Kcur", il);
  12683. }
  12684. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12685. cb(Vcur, "Vcur", il);
  12686. if (hparams.f_clamp_kqv > 0.0f) {
  12687. Vcur = ggml_clamp(ctx0, Vcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  12688. cb(Vcur, "Vcur", il);
  12689. }
  12690. Qcur = ggml_rope_ext(
  12691. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  12692. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12693. ext_factor, attn_factor, beta_fast, beta_slow
  12694. );
  12695. cb(Qcur, "Qcur", il);
  12696. Kcur = ggml_rope_ext(
  12697. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  12698. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12699. ext_factor, attn_factor, beta_fast, beta_slow
  12700. );
  12701. cb(Kcur, "Kcur", il);
  12702. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12703. model.layers[il].wo, nullptr,
  12704. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12705. }
  12706. if (il == n_layer - 1) {
  12707. // skip computing output for unused tokens
  12708. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12709. n_tokens = n_outputs;
  12710. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12711. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12712. }
  12713. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12714. cb(ffn_inp, "ffn_inp", il);
  12715. // feed-forward network
  12716. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12717. NULL, NULL,
  12718. LLM_NORM, cb, il);
  12719. cb(cur, "ffn_norm", il);
  12720. cur = llm_build_ffn(ctx0, lctx, cur,
  12721. model.layers[il].ffn_up, NULL, NULL,
  12722. model.layers[il].ffn_gate, NULL, NULL,
  12723. model.layers[il].ffn_down, NULL, NULL,
  12724. NULL,
  12725. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12726. cb(cur, "ffn_out", il);
  12727. cur = ggml_add(ctx0, cur, ffn_inp);
  12728. cb(cur, "ffn_out", il);
  12729. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12730. cb(cur, "l_out", il);
  12731. // input for next layer
  12732. inpL = cur;
  12733. }
  12734. cur = inpL;
  12735. cur = llm_build_norm(ctx0, cur, hparams,
  12736. NULL, NULL,
  12737. LLM_NORM, cb, -1);
  12738. cb(cur, "result_norm", -1);
  12739. // lm_head
  12740. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12741. cb(cur, "result_output", -1);
  12742. ggml_build_forward_expand(gf, cur);
  12743. return gf;
  12744. }
  12745. struct ggml_cgraph * build_olmo2() {
  12746. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12747. // mutable variable, needed during the last layer of the computation to skip unused tokens
  12748. int32_t n_tokens = this->n_tokens;
  12749. const int64_t n_embd_head = hparams.n_embd_head_v;
  12750. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12751. GGML_ASSERT(n_embd_head == hparams.n_rot);
  12752. struct ggml_tensor * cur;
  12753. struct ggml_tensor * inpL;
  12754. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12755. // inp_pos - contains the positions
  12756. struct ggml_tensor * inp_pos = build_inp_pos();
  12757. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12758. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12759. for (int il = 0; il < n_layer; ++il) {
  12760. struct ggml_tensor * inpSA = inpL;
  12761. cur = inpL;
  12762. // self_attention
  12763. {
  12764. // compute Q and K and RoPE them
  12765. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12766. cb(Qcur, "Qcur", il);
  12767. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12768. cb(Kcur, "Kcur", il);
  12769. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12770. cb(Vcur, "Vcur", il);
  12771. Qcur = llm_build_norm(ctx0, Qcur, hparams, model.layers[il].attn_q_norm, NULL,
  12772. LLM_NORM_RMS, cb, il);
  12773. cb(Qcur, "Qcur_normed", il);
  12774. Kcur = llm_build_norm(ctx0, Kcur, hparams, model.layers[il].attn_k_norm, NULL,
  12775. LLM_NORM_RMS, cb, il);
  12776. cb(Kcur, "Kcur_normed", il);
  12777. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  12778. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  12779. Qcur = ggml_rope_ext(
  12780. ctx0, Qcur, inp_pos, nullptr,
  12781. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12782. ext_factor, attn_factor, beta_fast, beta_slow
  12783. );
  12784. cb(Qcur, "Qcur_rope", il);
  12785. Kcur = ggml_rope_ext(
  12786. ctx0, Kcur, inp_pos, nullptr,
  12787. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12788. ext_factor, attn_factor, beta_fast, beta_slow
  12789. );
  12790. cb(Kcur, "Kcur_rope", il);
  12791. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12792. model.layers[il].wo, NULL,
  12793. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12794. }
  12795. cur = llm_build_norm(ctx0, cur, hparams,
  12796. model.layers[il].attn_post_norm, NULL,
  12797. LLM_NORM_RMS, cb, il);
  12798. cb(cur, "attn_post_norm", il);
  12799. if (il == n_layer - 1) {
  12800. // skip computing output for unused tokens
  12801. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12802. n_tokens = n_outputs;
  12803. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12804. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12805. }
  12806. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12807. cb(ffn_inp, "ffn_inp", il);
  12808. // feed-forward network
  12809. cur = llm_build_ffn(ctx0, lctx, ffn_inp,
  12810. model.layers[il].ffn_up, NULL, NULL,
  12811. model.layers[il].ffn_gate, NULL, NULL,
  12812. model.layers[il].ffn_down, NULL, NULL,
  12813. NULL,
  12814. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12815. cb(cur, "ffn_out", il);
  12816. cur = llm_build_norm(ctx0, cur, hparams,
  12817. model.layers[il].ffn_post_norm, NULL,
  12818. LLM_NORM_RMS, cb, -1);
  12819. cb(cur, "ffn_post_norm", -1);
  12820. cur = ggml_add(ctx0, cur, ffn_inp);
  12821. cb(cur, "ffn_out", il);
  12822. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12823. cb(cur, "l_out", il);
  12824. // input for next layer
  12825. inpL = cur;
  12826. }
  12827. cur = inpL;
  12828. cur = llm_build_norm(ctx0, cur, hparams,
  12829. model.output_norm, NULL,
  12830. LLM_NORM_RMS, cb, -1);
  12831. cb(cur, "result_norm", -1);
  12832. // lm_head
  12833. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12834. cb(cur, "result_output", -1);
  12835. ggml_build_forward_expand(gf, cur);
  12836. return gf;
  12837. }
  12838. // based on the build_qwen2moe() function, changes:
  12839. // * removed shared experts
  12840. // * removed bias
  12841. // * added q, k norm
  12842. struct ggml_cgraph * build_olmoe() {
  12843. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12844. // mutable variable, needed during the last layer of the computation to skip unused tokens
  12845. int32_t n_tokens = this->n_tokens;
  12846. const int64_t n_embd_head = hparams.n_embd_head_v;
  12847. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12848. GGML_ASSERT(n_embd_head == hparams.n_rot);
  12849. struct ggml_tensor * cur;
  12850. struct ggml_tensor * inpL;
  12851. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12852. // inp_pos - contains the positions
  12853. struct ggml_tensor * inp_pos = build_inp_pos();
  12854. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12855. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12856. for (int il = 0; il < n_layer; ++il) {
  12857. struct ggml_tensor * inpSA = inpL;
  12858. // norm
  12859. cur = llm_build_norm(ctx0, inpL, hparams,
  12860. model.layers[il].attn_norm, NULL,
  12861. LLM_NORM_RMS, cb, il);
  12862. cb(cur, "attn_norm", il);
  12863. // self_attention
  12864. {
  12865. // compute Q and K and RoPE them
  12866. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12867. cb(Qcur, "Qcur", il);
  12868. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12869. cb(Kcur, "Kcur", il);
  12870. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12871. cb(Vcur, "Vcur", il);
  12872. Qcur = llm_build_norm(ctx0, Qcur, hparams, model.layers[il].attn_q_norm, NULL,
  12873. LLM_NORM_RMS, cb, il);
  12874. cb(Qcur, "Qcur_normed", il);
  12875. Kcur = llm_build_norm(ctx0, Kcur, hparams, model.layers[il].attn_k_norm, NULL,
  12876. LLM_NORM_RMS, cb, il);
  12877. cb(Kcur, "Kcur_normed", il);
  12878. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  12879. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  12880. Qcur = ggml_rope_ext(
  12881. ctx0, Qcur, inp_pos, nullptr,
  12882. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12883. ext_factor, attn_factor, beta_fast, beta_slow
  12884. );
  12885. cb(Qcur, "Qcur_rope", il);
  12886. Kcur = ggml_rope_ext(
  12887. ctx0, Kcur, inp_pos, nullptr,
  12888. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12889. ext_factor, attn_factor, beta_fast, beta_slow
  12890. );
  12891. cb(Kcur, "Kcur_rope", il);
  12892. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12893. model.layers[il].wo, NULL,
  12894. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12895. }
  12896. if (il == n_layer - 1) {
  12897. // skip computing output for unused tokens
  12898. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12899. n_tokens = n_outputs;
  12900. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12901. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12902. }
  12903. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12904. cb(ffn_inp, "ffn_inp", il);
  12905. // MoE branch
  12906. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12907. model.layers[il].ffn_norm, NULL,
  12908. LLM_NORM_RMS, cb, il);
  12909. cb(cur, "ffn_norm", il);
  12910. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  12911. model.layers[il].ffn_gate_inp,
  12912. model.layers[il].ffn_up_exps,
  12913. model.layers[il].ffn_gate_exps,
  12914. model.layers[il].ffn_down_exps,
  12915. n_expert, n_expert_used,
  12916. LLM_FFN_SILU, false,
  12917. false, 0.0,
  12918. cb, il);
  12919. cb(cur, "ffn_moe_out", il);
  12920. cur = ggml_add(ctx0, cur, ffn_inp);
  12921. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12922. cb(cur, "l_out", il);
  12923. // input for next layer
  12924. inpL = cur;
  12925. }
  12926. cur = inpL;
  12927. cur = llm_build_norm(ctx0, cur, hparams,
  12928. model.output_norm, NULL,
  12929. LLM_NORM_RMS, cb, -1);
  12930. cb(cur, "result_norm", -1);
  12931. // lm_head
  12932. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12933. cb(cur, "result_output", -1);
  12934. ggml_build_forward_expand(gf, cur);
  12935. return gf;
  12936. }
  12937. struct ggml_cgraph * build_openelm() {
  12938. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12939. const int64_t n_embd_head = hparams.n_embd_head_v;
  12940. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12941. struct ggml_tensor * cur;
  12942. struct ggml_tensor * inpL;
  12943. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12944. // inp_pos - contains the positions
  12945. struct ggml_tensor * inp_pos = build_inp_pos();
  12946. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12947. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12948. for (int il = 0; il < n_layer; ++il) {
  12949. const int64_t n_head = hparams.n_head(il);
  12950. const int64_t n_head_kv = hparams.n_head_kv(il);
  12951. const int64_t n_head_qkv = 2*n_head_kv + n_head;
  12952. cur = inpL;
  12953. struct ggml_tensor * residual = cur;
  12954. // norm
  12955. cur = llm_build_norm(ctx0, inpL, hparams,
  12956. model.layers[il].attn_norm, NULL,
  12957. LLM_NORM_RMS, cb, il);
  12958. cb(cur, "attn_norm", il);
  12959. // self-attention
  12960. {
  12961. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  12962. cb(cur, "wqkv", il);
  12963. cur = ggml_reshape_3d(ctx0, cur, n_embd_head_k, n_head_qkv, n_tokens);
  12964. 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));
  12965. cb(Qcur, "Qcur", il);
  12966. 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));
  12967. cb(Kcur, "Kcur", il);
  12968. 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)));
  12969. cb(Vcur, "Vcur", il);
  12970. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  12971. model.layers[il].attn_q_norm, NULL,
  12972. LLM_NORM_RMS, cb, il);
  12973. cb(Qcur, "Qcur", il);
  12974. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  12975. model.layers[il].attn_k_norm, NULL,
  12976. LLM_NORM_RMS, cb, il);
  12977. cb(Kcur, "Kcur", il);
  12978. Qcur = ggml_rope_ext(
  12979. ctx0, Qcur, inp_pos, NULL, n_rot, rope_type, n_ctx_orig,
  12980. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  12981. );
  12982. cb(Qcur, "Qcur", il);
  12983. Kcur = ggml_rope_ext(
  12984. ctx0, Kcur, inp_pos, NULL, n_rot, rope_type, n_ctx_orig,
  12985. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  12986. );
  12987. cb(Kcur, "Kcur", il);
  12988. Vcur = ggml_reshape_2d(ctx0, Vcur, n_embd_head * n_head_kv, n_tokens);
  12989. cb(Qcur, "Vcur", il);
  12990. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12991. model.layers[il].wo, NULL,
  12992. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12993. }
  12994. if (il == n_layer - 1) {
  12995. // skip computing output for unused tokens
  12996. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12997. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  12998. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12999. }
  13000. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  13001. cb(ffn_inp, "ffn_inp", il);
  13002. // feed-forward network
  13003. {
  13004. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13005. model.layers[il].ffn_norm, NULL,
  13006. LLM_NORM_RMS, cb, il);
  13007. cb(cur, "ffn_norm", il);
  13008. cur = llm_build_ffn(ctx0, lctx, cur,
  13009. model.layers[il].ffn_up, NULL, NULL,
  13010. model.layers[il].ffn_gate, NULL, NULL,
  13011. model.layers[il].ffn_down, NULL, NULL,
  13012. NULL,
  13013. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13014. cb(cur, "ffn_out", il);
  13015. }
  13016. cur = ggml_add(ctx0, cur, ffn_inp);
  13017. cur = lctx.cvec.apply_to(ctx0, cur, il);
  13018. cb(cur, "l_out", il);
  13019. inpL = cur;
  13020. }
  13021. cur = inpL;
  13022. // norm
  13023. cur = llm_build_norm(ctx0, cur, hparams,
  13024. model.output_norm, NULL,
  13025. LLM_NORM_RMS, cb, -1);
  13026. cb(cur, "result_norm", -1);
  13027. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13028. cb(cur, "result_output", -1);
  13029. ggml_build_forward_expand(gf, cur);
  13030. return gf;
  13031. }
  13032. struct ggml_cgraph * build_gptneox() {
  13033. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13034. const int64_t n_embd_head = hparams.n_embd_head_v;
  13035. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  13036. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13037. struct ggml_tensor * cur;
  13038. struct ggml_tensor * inpL;
  13039. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13040. // inp_pos - contains the positions
  13041. struct ggml_tensor * inp_pos = build_inp_pos();
  13042. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13043. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13044. for (int il = 0; il < n_layer; ++il) {
  13045. cur = llm_build_norm(ctx0, inpL, hparams,
  13046. model.layers[il].attn_norm,
  13047. model.layers[il].attn_norm_b,
  13048. LLM_NORM, cb, il);
  13049. cb(cur, "attn_norm", il);
  13050. // self-attention
  13051. {
  13052. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  13053. cb(cur, "wqkv", il);
  13054. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  13055. cb(cur, "bqkv", il);
  13056. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  13057. 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)));
  13058. 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)));
  13059. cb(Qcur, "Qcur", il);
  13060. cb(Kcur, "Kcur", il);
  13061. cb(Vcur, "Vcur", il);
  13062. Qcur = ggml_rope_ext(
  13063. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  13064. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13065. ext_factor, attn_factor, beta_fast, beta_slow
  13066. );
  13067. cb(Qcur, "Qcur", il);
  13068. Kcur = ggml_rope_ext(
  13069. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  13070. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13071. ext_factor, attn_factor, beta_fast, beta_slow
  13072. );
  13073. cb(Kcur, "Kcur", il);
  13074. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13075. model.layers[il].wo, model.layers[il].bo,
  13076. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13077. }
  13078. if (il == n_layer - 1) {
  13079. // skip computing output for unused tokens
  13080. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13081. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13082. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  13083. }
  13084. // ffn
  13085. if (hparams.use_par_res) {
  13086. // attention and ffn are computed in parallel
  13087. // x = x + attn(ln1(x)) + ffn(ln2(x))
  13088. struct ggml_tensor * attn_out = cur;
  13089. cur = llm_build_norm(ctx0, inpL, hparams,
  13090. model.layers[il].ffn_norm,
  13091. model.layers[il].ffn_norm_b,
  13092. LLM_NORM, cb, il);
  13093. cb(cur, "ffn_norm", il);
  13094. cur = llm_build_ffn(ctx0, lctx, cur,
  13095. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  13096. NULL, NULL, NULL,
  13097. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  13098. NULL,
  13099. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  13100. cb(cur, "ffn_out", il);
  13101. cur = ggml_add(ctx0, cur, inpL);
  13102. cb(cur, "ffn_out", il);
  13103. cur = ggml_add(ctx0, cur, attn_out);
  13104. cur = lctx.cvec.apply_to(ctx0, cur, il);
  13105. cb(cur, "l_out", il);
  13106. // input for next layer
  13107. inpL = cur;
  13108. } else {
  13109. // attention and ffn are computed sequentially
  13110. // x = x + attn(ln1(x))
  13111. // x = x + ffn(ln2(x))
  13112. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  13113. cb(ffn_inp, "ffn_inp", il);
  13114. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13115. model.layers[il].ffn_norm,
  13116. model.layers[il].ffn_norm_b,
  13117. LLM_NORM, cb, il);
  13118. cb(cur, "ffn_norm", il);
  13119. cur = llm_build_ffn(ctx0, lctx, cur,
  13120. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  13121. NULL, NULL, NULL,
  13122. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  13123. NULL,
  13124. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  13125. cb(cur, "ffn_out", il);
  13126. cur = ggml_add(ctx0, cur, ffn_inp);
  13127. cur = lctx.cvec.apply_to(ctx0, cur, il);
  13128. cb(cur, "l_out", il);
  13129. // input for next layer
  13130. inpL = cur;
  13131. }
  13132. }
  13133. cur = llm_build_norm(ctx0, inpL, hparams,
  13134. model.output_norm,
  13135. model.output_norm_b,
  13136. LLM_NORM, cb, -1);
  13137. cb(cur, "result_norm", -1);
  13138. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13139. cb(cur, "result_output", -1);
  13140. ggml_build_forward_expand(gf, cur);
  13141. return gf;
  13142. }
  13143. struct ggml_cgraph * build_arctic() {
  13144. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13145. // mutable variable, needed during the last layer of the computation to skip unused tokens
  13146. int32_t n_tokens = this->n_tokens;
  13147. const int64_t n_embd_head = hparams.n_embd_head_v;
  13148. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13149. GGML_ASSERT(n_embd_head == hparams.n_rot);
  13150. struct ggml_tensor * cur;
  13151. struct ggml_tensor * inpL;
  13152. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13153. // inp_pos - contains the positions
  13154. struct ggml_tensor * inp_pos = build_inp_pos();
  13155. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13156. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13157. for (int il = 0; il < n_layer; ++il) {
  13158. struct ggml_tensor * inpSA = inpL;
  13159. // norm
  13160. cur = llm_build_norm(ctx0, inpL, hparams,
  13161. model.layers[il].attn_norm, NULL,
  13162. LLM_NORM_RMS, cb, il);
  13163. cb(cur, "attn_norm", il);
  13164. // self-attention
  13165. {
  13166. // compute Q and K and RoPE them
  13167. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  13168. cb(Qcur, "Qcur", il);
  13169. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  13170. cb(Kcur, "Kcur", il);
  13171. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  13172. cb(Vcur, "Vcur", il);
  13173. Qcur = ggml_rope_ext(
  13174. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  13175. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13176. ext_factor, attn_factor, beta_fast, beta_slow
  13177. );
  13178. cb(Qcur, "Qcur", il);
  13179. Kcur = ggml_rope_ext(
  13180. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  13181. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13182. ext_factor, attn_factor, beta_fast, beta_slow
  13183. );
  13184. cb(Kcur, "Kcur", il);
  13185. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13186. model.layers[il].wo, NULL,
  13187. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13188. }
  13189. if (il == n_layer - 1) {
  13190. // skip computing output for unused tokens
  13191. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13192. n_tokens = n_outputs;
  13193. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13194. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13195. }
  13196. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13197. cb(ffn_inp, "ffn_inp", il);
  13198. // feed-forward network
  13199. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13200. model.layers[il].ffn_norm, NULL,
  13201. LLM_NORM_RMS, cb, il);
  13202. cb(cur, "ffn_norm", il);
  13203. cur = llm_build_ffn(ctx0, lctx, cur,
  13204. model.layers[il].ffn_up, NULL, NULL,
  13205. model.layers[il].ffn_gate, NULL, NULL,
  13206. model.layers[il].ffn_down, NULL, NULL,
  13207. NULL,
  13208. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13209. cb(cur, "ffn_out", il);
  13210. struct ggml_tensor * ffn_out = ggml_add(ctx0, cur, ffn_inp);
  13211. cb(ffn_out, "ffn_out", il);
  13212. // MoE
  13213. cur = llm_build_norm(ctx0, inpSA, hparams,
  13214. model.layers[il].ffn_norm_exps, NULL,
  13215. LLM_NORM_RMS, cb, il);
  13216. cb(cur, "ffn_norm_exps", il);
  13217. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  13218. model.layers[il].ffn_gate_inp,
  13219. model.layers[il].ffn_up_exps,
  13220. model.layers[il].ffn_gate_exps,
  13221. model.layers[il].ffn_down_exps,
  13222. n_expert, n_expert_used,
  13223. LLM_FFN_SILU, true,
  13224. false, 0.0,
  13225. cb, il);
  13226. cb(cur, "ffn_moe_out", il);
  13227. cur = ggml_add(ctx0, cur, ffn_out);
  13228. cb(cur, "ffn_out", il);
  13229. cur = lctx.cvec.apply_to(ctx0, cur, il);
  13230. cb(cur, "l_out", il);
  13231. // input for next layer
  13232. inpL = cur;
  13233. }
  13234. cur = inpL;
  13235. cur = llm_build_norm(ctx0, cur, hparams,
  13236. model.output_norm, NULL,
  13237. LLM_NORM_RMS, cb, -1);
  13238. cb(cur, "result_norm", -1);
  13239. // lm_head
  13240. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13241. cb(cur, "result_output", -1);
  13242. ggml_build_forward_expand(gf, cur);
  13243. return gf;
  13244. }
  13245. struct ggml_cgraph * build_deepseek2() {
  13246. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13247. // mutable variable, needed during the last layer of the computation to skip unused tokens
  13248. int32_t n_tokens = this->n_tokens;
  13249. bool is_lite = (hparams.n_layer == 27);
  13250. // We have to pre-scale kq_scale and attn_factor to make the YaRN RoPE work correctly.
  13251. // See https://github.com/ggerganov/llama.cpp/discussions/7416 for detailed explanation.
  13252. const float mscale = attn_factor * (1.0f + hparams.rope_yarn_log_mul * logf(1.0f / freq_scale));
  13253. const float kq_scale = 1.0f*mscale*mscale/sqrtf(float(hparams.n_embd_head_k));
  13254. const float attn_factor_scaled = 1.0f / (1.0f + 0.1f * logf(1.0f / freq_scale));
  13255. const uint32_t n_embd_head_qk_rope = hparams.n_rot;
  13256. const uint32_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  13257. const uint32_t kv_lora_rank = hparams.n_lora_kv;
  13258. struct ggml_tensor * cur;
  13259. struct ggml_tensor * inpL;
  13260. // {n_embd, n_tokens}
  13261. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13262. // inp_pos - contains the positions
  13263. struct ggml_tensor * inp_pos = build_inp_pos();
  13264. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13265. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13266. for (int il = 0; il < n_layer; ++il) {
  13267. struct ggml_tensor * inpSA = inpL;
  13268. // norm
  13269. cur = llm_build_norm(ctx0, inpL, hparams,
  13270. model.layers[il].attn_norm, NULL,
  13271. LLM_NORM_RMS, cb, il);
  13272. cb(cur, "attn_norm", il);
  13273. // self_attention
  13274. {
  13275. struct ggml_tensor * q = NULL;
  13276. if (!is_lite) {
  13277. // {n_embd, q_lora_rank} * {n_embd, n_tokens} -> {q_lora_rank, n_tokens}
  13278. q = ggml_mul_mat(ctx0, model.layers[il].wq_a, cur);
  13279. cb(q, "q", il);
  13280. q = llm_build_norm(ctx0, q, hparams,
  13281. model.layers[il].attn_q_a_norm, NULL,
  13282. LLM_NORM_RMS, cb, il);
  13283. cb(q, "q", il);
  13284. // {q_lora_rank, n_head * hparams.n_embd_head_k} * {q_lora_rank, n_tokens} -> {n_head * hparams.n_embd_head_k, n_tokens}
  13285. q = ggml_mul_mat(ctx0, model.layers[il].wq_b, q);
  13286. cb(q, "q", il);
  13287. } else {
  13288. q = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  13289. cb(q, "q", il);
  13290. }
  13291. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  13292. struct ggml_tensor * q_nope = ggml_view_3d(ctx0, q, n_embd_head_qk_nope, n_head, n_tokens,
  13293. ggml_row_size(q->type, hparams.n_embd_head_k),
  13294. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  13295. 0);
  13296. cb(q_nope, "q_nope", il);
  13297. // and {n_head * n_embd_head_qk_rope, n_tokens}
  13298. struct ggml_tensor * q_pe = ggml_view_3d(ctx0, q, n_embd_head_qk_rope, n_head, n_tokens,
  13299. ggml_row_size(q->type, hparams.n_embd_head_k),
  13300. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  13301. ggml_row_size(q->type, n_embd_head_qk_nope));
  13302. cb(q_pe, "q_pe", il);
  13303. // {n_embd, kv_lora_rank + n_embd_head_qk_rope} * {n_embd, n_tokens} -> {kv_lora_rank + n_embd_head_qk_rope, n_tokens}
  13304. struct ggml_tensor * kv_pe_compresseed = ggml_mul_mat(ctx0, model.layers[il].wkv_a_mqa, cur);
  13305. cb(kv_pe_compresseed, "kv_pe_compresseed", il);
  13306. // split into {kv_lora_rank, n_tokens}
  13307. struct ggml_tensor * kv_compressed = ggml_view_2d(ctx0, kv_pe_compresseed, kv_lora_rank, n_tokens,
  13308. kv_pe_compresseed->nb[1],
  13309. 0);
  13310. cb(kv_compressed, "kv_compressed", il);
  13311. // and {n_embd_head_qk_rope, n_tokens}
  13312. struct ggml_tensor * k_pe = ggml_view_3d(ctx0, kv_pe_compresseed, n_embd_head_qk_rope, 1, n_tokens,
  13313. kv_pe_compresseed->nb[1],
  13314. kv_pe_compresseed->nb[1],
  13315. ggml_row_size(kv_pe_compresseed->type, kv_lora_rank));
  13316. cb(k_pe, "k_pe", il);
  13317. kv_compressed = ggml_cont(ctx0, kv_compressed); // TODO: the CUDA backend does not support non-contiguous norm
  13318. kv_compressed = llm_build_norm(ctx0, kv_compressed, hparams,
  13319. model.layers[il].attn_kv_a_norm, NULL,
  13320. LLM_NORM_RMS, cb, il);
  13321. cb(kv_compressed, "kv_compressed", il);
  13322. // {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}
  13323. struct ggml_tensor * kv = ggml_mul_mat(ctx0, model.layers[il].wkv_b, kv_compressed);
  13324. cb(kv, "kv", il);
  13325. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  13326. struct ggml_tensor * k_nope = ggml_view_3d(ctx0, kv, n_embd_head_qk_nope, n_head, n_tokens,
  13327. ggml_row_size(kv->type, n_embd_head_qk_nope + hparams.n_embd_head_v),
  13328. ggml_row_size(kv->type, n_head * (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  13329. 0);
  13330. cb(k_nope, "k_nope", il);
  13331. // and {n_head * n_embd_head_v, n_tokens}
  13332. struct ggml_tensor * v_states = ggml_view_3d(ctx0, kv, hparams.n_embd_head_v, n_head, n_tokens,
  13333. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  13334. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)*n_head),
  13335. ggml_row_size(kv->type, (n_embd_head_qk_nope)));
  13336. cb(v_states, "v_states", il);
  13337. v_states = ggml_cont(ctx0, v_states);
  13338. cb(v_states, "v_states", il);
  13339. v_states = ggml_view_2d(ctx0, v_states, hparams.n_embd_head_v * n_head, n_tokens,
  13340. ggml_row_size(kv->type, hparams.n_embd_head_v * n_head),
  13341. 0);
  13342. cb(v_states, "v_states", il);
  13343. q_pe = ggml_cont(ctx0, q_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  13344. q_pe = ggml_rope_ext(
  13345. ctx0, q_pe, inp_pos, nullptr,
  13346. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13347. ext_factor, attn_factor_scaled, beta_fast, beta_slow
  13348. );
  13349. cb(q_pe, "q_pe", il);
  13350. // shared RoPE key
  13351. k_pe = ggml_cont(ctx0, k_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  13352. k_pe = ggml_rope_ext(
  13353. ctx0, k_pe, inp_pos, nullptr,
  13354. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13355. ext_factor, attn_factor_scaled, beta_fast, beta_slow
  13356. );
  13357. cb(k_pe, "k_pe", il);
  13358. struct ggml_tensor * q_states = ggml_concat(ctx0, q_nope, q_pe, 0);
  13359. cb(q_states, "q_states", il);
  13360. struct ggml_tensor * k_states = ggml_concat(ctx0, k_nope, ggml_repeat(ctx0, k_pe, q_pe), 0);
  13361. cb(k_states, "k_states", il);
  13362. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13363. model.layers[il].wo, NULL,
  13364. k_states, v_states, q_states, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  13365. }
  13366. if (il == n_layer - 1) {
  13367. // skip computing output for unused tokens
  13368. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13369. n_tokens = n_outputs;
  13370. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13371. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13372. }
  13373. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13374. cb(ffn_inp, "ffn_inp", il);
  13375. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13376. model.layers[il].ffn_norm, NULL,
  13377. LLM_NORM_RMS, cb, il);
  13378. cb(cur, "ffn_norm", il);
  13379. if ((uint32_t) il < hparams.n_layer_dense_lead) {
  13380. cur = llm_build_ffn(ctx0, lctx, cur,
  13381. model.layers[il].ffn_up, NULL, NULL,
  13382. model.layers[il].ffn_gate, NULL, NULL,
  13383. model.layers[il].ffn_down, NULL, NULL,
  13384. NULL,
  13385. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13386. cb(cur, "ffn_out", il);
  13387. } else {
  13388. // MoE branch
  13389. ggml_tensor * moe_out =
  13390. llm_build_moe_ffn(ctx0, lctx, cur,
  13391. model.layers[il].ffn_gate_inp,
  13392. model.layers[il].ffn_up_exps,
  13393. model.layers[il].ffn_gate_exps,
  13394. model.layers[il].ffn_down_exps,
  13395. n_expert, n_expert_used,
  13396. LLM_FFN_SILU, false,
  13397. true, hparams.expert_weights_scale,
  13398. cb, il);
  13399. cb(moe_out, "ffn_moe_out", il);
  13400. // FFN shared expert
  13401. {
  13402. ggml_tensor * ffn_shexp = llm_build_ffn(ctx0, lctx, cur,
  13403. model.layers[il].ffn_up_shexp, NULL, NULL,
  13404. model.layers[il].ffn_gate_shexp, NULL, NULL,
  13405. model.layers[il].ffn_down_shexp, NULL, NULL,
  13406. NULL,
  13407. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13408. cb(ffn_shexp, "ffn_shexp", il);
  13409. cur = ggml_add(ctx0, moe_out, ffn_shexp);
  13410. cb(cur, "ffn_out", il);
  13411. }
  13412. }
  13413. cur = ggml_add(ctx0, cur, ffn_inp);
  13414. cur = lctx.cvec.apply_to(ctx0, cur, il);
  13415. cb(cur, "l_out", il);
  13416. // input for next layer
  13417. inpL = cur;
  13418. }
  13419. cur = inpL;
  13420. cur = llm_build_norm(ctx0, cur, hparams,
  13421. model.output_norm, NULL,
  13422. LLM_NORM_RMS, cb, -1);
  13423. cb(cur, "result_norm", -1);
  13424. // lm_head
  13425. cur = ggml_mul_mat(ctx0, model.output, cur);
  13426. cb(cur, "result_output", -1);
  13427. ggml_build_forward_expand(gf, cur);
  13428. return gf;
  13429. }
  13430. struct ggml_cgraph * build_bitnet() {
  13431. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13432. const int64_t n_embd_head = hparams.n_embd_head_v;
  13433. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13434. struct ggml_tensor * cur;
  13435. struct ggml_tensor * inpL;
  13436. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13437. // inp_pos - contains the positions
  13438. struct ggml_tensor * inp_pos = build_inp_pos();
  13439. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13440. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13441. for (int il = 0; il < n_layer; ++il) {
  13442. struct ggml_tensor * inpSA = inpL;
  13443. cur = llm_build_norm(ctx0, inpL, hparams,
  13444. model.layers[il].attn_norm, NULL,
  13445. LLM_NORM_RMS, cb, il);
  13446. cb(cur, "attn_norm", il);
  13447. // self-attention
  13448. {
  13449. // compute Q and K and RoPE them
  13450. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  13451. if (model.layers[il].wq_scale) {
  13452. Qcur = ggml_mul(ctx0, Qcur, model.layers[il].wq_scale);
  13453. }
  13454. cb(Qcur, "Qcur", il);
  13455. if (model.layers[il].bq) {
  13456. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  13457. cb(Qcur, "Qcur", il);
  13458. }
  13459. // B1.K
  13460. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  13461. if (model.layers[il].wk_scale) {
  13462. Kcur = ggml_mul(ctx0, Kcur, model.layers[il].wk_scale);
  13463. }
  13464. cb(Kcur, "Kcur", il);
  13465. if (model.layers[il].bk) {
  13466. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  13467. cb(Kcur, "Kcur", il);
  13468. }
  13469. // B1.V
  13470. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  13471. if (model.layers[il].wv_scale) {
  13472. Vcur = ggml_mul(ctx0, Vcur, model.layers[il].wv_scale);
  13473. }
  13474. cb(Vcur, "Vcur", il);
  13475. if (model.layers[il].bv) {
  13476. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  13477. cb(Vcur, "Vcur", il);
  13478. }
  13479. Qcur = ggml_rope_ext(
  13480. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  13481. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13482. ext_factor, attn_factor, beta_fast, beta_slow
  13483. );
  13484. cb(Qcur, "Qcur", il);
  13485. Kcur = ggml_rope_ext(
  13486. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  13487. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13488. ext_factor, attn_factor, beta_fast, beta_slow
  13489. );
  13490. cb(Kcur, "Kcur", il);
  13491. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13492. NULL, NULL,
  13493. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13494. cur = llm_build_norm(ctx0, cur, hparams,
  13495. model.layers[il].attn_sub_norm, NULL,
  13496. LLM_NORM_RMS, cb, il);
  13497. cb(cur, "attn_sub_norm", il);
  13498. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  13499. if (model.layers[il].wo_scale) {
  13500. cur = ggml_mul(ctx0, cur, model.layers[il].wo_scale);
  13501. }
  13502. if (model.layers[il].bo) {
  13503. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  13504. }
  13505. cb(cur, "attn_o_out", il);
  13506. }
  13507. if (il == n_layer - 1) {
  13508. // skip computing output for unused tokens
  13509. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13510. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13511. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13512. }
  13513. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13514. cb(ffn_inp, "ffn_inp", il);
  13515. // feed-forward forward
  13516. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13517. model.layers[il].ffn_norm, NULL,
  13518. LLM_NORM_RMS, cb, il);
  13519. cb(cur, "ffn_norm", il);
  13520. cur = llm_build_ffn(ctx0, lctx, cur,
  13521. model.layers[il].ffn_up, NULL, model.layers[il].ffn_up_scale,
  13522. model.layers[il].ffn_gate, NULL, model.layers[il].ffn_gate_scale,
  13523. NULL, NULL, NULL,
  13524. NULL,
  13525. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13526. cb(cur, "ffn_sub_out", il);
  13527. cur = llm_build_norm(ctx0, cur, hparams,
  13528. model.layers[il].ffn_sub_norm, NULL,
  13529. LLM_NORM_RMS, cb, il);
  13530. cb(cur, "ffn_sub_norm", il);
  13531. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].ffn_down, cur);
  13532. if (model.layers[il].ffn_down_scale) {
  13533. cur = ggml_mul(ctx0, cur, model.layers[il].ffn_down_scale);
  13534. }
  13535. cb(cur, "ffn_down", il);
  13536. cur = ggml_add(ctx0, cur, ffn_inp);
  13537. cb(cur, "l_out", il);
  13538. // input for next layer
  13539. inpL = cur;
  13540. }
  13541. cur = inpL;
  13542. cur = llm_build_norm(ctx0, cur, hparams,
  13543. model.output_norm, NULL,
  13544. LLM_NORM_RMS, cb, -1);
  13545. cb(cur, "result_norm", -1);
  13546. // lm_head
  13547. // FIXME: do not use model.tok_embd directly, duplicate as model.output
  13548. cur = llm_build_lora_mm(lctx, ctx0, model.tok_embd, cur);
  13549. cb(cur, "result_output", -1);
  13550. ggml_build_forward_expand(gf, cur);
  13551. return gf;
  13552. }
  13553. struct ggml_cgraph * build_t5_encoder() {
  13554. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13555. // mutable variable, needed during the last layer of the computation to skip unused tokens
  13556. int32_t n_tokens = this->n_tokens;
  13557. const int64_t n_embd_head = hparams.n_embd_head_v;
  13558. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  13559. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13560. struct ggml_tensor * cur;
  13561. struct ggml_tensor * inpL;
  13562. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13563. GGML_ASSERT(lctx.is_encoding);
  13564. struct ggml_tensor * pos_bucket_enc = llm_build_pos_bucket(false);
  13565. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13566. struct ggml_tensor * KQ_mask_enc = build_inp_KQ_mask(false);
  13567. for (int il = 0; il < n_layer; ++il) {
  13568. struct ggml_tensor * inpSA = inpL;
  13569. // norm
  13570. cur = llm_build_norm(ctx0, inpL, hparams,
  13571. model.layers[il].attn_norm_enc, NULL,
  13572. LLM_NORM_RMS, cb, il);
  13573. cb(cur, "attn_norm", il);
  13574. // self-attention
  13575. {
  13576. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq_enc, cur);
  13577. cb(Qcur, "Qcur", il);
  13578. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk_enc, cur);
  13579. cb(Kcur, "Kcur", il);
  13580. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv_enc, cur);
  13581. cb(Vcur, "Vcur", il);
  13582. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  13583. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  13584. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  13585. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  13586. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  13587. cb(kq, "kq", il);
  13588. 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;
  13589. struct ggml_tensor * pos_bias = llm_build_pos_bias(pos_bucket_enc, attn_rel_b);
  13590. struct ggml_tensor * kq_b = ggml_add(ctx0, kq, pos_bias);
  13591. cb(kq_b, "kq_b", il);
  13592. kq = ggml_soft_max_ext(ctx0, kq_b, KQ_mask_enc, 1.0f, hparams.f_max_alibi_bias);
  13593. cb(kq, "kq_soft_max_ext", il);
  13594. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  13595. cb(v, "v", il);
  13596. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  13597. cb(kqv, "kqv", il);
  13598. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  13599. cb(kqv_merged, "kqv_merged", il);
  13600. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  13601. cb(cur, "kqv_merged_cont", il);
  13602. ggml_build_forward_expand(gf, cur);
  13603. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo_enc, cur);
  13604. cb(cur, "kqv_out", il);
  13605. }
  13606. if (il == n_layer - 1) {
  13607. // skip computing output for unused tokens
  13608. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13609. n_tokens = n_outputs;
  13610. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13611. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13612. }
  13613. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13614. cb(ffn_inp, "ffn_inp", il);
  13615. // feed-forward network
  13616. {
  13617. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13618. model.layers[il].ffn_norm_enc, NULL,
  13619. LLM_NORM_RMS, cb, il);
  13620. cb(cur, "ffn_norm", il);
  13621. // T5 uses relu, flan-T5 uses gelu-gated
  13622. cur = llm_build_ffn(ctx0, lctx, cur,
  13623. model.layers[il].ffn_up_enc, NULL, NULL,
  13624. model.layers[il].ffn_gate_enc, NULL, NULL,
  13625. model.layers[il].ffn_down_enc, NULL, NULL,
  13626. NULL,
  13627. model.layers[il].ffn_gate_enc ? LLM_FFN_GELU : LLM_FFN_RELU,
  13628. model.layers[il].ffn_gate_enc ? LLM_FFN_PAR : LLM_FFN_SEQ,
  13629. cb, il);
  13630. cb(cur, "ffn_out", il);
  13631. }
  13632. cur = ggml_add(ctx0, cur, ffn_inp);
  13633. cb(cur, "ffn_out", il);
  13634. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  13635. if (layer_dir != nullptr) {
  13636. cur = ggml_add(ctx0, cur, layer_dir);
  13637. }
  13638. cb(cur, "l_out", il);
  13639. // input for next layer
  13640. inpL = cur;
  13641. }
  13642. cur = inpL;
  13643. cb(cur, "result_embd", -1);
  13644. cur = llm_build_norm(ctx0, cur, hparams,
  13645. model.output_norm_enc, NULL,
  13646. LLM_NORM_RMS, cb, -1);
  13647. cb(cur, "result_norm", -1);
  13648. ggml_build_forward_expand(gf, cur);
  13649. return gf;
  13650. }
  13651. struct ggml_cgraph * build_t5_decoder() {
  13652. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13653. // mutable variable, needed during the last layer of the computation to skip unused tokens
  13654. int32_t n_tokens = this->n_tokens;
  13655. const int64_t n_embd_head = hparams.n_embd_head_v;
  13656. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  13657. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13658. struct ggml_tensor * cur;
  13659. struct ggml_tensor * inpL;
  13660. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13661. GGML_ASSERT(!lctx.is_encoding);
  13662. GGML_ASSERT(n_outputs_enc > 0 && "call llama_encode() first");
  13663. struct ggml_tensor * embd_enc = llm_build_inp_embd_enc();
  13664. struct ggml_tensor * pos_bucket_dec = llm_build_pos_bucket(true);
  13665. struct ggml_tensor * KQ_mask_dec = build_inp_KQ_mask();
  13666. struct ggml_tensor * KQ_mask_cross = llm_build_inp_KQ_mask_cross();
  13667. for (int il = 0; il < n_layer; ++il) {
  13668. struct ggml_tensor * inpSA = inpL;
  13669. // norm
  13670. cur = llm_build_norm(ctx0, inpL, hparams,
  13671. model.layers[il].attn_norm, NULL,
  13672. LLM_NORM_RMS, cb, il);
  13673. cb(cur, "attn_norm", il);
  13674. // self-attention
  13675. {
  13676. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  13677. cb(Qcur, "Qcur", il);
  13678. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  13679. cb(Kcur, "Kcur", il);
  13680. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  13681. cb(Vcur, "Vcur", il);
  13682. llm_build_kv_store(ctx0, hparams, cparams, kv_self, gf, Kcur, Vcur, n_tokens, kv_head, cb, il);
  13683. struct ggml_tensor * k =
  13684. ggml_view_3d(ctx0, kv_self.k_l[il],
  13685. n_embd_head_k, n_kv, n_head_kv,
  13686. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  13687. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  13688. 0);
  13689. cb(k, "k", il);
  13690. struct ggml_tensor * v =
  13691. ggml_view_3d(ctx0, kv_self.v_l[il],
  13692. n_kv, n_embd_head_v, n_head_kv,
  13693. ggml_element_size(kv_self.v_l[il])*n_ctx,
  13694. ggml_element_size(kv_self.v_l[il])*n_ctx*n_embd_head_v,
  13695. 0);
  13696. cb(v, "v", il);
  13697. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  13698. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  13699. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  13700. cb(kq, "kq", il);
  13701. struct ggml_tensor * attn_rel_b = model.layers[il].attn_rel_b ? model.layers[il].attn_rel_b : model.layers[0].attn_rel_b;
  13702. struct ggml_tensor * pos_bias = llm_build_pos_bias(pos_bucket_dec, attn_rel_b);
  13703. struct ggml_tensor * kq_b = ggml_add(ctx0, kq, pos_bias);
  13704. cb(kq_b, "kq_b", il);
  13705. kq = ggml_soft_max_ext(ctx0, kq_b, KQ_mask_dec, 1.0f, hparams.f_max_alibi_bias);
  13706. cb(kq, "kq_soft_max_ext", il);
  13707. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, v, kq);
  13708. cb(kqv, "kqv", il);
  13709. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  13710. cb(kqv_merged, "kqv_merged", il);
  13711. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  13712. cb(cur, "kqv_merged_cont", il);
  13713. ggml_build_forward_expand(gf, cur);
  13714. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  13715. cb(cur, "kqv_out", il);
  13716. }
  13717. cur = ggml_add(ctx0, cur, inpSA);
  13718. cb(cur, "cross_inp", il);
  13719. struct ggml_tensor * inpCA = cur;
  13720. // norm
  13721. cur = llm_build_norm(ctx0, cur, hparams,
  13722. model.layers[il].attn_norm_cross, NULL,
  13723. LLM_NORM_RMS, cb, il);
  13724. cb(cur, "attn_norm_cross", il);
  13725. // cross-attention
  13726. {
  13727. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq_cross, cur);
  13728. cb(Qcur, "Qcur", il);
  13729. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk_cross, embd_enc);
  13730. cb(Kcur, "Kcur", il);
  13731. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv_cross, embd_enc);
  13732. cb(Vcur, "Vcur", il);
  13733. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  13734. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_outputs_enc);
  13735. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  13736. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  13737. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  13738. cb(kq, "kq", il);
  13739. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask_cross, 1.0f, hparams.f_max_alibi_bias);
  13740. cb(kq, "kq_soft_max_ext", il);
  13741. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_outputs_enc)));
  13742. cb(v, "v", il);
  13743. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_outputs_enc, n_embd_head, n_head_kv), kq);
  13744. cb(kqv, "kqv", il);
  13745. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  13746. cb(kqv_merged, "kqv_merged", il);
  13747. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  13748. cb(cur, "kqv_merged_cont", il);
  13749. ggml_build_forward_expand(gf, cur);
  13750. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo_cross, cur);
  13751. cb(cur, "kqv_out", il);
  13752. }
  13753. if (il == n_layer - 1) {
  13754. // skip computing output for unused tokens
  13755. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13756. n_tokens = n_outputs;
  13757. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13758. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13759. inpCA = ggml_get_rows(ctx0, inpCA, inp_out_ids);
  13760. }
  13761. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpCA);
  13762. cb(ffn_inp, "ffn_inp", il);
  13763. // feed-forward network
  13764. {
  13765. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13766. model.layers[il].ffn_norm, NULL,
  13767. LLM_NORM_RMS, cb, il);
  13768. cb(cur, "ffn_norm", il);
  13769. // T5 uses relu, flan-T5 uses gelu-gated
  13770. cur = llm_build_ffn(ctx0, lctx, cur,
  13771. model.layers[il].ffn_up, NULL, NULL,
  13772. model.layers[il].ffn_gate, NULL, NULL,
  13773. model.layers[il].ffn_down, NULL, NULL,
  13774. NULL,
  13775. model.layers[il].ffn_gate_enc ? LLM_FFN_GELU : LLM_FFN_RELU,
  13776. model.layers[il].ffn_gate_enc ? LLM_FFN_PAR : LLM_FFN_SEQ,
  13777. cb, il);
  13778. cb(cur, "ffn_out", il);
  13779. }
  13780. cur = ggml_add(ctx0, cur, ffn_inp);
  13781. cb(cur, "ffn_out", il);
  13782. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  13783. if (layer_dir != nullptr) {
  13784. cur = ggml_add(ctx0, cur, layer_dir);
  13785. }
  13786. cb(cur, "l_out", il);
  13787. // input for next layer
  13788. inpL = cur;
  13789. }
  13790. cur = inpL;
  13791. cb(cur, "result_embd", -1);
  13792. cur = llm_build_norm(ctx0, cur, hparams,
  13793. model.output_norm, NULL,
  13794. LLM_NORM_RMS, cb, -1);
  13795. cb(cur, "result_norm", -1);
  13796. // lm_head
  13797. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13798. cb(cur, "result_output", -1);
  13799. ggml_build_forward_expand(gf, cur);
  13800. return gf;
  13801. }
  13802. struct ggml_cgraph * build_jais() {
  13803. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13804. const int64_t n_embd_head = hparams.n_embd_head_v;
  13805. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  13806. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13807. struct ggml_tensor * cur;
  13808. struct ggml_tensor * inpL;
  13809. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13810. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13811. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13812. for (int il = 0; il < n_layer; ++il) {
  13813. cur = llm_build_norm(ctx0, inpL, hparams,
  13814. model.layers[il].attn_norm,
  13815. model.layers[il].attn_norm_b,
  13816. LLM_NORM, cb, il);
  13817. cb(cur, "attn_norm", il);
  13818. // self-attention
  13819. {
  13820. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  13821. cb(cur, "wqkv", il);
  13822. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  13823. cb(cur, "bqkv", il);
  13824. 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)));
  13825. 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)));
  13826. 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)));
  13827. cb(Qcur, "Qcur", il);
  13828. cb(Kcur, "Kcur", il);
  13829. cb(Vcur, "Vcur", il);
  13830. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  13831. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13832. model.layers[il].wo, model.layers[il].bo,
  13833. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/float(n_embd_head), cb, il);
  13834. }
  13835. if (il == n_layer - 1) {
  13836. // skip computing output for unused tokens
  13837. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13838. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13839. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  13840. }
  13841. // add the input
  13842. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  13843. cb(ffn_inp, "ffn_inp", il);
  13844. // FF
  13845. {
  13846. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13847. model.layers[il].ffn_norm,
  13848. model.layers[il].ffn_norm_b,
  13849. LLM_NORM, cb, il);
  13850. cb(cur, "ffn_norm", il);
  13851. cur = llm_build_ffn(ctx0, lctx, cur,
  13852. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  13853. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  13854. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  13855. NULL,
  13856. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13857. cb(cur, "ffn_out", il);
  13858. }
  13859. inpL = ggml_add(ctx0, cur, ffn_inp);
  13860. cb(inpL, "l_out", il);
  13861. }
  13862. cur = llm_build_norm(ctx0, inpL, hparams,
  13863. model.output_norm,
  13864. model.output_norm_b,
  13865. LLM_NORM, cb, -1);
  13866. cb(cur, "result_norm", -1);
  13867. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13868. cb(cur, "result_output", -1);
  13869. ggml_build_forward_expand(gf, cur);
  13870. return gf;
  13871. }
  13872. struct ggml_cgraph * build_chatglm() {
  13873. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13874. const int64_t n_embd_head = hparams.n_embd_head_v;
  13875. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  13876. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13877. struct ggml_tensor * cur;
  13878. struct ggml_tensor * inpL;
  13879. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13880. // inp_pos - contains the positions
  13881. struct ggml_tensor * inp_pos = build_inp_pos();
  13882. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13883. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13884. for (int il = 0; il < n_layer; ++il) {
  13885. struct ggml_tensor * inpSA = inpL;
  13886. cur = llm_build_norm(ctx0, inpL, hparams,
  13887. model.layers[il].attn_norm,
  13888. NULL,
  13889. LLM_NORM_RMS, cb, il);
  13890. cb(cur, "attn_norm", il);
  13891. // self-attention
  13892. {
  13893. struct ggml_tensor * Qcur = nullptr;
  13894. struct ggml_tensor * Kcur = nullptr;
  13895. struct ggml_tensor * Vcur = nullptr;
  13896. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  13897. cb(cur, "wqkv", il);
  13898. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  13899. cb(cur, "bqkv", il);
  13900. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  13901. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  13902. 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)));
  13903. cb(Qcur, "Qcur", il);
  13904. cb(Kcur, "Kcur", il);
  13905. cb(Vcur, "Vcur", il);
  13906. //printf("freq_base: %f freq_scale: %f ext_factor: %f attn_factor: %f\n", freq_base, freq_scale, ext_factor, attn_factor);
  13907. Qcur = ggml_rope_ext(
  13908. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  13909. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13910. ext_factor, attn_factor, beta_fast, beta_slow
  13911. );
  13912. cb(Qcur, "Qcur_rope", il);
  13913. Kcur = ggml_rope_ext(
  13914. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  13915. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13916. ext_factor, attn_factor, beta_fast, beta_slow
  13917. );
  13918. cb(Kcur, "Kcur_rope", il);
  13919. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13920. model.layers[il].wo, NULL,
  13921. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13922. }
  13923. if (il == n_layer - 1) {
  13924. // skip computing output for unused tokens
  13925. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13926. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13927. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13928. }
  13929. // Add the input
  13930. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13931. cb(ffn_inp, "ffn_inp", il);
  13932. // FF
  13933. {
  13934. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13935. model.layers[il].ffn_norm,
  13936. NULL,
  13937. LLM_NORM_RMS, cb, il);
  13938. cb(cur, "ffn_norm", il);
  13939. cur = llm_build_ffn(ctx0, lctx, cur,
  13940. model.layers[il].ffn_up, NULL, NULL,
  13941. NULL, NULL, NULL,
  13942. model.layers[il].ffn_down, NULL, NULL,
  13943. NULL,
  13944. LLM_FFN_SWIGLU, LLM_FFN_SEQ, cb, il);
  13945. cb(cur, "ffn_out", il);
  13946. }
  13947. inpL = ggml_add(ctx0, cur, ffn_inp);
  13948. cb(inpL, "l_out", il);
  13949. }
  13950. cur = llm_build_norm(ctx0, inpL, hparams,
  13951. model.output_norm,
  13952. NULL,
  13953. LLM_NORM_RMS, cb, -1);
  13954. cb(cur, "result_norm", -1);
  13955. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13956. cb(cur, "result_output", -1);
  13957. ggml_build_forward_expand(gf, cur);
  13958. return gf;
  13959. }
  13960. struct ggml_cgraph * build_nemotron() {
  13961. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13962. const int64_t n_embd_head = hparams.n_embd_head_v;
  13963. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13964. //GGML_ASSERT(n_embd_head == hparams.n_rot);
  13965. struct ggml_tensor * cur;
  13966. struct ggml_tensor * inpL;
  13967. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13968. // inp_pos - contains the positions
  13969. struct ggml_tensor * inp_pos = build_inp_pos();
  13970. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13971. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13972. for (int il = 0; il < n_layer; ++il) {
  13973. struct ggml_tensor * inpSA = inpL;
  13974. // norm
  13975. cur = llm_build_norm(ctx0, inpL, hparams,
  13976. model.layers[il].attn_norm,
  13977. model.layers[il].attn_norm_b,
  13978. LLM_NORM, cb, il);
  13979. cb(cur, "attn_norm", il);
  13980. // self-attention
  13981. {
  13982. // compute Q and K and RoPE them
  13983. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  13984. cb(Qcur, "Qcur", il);
  13985. if (model.layers[il].bq) {
  13986. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  13987. cb(Qcur, "Qcur", il);
  13988. }
  13989. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  13990. cb(Kcur, "Kcur", il);
  13991. if (model.layers[il].bk) {
  13992. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  13993. cb(Kcur, "Kcur", il);
  13994. }
  13995. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  13996. cb(Vcur, "Vcur", il);
  13997. if (model.layers[il].bv) {
  13998. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  13999. cb(Vcur, "Vcur", il);
  14000. }
  14001. Qcur = ggml_rope_ext(
  14002. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  14003. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  14004. ext_factor, attn_factor, beta_fast, beta_slow
  14005. );
  14006. cb(Qcur, "Qcur", il);
  14007. Kcur = ggml_rope_ext(
  14008. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  14009. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  14010. ext_factor, attn_factor, beta_fast, beta_slow
  14011. );
  14012. cb(Kcur, "Kcur", il);
  14013. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  14014. model.layers[il].wo, model.layers[il].bo,
  14015. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  14016. }
  14017. if (il == n_layer - 1) {
  14018. // skip computing output for unused tokens
  14019. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  14020. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  14021. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  14022. }
  14023. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  14024. cb(ffn_inp, "ffn_inp", il);
  14025. // feed-forward network
  14026. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  14027. model.layers[il].ffn_norm,
  14028. model.layers[il].ffn_norm_b,
  14029. LLM_NORM, cb, il);
  14030. cb(cur, "ffn_norm", il);
  14031. cur = llm_build_ffn(ctx0, lctx, cur,
  14032. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  14033. NULL, NULL, NULL,
  14034. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  14035. NULL,
  14036. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  14037. cur = ggml_add(ctx0, cur, ffn_inp);
  14038. cb(cur, "ffn_out", il);
  14039. cur = lctx.cvec.apply_to(ctx0, cur, il);
  14040. cb(cur, "l_out", il);
  14041. // input for next layer
  14042. inpL = cur;
  14043. }
  14044. cur = inpL;
  14045. cur = llm_build_norm(ctx0, cur, hparams,
  14046. model.output_norm, model.output_norm_b,
  14047. LLM_NORM, cb, -1);
  14048. cb(cur, "result_norm", -1);
  14049. // lm_head
  14050. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  14051. cb(cur, "result_output", -1);
  14052. ggml_build_forward_expand(gf, cur);
  14053. return gf;
  14054. }
  14055. struct ggml_cgraph * build_exaone() {
  14056. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  14057. // mutable variable, needed during the last layer of the computation to skip unused tokens
  14058. int32_t n_tokens = this->n_tokens;
  14059. const int64_t n_embd_head = hparams.n_embd_head_v;
  14060. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  14061. GGML_ASSERT(n_embd_head == hparams.n_rot);
  14062. struct ggml_tensor * cur;
  14063. struct ggml_tensor * inpL;
  14064. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  14065. // inp_pos - contains the positions
  14066. struct ggml_tensor * inp_pos = build_inp_pos();
  14067. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  14068. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  14069. for (int il = 0; il < n_layer; ++il) {
  14070. struct ggml_tensor * inpSA = inpL;
  14071. // norm
  14072. cur = llm_build_norm(ctx0, inpL, hparams,
  14073. model.layers[il].attn_norm, NULL,
  14074. LLM_NORM_RMS, cb, il);
  14075. cb(cur, "attn_norm", il);
  14076. // self-attention
  14077. {
  14078. // rope freq factors for llama3; may return nullptr for llama2 and other models
  14079. struct ggml_tensor * rope_factors = build_rope_factors(il);
  14080. // compute Q and K and RoPE them
  14081. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  14082. cb(Qcur, "Qcur", il);
  14083. if (model.layers[il].bq) {
  14084. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  14085. cb(Qcur, "Qcur", il);
  14086. }
  14087. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  14088. cb(Kcur, "Kcur", il);
  14089. if (model.layers[il].bk) {
  14090. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  14091. cb(Kcur, "Kcur", il);
  14092. }
  14093. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  14094. cb(Vcur, "Vcur", il);
  14095. if (model.layers[il].bv) {
  14096. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  14097. cb(Vcur, "Vcur", il);
  14098. }
  14099. Qcur = ggml_rope_ext(
  14100. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  14101. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  14102. ext_factor, attn_factor, beta_fast, beta_slow
  14103. );
  14104. cb(Qcur, "Qcur", il);
  14105. Kcur = ggml_rope_ext(
  14106. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  14107. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  14108. ext_factor, attn_factor, beta_fast, beta_slow
  14109. );
  14110. cb(Kcur, "Kcur", il);
  14111. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  14112. model.layers[il].wo, model.layers[il].bo,
  14113. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  14114. }
  14115. if (il == n_layer - 1) {
  14116. // skip computing output for unused tokens
  14117. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  14118. n_tokens = n_outputs;
  14119. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  14120. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  14121. }
  14122. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  14123. cb(ffn_inp, "ffn_inp", il);
  14124. // feed-forward network
  14125. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  14126. model.layers[il].ffn_norm, NULL,
  14127. LLM_NORM_RMS, cb, il);
  14128. cb(cur, "ffn_norm", il);
  14129. cur = llm_build_ffn(ctx0, lctx, cur,
  14130. model.layers[il].ffn_up, NULL, NULL,
  14131. model.layers[il].ffn_gate, NULL, NULL,
  14132. model.layers[il].ffn_down, NULL, NULL,
  14133. NULL,
  14134. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  14135. cb(cur, "ffn_out", il);
  14136. cur = ggml_add(ctx0, cur, ffn_inp);
  14137. cb(cur, "ffn_out", il);
  14138. cur = lctx.cvec.apply_to(ctx0, cur, il);
  14139. cb(cur, "l_out", il);
  14140. // input for next layer
  14141. inpL = cur;
  14142. }
  14143. cur = inpL;
  14144. cur = llm_build_norm(ctx0, cur, hparams,
  14145. model.output_norm, NULL,
  14146. LLM_NORM_RMS, cb, -1);
  14147. cb(cur, "result_norm", -1);
  14148. // lm_head
  14149. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  14150. cb(cur, "result_output", -1);
  14151. ggml_build_forward_expand(gf, cur);
  14152. return gf;
  14153. }
  14154. ggml_cgraph * build_rwkv6() {
  14155. ggml_cgraph *gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  14156. // Token shift state dimensions should be 2 * n_emb
  14157. GGML_ASSERT(n_embd == hparams.n_embd_k_s() / 2);
  14158. const int64_t n_seqs = ubatch.n_seqs;
  14159. const int64_t n_seq_tokens = ubatch.n_seq_tokens;
  14160. const int64_t n_tokens = ubatch.n_tokens;
  14161. GGML_ASSERT(n_seqs != 0);
  14162. GGML_ASSERT(ubatch.equal_seqs);
  14163. GGML_ASSERT(n_tokens == n_seq_tokens * n_seqs);
  14164. struct ggml_tensor * cur;
  14165. struct ggml_tensor * inpL;
  14166. struct ggml_tensor * state_copy = build_inp_s_copy();
  14167. struct ggml_tensor * state_mask = build_inp_s_mask();
  14168. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  14169. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  14170. for (int il = 0; il < n_layer; ++il) {
  14171. const llama_layer * layer = &model.layers[il];
  14172. // (ab)using the KV cache to store the states
  14173. struct ggml_tensor * token_shift = llm_build_copy_mask_state(ctx0,
  14174. gf, kv_self.k_l[il], state_copy, state_mask,
  14175. hparams.n_embd_k_s(), kv_self.size, kv_head, n_kv, n_seqs);
  14176. struct ggml_tensor * wkv_states = llm_build_copy_mask_state(ctx0,
  14177. gf, kv_self.v_l[il], state_copy, state_mask,
  14178. hparams.n_embd_v_s(), kv_self.size, kv_head, n_kv, n_seqs);
  14179. cur = ggml_reshape_3d(ctx0, inpL, n_embd, n_seq_tokens, n_seqs);
  14180. token_shift = ggml_reshape_3d(ctx0, token_shift, n_embd, 2, n_seqs);
  14181. 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);
  14182. 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));
  14183. struct ggml_tensor * x_norm_att = llm_build_norm(ctx0, cur, hparams, layer->attn_norm, layer->attn_norm_b, LLM_NORM, cb, il);
  14184. struct ggml_tensor * x_prev = ggml_concat(
  14185. ctx0,
  14186. att_shift,
  14187. 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),
  14188. 1
  14189. );
  14190. cur = ggml_add(ctx0, cur, llm_build_rwkv6_time_mix(lctx, ctx0, layer, x_norm_att, x_prev, &wkv_states));
  14191. ggml_build_forward_expand(gf, cur);
  14192. ggml_build_forward_expand(
  14193. gf,
  14194. ggml_cpy(
  14195. ctx0,
  14196. wkv_states,
  14197. ggml_view_1d(
  14198. ctx0,
  14199. kv_self.v_l[il],
  14200. hparams.n_embd_v_s() * n_seqs,
  14201. hparams.n_embd_v_s() * kv_head * ggml_element_size(kv_self.v_l[il])
  14202. )
  14203. )
  14204. );
  14205. 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);
  14206. x_prev = ggml_concat(
  14207. ctx0,
  14208. ffn_shift,
  14209. 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),
  14210. 1
  14211. );
  14212. cur = ggml_add(ctx0, cur, llm_build_rwkv6_channel_mix(lctx, ctx0, layer, x_norm_ffn, x_prev));
  14213. ggml_build_forward_expand(gf, cur);
  14214. 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));
  14215. 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));
  14216. token_shift = ggml_concat(ctx0, last_norm_att, last_norm_ffn, 1);
  14217. ggml_build_forward_expand(
  14218. gf,
  14219. ggml_cpy(
  14220. ctx0,
  14221. ggml_view_1d(ctx0, token_shift, n_embd * n_seqs * 2, 0),
  14222. 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]))
  14223. )
  14224. );
  14225. if (hparams.rescale_every_n_layers != 0 && (il + 1) % hparams.rescale_every_n_layers == 0) {
  14226. cur = ggml_scale(ctx0, cur, 0.5F);
  14227. }
  14228. cur = lctx.cvec.apply_to(ctx0, cur, il);
  14229. cb(cur, "l_out", il);
  14230. // input for next layer
  14231. inpL = cur;
  14232. }
  14233. cur = inpL;
  14234. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  14235. cur = ggml_reshape_2d(ctx0, cur, n_embd, n_tokens);
  14236. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  14237. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, model.output_norm_b, LLM_NORM, cb, -1);
  14238. cb(cur, "result_norm", -1);
  14239. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  14240. cb(cur, "result_output", -1);
  14241. ggml_build_forward_expand(gf, cur);
  14242. return gf;
  14243. }
  14244. // ref: https://github.com/facebookresearch/chameleon
  14245. // based on the original build_llama() function, changes:
  14246. // * qk-norm
  14247. // * swin-norm
  14248. // * removed bias
  14249. // * removed MoE
  14250. struct ggml_cgraph * build_chameleon() {
  14251. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  14252. // mutable variable, needed during the last layer of the computation to skip unused tokens
  14253. int32_t n_tokens = this->n_tokens;
  14254. const int64_t n_embd_head = hparams.n_embd_head_v;
  14255. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  14256. GGML_ASSERT(n_embd_head == hparams.n_rot);
  14257. struct ggml_tensor * cur;
  14258. struct ggml_tensor * inpL;
  14259. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  14260. // inp_pos - contains the positions
  14261. struct ggml_tensor * inp_pos = build_inp_pos();
  14262. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  14263. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  14264. for (int il = 0; il < n_layer; ++il) {
  14265. struct ggml_tensor * inpSA = inpL;
  14266. // norm
  14267. if (hparams.swin_norm) {
  14268. cur = inpL;
  14269. } else {
  14270. cur = llm_build_norm(ctx0, inpL, hparams,
  14271. model.layers[il].attn_norm, NULL,
  14272. LLM_NORM_RMS, cb, il);
  14273. cb(cur, "attn_norm", il);
  14274. }
  14275. // self-attention
  14276. {
  14277. // compute Q and K and RoPE them
  14278. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  14279. cb(Qcur, "Qcur", il);
  14280. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  14281. cb(Kcur, "Kcur", il);
  14282. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  14283. cb(Vcur, "Vcur", il);
  14284. if (model.layers[il].attn_q_norm) {
  14285. Qcur = ggml_view_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens,
  14286. ggml_element_size(Qcur) * n_embd_head,
  14287. ggml_element_size(Qcur) * n_embd_head * n_head,
  14288. 0);
  14289. cb(Qcur, "Qcur", il);
  14290. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  14291. model.layers[il].attn_q_norm,
  14292. model.layers[il].attn_q_norm_b,
  14293. LLM_NORM, cb, il);
  14294. cb(Qcur, "Qcur", il);
  14295. }
  14296. if (model.layers[il].attn_k_norm) {
  14297. Kcur = ggml_view_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens,
  14298. ggml_element_size(Kcur) * n_embd_head,
  14299. ggml_element_size(Kcur) * n_embd_head * n_head_kv,
  14300. 0);
  14301. cb(Kcur, "Kcur", il);
  14302. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  14303. model.layers[il].attn_k_norm,
  14304. model.layers[il].attn_k_norm_b,
  14305. LLM_NORM, cb, il);
  14306. cb(Kcur, "Kcur", il);
  14307. }
  14308. Qcur = ggml_rope_ext(
  14309. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  14310. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  14311. ext_factor, attn_factor, beta_fast, beta_slow
  14312. );
  14313. cb(Qcur, "Qcur", il);
  14314. Kcur = ggml_rope_ext(
  14315. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  14316. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  14317. ext_factor, attn_factor, beta_fast, beta_slow
  14318. );
  14319. cb(Kcur, "Kcur", il);
  14320. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  14321. model.layers[il].wo, nullptr,
  14322. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  14323. if (hparams.swin_norm) {
  14324. cur = llm_build_norm(ctx0, cur, hparams,
  14325. model.layers[il].attn_norm, NULL,
  14326. LLM_NORM_RMS, cb, il);
  14327. }
  14328. }
  14329. if (il == n_layer - 1) {
  14330. // skip computing output for unused tokens
  14331. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  14332. n_tokens = n_outputs;
  14333. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  14334. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  14335. }
  14336. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  14337. cb(ffn_inp, "ffn_inp", il);
  14338. // feed-forward network
  14339. if (!hparams.swin_norm) {
  14340. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  14341. model.layers[il].ffn_norm, NULL,
  14342. LLM_NORM_RMS, cb, il);
  14343. cb(cur, "ffn_norm", il);
  14344. }
  14345. cur = llm_build_ffn(ctx0, lctx, cur,
  14346. model.layers[il].ffn_up, NULL, NULL,
  14347. model.layers[il].ffn_gate, NULL, NULL,
  14348. model.layers[il].ffn_down, NULL, NULL,
  14349. NULL,
  14350. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  14351. cb(cur, "ffn_out", il);
  14352. if (hparams.swin_norm) {
  14353. cur = llm_build_norm(ctx0, cur, hparams,
  14354. model.layers[il].ffn_norm, NULL,
  14355. LLM_NORM_RMS, cb, il);
  14356. cb(cur, "ffn_norm", il);
  14357. }
  14358. cur = ggml_add(ctx0, cur, ffn_inp);
  14359. cb(cur, "ffn_out", il);
  14360. cur = lctx.cvec.apply_to(ctx0, cur, il);
  14361. cb(cur, "l_out", il);
  14362. // input for next layer
  14363. inpL = cur;
  14364. }
  14365. cur = inpL;
  14366. cur = llm_build_norm(ctx0, cur, hparams,
  14367. model.output_norm, NULL,
  14368. LLM_NORM_RMS, cb, -1);
  14369. cb(cur, "result_norm", -1);
  14370. // lm_head
  14371. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  14372. cb(cur, "result_output_with_img_logits", -1);
  14373. // TODO: this suppresses the output of image tokens, which is required to enable text-only outputs.
  14374. // Needs to be removed once image outputs are supported.
  14375. int img_token_end_idx = 8196;
  14376. int img_token_start_idx = 4;
  14377. int num_img_tokens = img_token_end_idx - img_token_start_idx;
  14378. // creates 1d tensor of size num_img_tokens and values -FLT_MAX,
  14379. // which ensures that text token values are always at least larger than image token values
  14380. struct ggml_tensor * img_logits = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, num_img_tokens);
  14381. img_logits = ggml_clamp(ctx0, img_logits, -FLT_MAX, -FLT_MAX);
  14382. cb(img_logits, "img_logits", -1);
  14383. cur = ggml_set_1d(ctx0, cur, img_logits, ggml_element_size(cur) * img_token_start_idx);
  14384. cb(cur, "result_output", -1);
  14385. ggml_build_forward_expand(gf, cur);
  14386. return gf;
  14387. }
  14388. ggml_cgraph * build_solar() {
  14389. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  14390. // mutable variable, needed during the last layer of the computation to skip unused tokens
  14391. int32_t n_tokens = this->n_tokens;
  14392. const int64_t n_embd_head = hparams.n_embd_head_v;
  14393. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  14394. GGML_ASSERT(n_embd_head == hparams.n_rot);
  14395. struct ggml_tensor * cur;
  14396. struct ggml_tensor * inpL;
  14397. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  14398. // inp_pos - contains the positions
  14399. struct ggml_tensor * inp_pos = build_inp_pos();
  14400. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  14401. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  14402. struct ggml_tensor * bskcn_1;
  14403. struct ggml_tensor * bskcn_2;
  14404. for (int il = 0; il < n_layer; ++il) {
  14405. struct ggml_tensor * inpSA = inpL;
  14406. if (hparams.n_bskcn(0, il)) {
  14407. bskcn_1 = inpSA;
  14408. }
  14409. if (hparams.n_bskcn(1, il)) {
  14410. bskcn_2 = inpSA;
  14411. }
  14412. if (hparams.n_bskcn(2, il)) {
  14413. inpSA = ggml_add(
  14414. ctx0,
  14415. ggml_mul(ctx0, bskcn_1, ggml_view_1d(ctx0, model.layers[il].bskcn_tv, 1, 0)),
  14416. ggml_mul(ctx0, inpSA, ggml_view_1d(ctx0, model.layers[il].bskcn_tv, 1, ggml_element_size(model.layers[il].bskcn_tv))));
  14417. }
  14418. if (hparams.n_bskcn(3, il)) {
  14419. inpSA = ggml_add(
  14420. ctx0,
  14421. ggml_mul(ctx0, bskcn_2, ggml_view_1d(ctx0, model.layers[il].bskcn_tv, 1, 0)),
  14422. ggml_mul(ctx0, inpSA, ggml_view_1d(ctx0, model.layers[il].bskcn_tv, 1, ggml_element_size(model.layers[il].bskcn_tv))));
  14423. }
  14424. // norm
  14425. cur = llm_build_norm(ctx0, inpL, hparams,
  14426. model.layers[il].attn_norm, NULL,
  14427. LLM_NORM_RMS, cb, il);
  14428. cb(cur, "attn_norm", il);
  14429. // self-attention
  14430. {
  14431. // rope freq factors for llama3; may return nullptr for llama2 and other models
  14432. struct ggml_tensor * rope_factors = build_rope_factors(il);
  14433. // compute Q and K and RoPE them
  14434. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  14435. cb(Qcur, "Qcur", il);
  14436. if (model.layers[il].bq) {
  14437. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  14438. cb(Qcur, "Qcur", il);
  14439. }
  14440. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  14441. cb(Kcur, "Kcur", il);
  14442. if (model.layers[il].bk) {
  14443. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  14444. cb(Kcur, "Kcur", il);
  14445. }
  14446. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  14447. cb(Vcur, "Vcur", il);
  14448. if (model.layers[il].bv) {
  14449. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  14450. cb(Vcur, "Vcur", il);
  14451. }
  14452. Qcur = ggml_rope_ext(
  14453. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  14454. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  14455. ext_factor, attn_factor, beta_fast, beta_slow
  14456. );
  14457. cb(Qcur, "Qcur", il);
  14458. Kcur = ggml_rope_ext(
  14459. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  14460. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  14461. ext_factor, attn_factor, beta_fast, beta_slow
  14462. );
  14463. cb(Kcur, "Kcur", il);
  14464. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  14465. model.layers[il].wo, model.layers[il].bo,
  14466. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  14467. }
  14468. if (il == n_layer - 1) {
  14469. // skip computing output for unused tokens
  14470. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  14471. n_tokens = n_outputs;
  14472. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  14473. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  14474. }
  14475. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  14476. cb(ffn_inp, "ffn_inp", il);
  14477. // feed-forward network
  14478. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  14479. model.layers[il].ffn_norm, NULL,
  14480. LLM_NORM_RMS, cb, il);
  14481. cb(cur, "ffn_norm", il);
  14482. cur = llm_build_ffn(ctx0, lctx, cur,
  14483. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  14484. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  14485. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  14486. NULL,
  14487. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  14488. cb(cur, "ffn_out", il);
  14489. cur = ggml_add(ctx0, cur, ffn_inp);
  14490. cb(cur, "ffn_out", il);
  14491. cur = lctx.cvec.apply_to(ctx0, cur, il);
  14492. cb(cur, "l_out", il);
  14493. // input for next layer
  14494. inpL = cur;
  14495. }
  14496. cur = inpL;
  14497. cur = llm_build_norm(ctx0, cur, hparams,
  14498. model.output_norm, NULL,
  14499. LLM_NORM_RMS, cb, -1);
  14500. cb(cur, "result_norm", -1);
  14501. // lm_head
  14502. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  14503. cb(cur, "result_output", -1);
  14504. ggml_build_forward_expand(gf, cur);
  14505. return gf;
  14506. }
  14507. };
  14508. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<struct llama_kv_defrag_move> & moves) {
  14509. llama_ubatch dummy = {};
  14510. dummy.equal_seqs = true;
  14511. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  14512. struct llm_build_context llm(lctx, dummy, cb, false);
  14513. llm.init();
  14514. struct ggml_cgraph * result = llm.build_defrag(moves);
  14515. llm.free();
  14516. return result;
  14517. }
  14518. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  14519. llama_ubatch dummy = {};
  14520. dummy.equal_seqs = true;
  14521. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  14522. struct llm_build_context llm(lctx, dummy, cb, false);
  14523. llm.init();
  14524. struct ggml_cgraph * result = llm.build_k_shift();
  14525. llm.free();
  14526. return result;
  14527. }
  14528. static struct ggml_cgraph * llama_build_graph(
  14529. llama_context & lctx,
  14530. const llama_ubatch & ubatch,
  14531. bool worst_case) {
  14532. const auto & model = lctx.model;
  14533. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  14534. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  14535. if (il >= 0) {
  14536. ggml_format_name(cur, "%s-%d", name, il);
  14537. } else {
  14538. ggml_set_name(cur, name);
  14539. }
  14540. if (!lctx.cparams.offload_kqv) {
  14541. if (strcmp(name, "kqv_merged_cont") == 0) {
  14542. // all nodes between the KV store and the attention output are run on the CPU
  14543. ggml_backend_sched_set_tensor_backend(lctx.sched.get(), cur, lctx.backend_cpu);
  14544. }
  14545. }
  14546. // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
  14547. // FIXME: fix in ggml_backend_sched
  14548. const bool full_offload = lctx.model.n_gpu_layers > (int)lctx.model.hparams.n_layer;
  14549. if (ubatch.n_tokens < 32 || full_offload) {
  14550. if (il != -1 && strcmp(name, "norm") == 0) {
  14551. const auto & dev_layer = lctx.model.dev_layer.at(il);
  14552. for (auto & backend : lctx.backends) {
  14553. if (ggml_backend_get_device(backend.get()) == dev_layer.dev) {
  14554. if (ggml_backend_supports_op(backend.get(), cur)) {
  14555. ggml_backend_sched_set_tensor_backend(lctx.sched.get(), cur, backend.get());
  14556. }
  14557. }
  14558. }
  14559. }
  14560. }
  14561. };
  14562. struct ggml_cgraph * result = NULL;
  14563. struct llm_build_context llm(lctx, ubatch, cb, worst_case);
  14564. llm.init();
  14565. switch (model.arch) {
  14566. case LLM_ARCH_LLAMA:
  14567. case LLM_ARCH_MINICPM:
  14568. case LLM_ARCH_GRANITE:
  14569. case LLM_ARCH_GRANITE_MOE:
  14570. {
  14571. result = llm.build_llama();
  14572. } break;
  14573. case LLM_ARCH_MLLAMA:
  14574. {
  14575. result = llm.build_mllama();
  14576. } break;
  14577. case LLM_ARCH_BAICHUAN:
  14578. {
  14579. result = llm.build_baichuan();
  14580. } break;
  14581. case LLM_ARCH_FALCON:
  14582. {
  14583. result = llm.build_falcon();
  14584. } break;
  14585. case LLM_ARCH_GROK:
  14586. {
  14587. result = llm.build_grok();
  14588. } break;
  14589. case LLM_ARCH_STARCODER:
  14590. {
  14591. result = llm.build_starcoder();
  14592. } break;
  14593. case LLM_ARCH_REFACT:
  14594. {
  14595. result = llm.build_refact();
  14596. } break;
  14597. case LLM_ARCH_BERT:
  14598. case LLM_ARCH_JINA_BERT_V2:
  14599. case LLM_ARCH_NOMIC_BERT:
  14600. {
  14601. result = llm.build_bert();
  14602. } break;
  14603. case LLM_ARCH_BLOOM:
  14604. {
  14605. result = llm.build_bloom();
  14606. } break;
  14607. case LLM_ARCH_MPT:
  14608. {
  14609. result = llm.build_mpt();
  14610. } break;
  14611. case LLM_ARCH_STABLELM:
  14612. {
  14613. result = llm.build_stablelm();
  14614. } break;
  14615. case LLM_ARCH_QWEN:
  14616. {
  14617. result = llm.build_qwen();
  14618. } break;
  14619. case LLM_ARCH_QWEN2:
  14620. {
  14621. result = llm.build_qwen2();
  14622. } break;
  14623. case LLM_ARCH_QWEN2VL:
  14624. {
  14625. lctx.n_pos_per_token = 4;
  14626. result = llm.build_qwen2vl();
  14627. } break;
  14628. case LLM_ARCH_QWEN2MOE:
  14629. {
  14630. result = llm.build_qwen2moe();
  14631. } break;
  14632. case LLM_ARCH_PHI2:
  14633. {
  14634. result = llm.build_phi2();
  14635. } break;
  14636. case LLM_ARCH_PHI3:
  14637. {
  14638. result = llm.build_phi3();
  14639. } break;
  14640. case LLM_ARCH_PLAMO:
  14641. {
  14642. result = llm.build_plamo();
  14643. } break;
  14644. case LLM_ARCH_GPT2:
  14645. {
  14646. result = llm.build_gpt2();
  14647. } break;
  14648. case LLM_ARCH_CODESHELL:
  14649. {
  14650. result = llm.build_codeshell();
  14651. } break;
  14652. case LLM_ARCH_ORION:
  14653. {
  14654. result = llm.build_orion();
  14655. } break;
  14656. case LLM_ARCH_INTERNLM2:
  14657. {
  14658. result = llm.build_internlm2();
  14659. } break;
  14660. case LLM_ARCH_MINICPM3:
  14661. {
  14662. result = llm.build_minicpm3();
  14663. } break;
  14664. case LLM_ARCH_GEMMA:
  14665. {
  14666. result = llm.build_gemma();
  14667. } break;
  14668. case LLM_ARCH_GEMMA2:
  14669. {
  14670. result = llm.build_gemma2();
  14671. } break;
  14672. case LLM_ARCH_STARCODER2:
  14673. {
  14674. result = llm.build_starcoder2();
  14675. } break;
  14676. case LLM_ARCH_MAMBA:
  14677. {
  14678. result = llm.build_mamba();
  14679. } break;
  14680. case LLM_ARCH_XVERSE:
  14681. {
  14682. result = llm.build_xverse();
  14683. } break;
  14684. case LLM_ARCH_COMMAND_R:
  14685. {
  14686. result = llm.build_command_r();
  14687. } break;
  14688. case LLM_ARCH_DBRX:
  14689. {
  14690. result = llm.build_dbrx();
  14691. } break;
  14692. case LLM_ARCH_OLMO:
  14693. {
  14694. result = llm.build_olmo();
  14695. } break;
  14696. case LLM_ARCH_OLMO2:
  14697. {
  14698. result = llm.build_olmo2();
  14699. } break;
  14700. case LLM_ARCH_OLMOE:
  14701. {
  14702. result = llm.build_olmoe();
  14703. } break;
  14704. case LLM_ARCH_OPENELM:
  14705. {
  14706. result = llm.build_openelm();
  14707. } break;
  14708. case LLM_ARCH_GPTNEOX:
  14709. {
  14710. result = llm.build_gptneox();
  14711. } break;
  14712. case LLM_ARCH_ARCTIC:
  14713. {
  14714. result = llm.build_arctic();
  14715. } break;
  14716. case LLM_ARCH_DEEPSEEK2:
  14717. {
  14718. result = llm.build_deepseek2();
  14719. } break;
  14720. case LLM_ARCH_CHATGLM:
  14721. {
  14722. result = llm.build_chatglm();
  14723. } break;
  14724. case LLM_ARCH_BITNET:
  14725. {
  14726. result = llm.build_bitnet();
  14727. } break;
  14728. case LLM_ARCH_T5:
  14729. {
  14730. if (lctx.is_encoding) {
  14731. result = llm.build_t5_encoder();
  14732. } else {
  14733. result = llm.build_t5_decoder();
  14734. }
  14735. } break;
  14736. case LLM_ARCH_T5ENCODER:
  14737. {
  14738. result = llm.build_t5_encoder();
  14739. } break;
  14740. case LLM_ARCH_JAIS:
  14741. {
  14742. result = llm.build_jais();
  14743. } break;
  14744. case LLM_ARCH_NEMOTRON:
  14745. {
  14746. result = llm.build_nemotron();
  14747. } break;
  14748. case LLM_ARCH_EXAONE:
  14749. {
  14750. result = llm.build_exaone();
  14751. } break;
  14752. case LLM_ARCH_RWKV6:
  14753. {
  14754. result = llm.build_rwkv6();
  14755. } break;
  14756. case LLM_ARCH_CHAMELEON:
  14757. {
  14758. result = llm.build_chameleon();
  14759. } break;
  14760. case LLM_ARCH_SOLAR:
  14761. {
  14762. result = llm.build_solar();
  14763. } break;
  14764. default:
  14765. GGML_ABORT("fatal error");
  14766. }
  14767. // add on pooling layer
  14768. if (lctx.cparams.embeddings) {
  14769. result = llm.append_pooling(result);
  14770. }
  14771. llm.free();
  14772. return result;
  14773. }
  14774. static void llama_set_k_shift(llama_context & lctx) {
  14775. const int64_t kv_size = lctx.kv_self.size;
  14776. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  14777. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  14778. for (int i = 0; i < kv_size; ++i) {
  14779. data[i] = lctx.kv_self.cells[i].delta;
  14780. }
  14781. }
  14782. static void llama_set_s_copy(llama_context & lctx) {
  14783. const int64_t kv_size = lctx.kv_self.size;
  14784. assert(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  14785. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  14786. for (int i = 0; i < kv_size; ++i) {
  14787. data[i] = lctx.kv_self.cells[i].src;
  14788. }
  14789. }
  14790. static int32_t llama_relative_position_bucket(llama_pos x, llama_pos y, uint64_t n_buckets, bool bidirectional) {
  14791. // TODO move to hparams if a T5 variant appears that uses a different value
  14792. const int64_t max_distance = 128;
  14793. if (bidirectional) {
  14794. n_buckets >>= 1;
  14795. }
  14796. const int64_t max_exact = n_buckets >> 1;
  14797. int32_t relative_position = x - y;
  14798. int32_t relative_bucket = 0;
  14799. if (bidirectional) {
  14800. relative_bucket += (relative_position > 0) * n_buckets;
  14801. relative_position = abs(relative_position);
  14802. } else {
  14803. relative_position = -std::min<int32_t>(relative_position, 0);
  14804. }
  14805. 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));
  14806. relative_position_if_large = std::min<int32_t>(relative_position_if_large, n_buckets - 1);
  14807. relative_bucket += (relative_position < max_exact ? relative_position : relative_position_if_large);
  14808. return relative_bucket;
  14809. }
  14810. static void llama_set_inputs(llama_context & lctx, const llama_ubatch & ubatch) {
  14811. //
  14812. // set input data
  14813. //
  14814. const auto & hparams = lctx.model.hparams;
  14815. const auto & cparams = lctx.cparams;
  14816. const auto & kv_self = lctx.kv_self;
  14817. if (ubatch.token) {
  14818. const int64_t n_tokens = ubatch.n_tokens;
  14819. ggml_backend_tensor_set(lctx.inp_tokens, ubatch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  14820. }
  14821. if (ubatch.embd) {
  14822. if (lctx.inp_cross_attn_state && lctx.inp_cross_attn_state->buffer) {
  14823. ggml_backend_tensor_set(lctx.inp_cross_attn_state, ubatch.embd, 0, ggml_nbytes(lctx.inp_cross_attn_state));
  14824. // zero out inp_embd since it's not used
  14825. float * inp_embd_data = (float *)lctx.inp_embd->data;
  14826. for (int i = 0; i < ggml_nelements(lctx.inp_embd); ++i) {
  14827. inp_embd_data[i] = 0.0f;
  14828. }
  14829. } else {
  14830. const int64_t n_embd = hparams.n_embd;
  14831. const int64_t n_tokens = ubatch.n_tokens;
  14832. ggml_backend_tensor_set(lctx.inp_embd, ubatch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  14833. }
  14834. }
  14835. if (ubatch.pos && lctx.inp_pos) {
  14836. const int64_t n_tokens = ubatch.n_tokens;
  14837. auto n_pos = lctx.n_pos_per_token;
  14838. ggml_backend_tensor_set(lctx.inp_pos, ubatch.pos, 0, n_tokens*n_pos*ggml_element_size(lctx.inp_pos));
  14839. }
  14840. if (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE) {
  14841. GGML_ASSERT(lctx.inp_out_ids && "every model that can must skip unused outputs");
  14842. const int64_t n_tokens = ubatch.n_tokens;
  14843. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_out_ids->buffer));
  14844. int32_t * data = (int32_t *) lctx.inp_out_ids->data;
  14845. if (lctx.n_outputs == n_tokens) {
  14846. for (int i = 0; i < n_tokens; ++i) {
  14847. data[i] = i;
  14848. }
  14849. } else if (ubatch.output) {
  14850. int32_t n_outputs = 0;
  14851. for (int i = 0; i < n_tokens; ++i) {
  14852. if (ubatch.output[i]) {
  14853. data[n_outputs++] = i;
  14854. }
  14855. }
  14856. // the graph needs to have been passed the correct number of outputs
  14857. GGML_ASSERT(lctx.n_outputs == n_outputs);
  14858. } else if (lctx.n_outputs == 1) {
  14859. // only keep last output
  14860. data[0] = n_tokens - 1;
  14861. } else {
  14862. GGML_ASSERT(lctx.n_outputs == 0);
  14863. }
  14864. }
  14865. GGML_ASSERT(
  14866. // (!a || b) is a logical implication (a -> b)
  14867. // !hparams.causal_attn -> !cparams.causal_attn
  14868. (hparams.causal_attn || !cparams.causal_attn) &&
  14869. "causal attention is not supported by this model"
  14870. );
  14871. if (lctx.inp_KQ_mask || lctx.inp_KQ_mask_swa) {
  14872. // NOTE: hparams.causal_attn indicates the model is capable of generation and uses the kv cache.
  14873. if (cparams.causal_attn && !lctx.is_encoding) {
  14874. const int64_t n_kv = kv_self.n;
  14875. const int64_t n_tokens = ubatch.n_tokens;
  14876. const int64_t n_seq_tokens = ubatch.n_seq_tokens;
  14877. const int64_t n_seqs = ubatch.n_seqs;
  14878. float * data = nullptr;
  14879. float * data_swa = nullptr;
  14880. if (lctx.inp_KQ_mask) {
  14881. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  14882. data = (float *) lctx.inp_KQ_mask->data;
  14883. }
  14884. if (lctx.inp_KQ_mask_swa) {
  14885. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask_swa->buffer));
  14886. data_swa = (float *) lctx.inp_KQ_mask_swa->data;
  14887. }
  14888. // For causal attention, use only the previous KV cells
  14889. // of the correct sequence for each token of the ubatch.
  14890. // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
  14891. for (int h = 0; h < 1; ++h) {
  14892. for (int s = 0; s < n_seqs; ++s) {
  14893. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  14894. for (int j = 0; j < n_seq_tokens; ++j) {
  14895. const llama_pos pos = ubatch.pos[s*n_seq_tokens + j];
  14896. for (int i = 0; i < n_kv; ++i) {
  14897. float f;
  14898. if (!kv_self.cells[i].has_seq_id(seq_id) || kv_self.cells[i].pos > pos) {
  14899. f = -INFINITY;
  14900. } else {
  14901. if (hparams.use_alibi) {
  14902. f = -std::abs(kv_self.cells[i].pos - pos);
  14903. } else {
  14904. f = 0.0f;
  14905. }
  14906. }
  14907. if (data) {
  14908. data[h*(n_kv*n_tokens) + s*(n_kv*n_seq_tokens) + j*n_kv + i] = f;
  14909. }
  14910. // may need to cut off old tokens for sliding window
  14911. if (data_swa) {
  14912. if (pos - kv_self.cells[i].pos >= (int32_t)hparams.n_swa) {
  14913. f = -INFINITY;
  14914. }
  14915. data_swa[h*(n_kv*n_tokens) + s*(n_kv*n_seq_tokens) + j*n_kv + i] = f;
  14916. }
  14917. }
  14918. }
  14919. }
  14920. if (data) {
  14921. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  14922. for (int j = 0; j < n_kv; ++j) {
  14923. data[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
  14924. }
  14925. }
  14926. }
  14927. if (data_swa) {
  14928. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  14929. for (int j = 0; j < n_kv; ++j) {
  14930. data_swa[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
  14931. }
  14932. }
  14933. }
  14934. }
  14935. } else {
  14936. const int64_t n_tokens = ubatch.n_tokens;
  14937. const int64_t n_seq_tokens = ubatch.n_seq_tokens;
  14938. const int64_t n_seqs = ubatch.n_seqs;
  14939. // when using kv cache, the mask needs to match the kv cache size
  14940. const int64_t n_stride = hparams.causal_attn && !lctx.is_encoding ? kv_self.n : n_tokens;
  14941. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  14942. float * data = (float *) lctx.inp_KQ_mask->data;
  14943. for (int h = 0; h < 1; ++h) {
  14944. for (int s1 = 0; s1 < n_seqs; ++s1) {
  14945. const llama_seq_id seq_id = ubatch.seq_id[s1][0];
  14946. for (int j = 0; j < n_seq_tokens; ++j) {
  14947. const int32_t tj = s1*n_seq_tokens + j;
  14948. for (int s0 = 0; s0 < n_seqs; ++s0) {
  14949. for (int i = 0; i < n_seq_tokens; ++i) {
  14950. const int32_t ti = s0*n_seq_tokens + i;
  14951. float f = -INFINITY;
  14952. for (int s = 0; s < ubatch.n_seq_id[s0]; ++s) {
  14953. if (ubatch.seq_id[s0][s] == seq_id) {
  14954. if (hparams.use_alibi) {
  14955. f = -std::abs(ubatch.pos[ti] - ubatch.pos[tj]);
  14956. } else {
  14957. f = 0.0f;
  14958. }
  14959. break;
  14960. }
  14961. }
  14962. data[h*(n_tokens*n_tokens) + tj*n_stride + ti] = f;
  14963. }
  14964. }
  14965. for (int i = n_tokens; i < n_stride; ++i) {
  14966. data[h*(n_tokens*n_tokens) + tj*n_stride + i] = -INFINITY;
  14967. }
  14968. }
  14969. }
  14970. }
  14971. }
  14972. }
  14973. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  14974. const int64_t n_tokens = ubatch.n_tokens;
  14975. const int64_t n_seq_tokens = ubatch.n_seq_tokens;
  14976. const int64_t n_seqs = ubatch.n_seqs;
  14977. GGML_ASSERT(lctx.inp_mean);
  14978. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  14979. float * data = (float *) lctx.inp_mean->data;
  14980. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  14981. std::vector<uint64_t> sum(n_tokens, 0);
  14982. for (int s = 0; s < n_seqs; ++s) {
  14983. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  14984. // TODO: adapt limits to n_seqs when ubatch.equal_seqs is true
  14985. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
  14986. sum[seq_id] += ubatch.n_seq_tokens;
  14987. }
  14988. std::vector<float> div(n_tokens, 0.0f);
  14989. for (int i = 0; i < n_tokens; ++i) {
  14990. const uint64_t s = sum[i];
  14991. if (s > 0) {
  14992. div[i] = 1.0f/float(s);
  14993. }
  14994. }
  14995. for (int s = 0; s < n_seqs; ++s) {
  14996. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  14997. for (int i = 0; i < n_seq_tokens; ++i) {
  14998. data[seq_id*n_tokens + s*n_seq_tokens + i] = div[seq_id];
  14999. }
  15000. }
  15001. }
  15002. if (cparams.embeddings && (
  15003. cparams.pooling_type == LLAMA_POOLING_TYPE_CLS ||
  15004. cparams.pooling_type == LLAMA_POOLING_TYPE_RANK)) {
  15005. const int64_t n_tokens = ubatch.n_tokens;
  15006. const int64_t n_seq_tokens = ubatch.n_seq_tokens;
  15007. const int64_t n_seqs = ubatch.n_seqs;
  15008. GGML_ASSERT(lctx.inp_cls);
  15009. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  15010. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  15011. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  15012. for (int s = 0; s < n_seqs; ++s) {
  15013. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  15014. // TODO: adapt limits to n_seqs when ubatch.equal_seqs is true
  15015. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS or RANK");
  15016. for (int i = 0; i < n_seq_tokens; ++i) {
  15017. const llama_pos pos = ubatch.pos[s*n_seq_tokens + i];
  15018. if (pos == 0) {
  15019. data[seq_id] = s*n_seq_tokens + i;
  15020. }
  15021. }
  15022. }
  15023. }
  15024. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_LAST) {
  15025. const int64_t n_tokens = ubatch.n_tokens;
  15026. const int64_t n_seq_tokens = ubatch.n_seq_tokens;
  15027. const int64_t n_seqs = ubatch.n_seqs;
  15028. GGML_ASSERT(lctx.inp_cls);
  15029. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  15030. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  15031. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  15032. std::vector<int> last_pos(n_tokens, -1);
  15033. std::vector<int> last_row(n_tokens, -1);
  15034. for (int s = 0; s < n_seqs; ++s) {
  15035. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  15036. // TODO: adapt limits to n_seqs when ubatch.equal_seqs is true
  15037. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == LAST");
  15038. for (int i = 0; i < n_seq_tokens; ++i) {
  15039. const llama_pos pos = ubatch.pos[s*n_seq_tokens + i];
  15040. if (pos >= last_pos[seq_id]) {
  15041. last_pos[seq_id] = pos;
  15042. last_row[seq_id] = s*n_seq_tokens + i;
  15043. }
  15044. }
  15045. }
  15046. for (int i = 0; i < n_tokens; ++i) {
  15047. if (last_row[i] >= 0) {
  15048. data[i] = last_row[i];
  15049. }
  15050. }
  15051. }
  15052. if (kv_self.recurrent) {
  15053. const int64_t n_kv = kv_self.n;
  15054. if (lctx.inp_s_mask) {
  15055. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_mask->buffer));
  15056. float * data = (float *) lctx.inp_s_mask->data;
  15057. // clear unused states
  15058. for (int i = 0; i < n_kv; ++i) {
  15059. const uint32_t cell_id = i + kv_self.head;
  15060. llama_kv_cell & kv_cell = lctx.kv_self.cells[cell_id];
  15061. data[i] = (float) (kv_cell.src >= 0);
  15062. // only clear once
  15063. if (kv_cell.src < 0) {
  15064. kv_cell.src = cell_id;
  15065. }
  15066. }
  15067. }
  15068. if (lctx.inp_s_copy) {
  15069. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  15070. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  15071. // assuming copy destinations ALWAYS happen ONLY on the cells between head and head+n
  15072. for (uint32_t i = 0; i < n_kv; ++i) {
  15073. const uint32_t cell_id = i + kv_self.head;
  15074. llama_kv_cell & kv_cell = lctx.kv_self.cells[cell_id];
  15075. // prevent out-of-bound sources
  15076. if (kv_cell.src < 0 || (uint32_t) kv_cell.src >= kv_self.size) {
  15077. kv_cell.src = cell_id;
  15078. }
  15079. data[i] = kv_cell.src;
  15080. // ensure copy only happens once
  15081. if (kv_cell.src != (int32_t) cell_id) {
  15082. kv_cell.src = cell_id;
  15083. }
  15084. }
  15085. }
  15086. }
  15087. if (lctx.inp_pos_bucket) {
  15088. const int64_t n_tokens = ubatch.n_tokens;
  15089. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_pos_bucket->buffer));
  15090. GGML_ASSERT(!ubatch.equal_seqs); // TODO: use ubatch.n_seqs instead of failing
  15091. int32_t * data = (int32_t *) lctx.inp_pos_bucket->data;
  15092. if (!lctx.is_encoding) {
  15093. const int64_t n_kv = kv_self.n;
  15094. for (int h = 0; h < 1; ++h) {
  15095. for (int j = 0; j < n_tokens; ++j) {
  15096. for (int i = 0; i < n_kv; ++i) {
  15097. 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);
  15098. }
  15099. }
  15100. }
  15101. } else {
  15102. for (int h = 0; h < 1; ++h) {
  15103. for (int j = 0; j < n_tokens; ++j) {
  15104. for (int i = 0; i < n_tokens; ++i) {
  15105. 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);
  15106. }
  15107. }
  15108. }
  15109. }
  15110. }
  15111. if (!lctx.is_encoding && lctx.inp_embd_enc) {
  15112. assert(lctx.inp_embd_enc->type == GGML_TYPE_F32);
  15113. assert((size_t) ggml_nelements(lctx.inp_embd_enc) == lctx.embd_enc.size());
  15114. ggml_backend_tensor_set(lctx.inp_embd_enc, lctx.embd_enc.data(), 0, ggml_nbytes(lctx.inp_embd_enc));
  15115. }
  15116. if (!lctx.is_encoding && lctx.inp_KQ_mask_cross) {
  15117. const int64_t n_output_enc = lctx.embd_enc.size() / hparams.n_embd;
  15118. const int64_t n_tokens = ubatch.n_tokens;
  15119. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask_cross->buffer));
  15120. GGML_ASSERT(!ubatch.equal_seqs); // TODO: use ubatch.n_seqs instead of failing
  15121. float * data = (float *) lctx.inp_KQ_mask_cross->data;
  15122. for (int h = 0; h < 1; ++h) {
  15123. for (int j = 0; j < n_tokens; ++j) {
  15124. for (int i = 0; i < n_output_enc; ++i) {
  15125. float f = -INFINITY;
  15126. for (int s = 0; s < ubatch.n_seq_id[j]; ++s) {
  15127. const llama_seq_id seq_id = ubatch.seq_id[j][s];
  15128. if (lctx.seq_ids_enc[i].find(seq_id) != lctx.seq_ids_enc[i].end()) {
  15129. f = 0.0f;
  15130. }
  15131. }
  15132. data[h*(n_output_enc*n_tokens) + j*n_output_enc + i] = f;
  15133. }
  15134. }
  15135. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  15136. for (int j = 0; j < n_output_enc; ++j) {
  15137. data[h*(n_output_enc*n_tokens) + i*n_output_enc + j] = -INFINITY;
  15138. }
  15139. }
  15140. }
  15141. }
  15142. }
  15143. // Make sure enough space is available for outputs.
  15144. // Returns max number of outputs for which space was reserved.
  15145. static size_t llama_output_reserve(llama_context & lctx, size_t n_outputs) {
  15146. const auto & cparams = lctx.cparams;
  15147. const auto & hparams = lctx.model.hparams;
  15148. const size_t n_outputs_max = std::max(n_outputs, (size_t) cparams.n_seq_max);
  15149. const auto n_batch = cparams.n_batch;
  15150. const auto n_vocab = hparams.n_vocab;
  15151. const auto n_embd = hparams.n_embd;
  15152. // TODO: use a per-batch flag for logits presence instead
  15153. const bool has_logits = cparams.causal_attn;
  15154. const bool has_embd = cparams.embeddings && (cparams.pooling_type == LLAMA_POOLING_TYPE_NONE);
  15155. const size_t logits_size = has_logits ? n_vocab*n_outputs_max : 0;
  15156. const size_t embd_size = has_embd ? n_embd*n_outputs_max : 0;
  15157. if (lctx.output_ids.empty()) {
  15158. // init, never resized afterwards
  15159. lctx.output_ids.resize(n_batch);
  15160. }
  15161. const size_t prev_size = lctx.buf_output ? ggml_backend_buffer_get_size(lctx.buf_output.get()) : 0;
  15162. const size_t new_size = (logits_size + embd_size) * sizeof(float);
  15163. // alloc only when more than the current capacity is required
  15164. // TODO: also consider shrinking the buffer
  15165. if (!lctx.buf_output || prev_size < new_size) {
  15166. if (lctx.buf_output) {
  15167. #ifndef NDEBUG
  15168. // This doesn't happen often, but may be annoying in some cases (like the HellaSwag benchmark)
  15169. 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);
  15170. #endif
  15171. lctx.buf_output = nullptr;
  15172. lctx.logits = nullptr;
  15173. lctx.embd = nullptr;
  15174. }
  15175. auto * buft = ggml_backend_cpu_buffer_type();
  15176. // try to use the host buffer of the device where the output tensor is allocated for faster transfer to system memory
  15177. auto * output_dev = lctx.model.dev_output.dev;
  15178. auto * output_dev_host_buft = output_dev ? ggml_backend_dev_host_buffer_type(output_dev) : nullptr;
  15179. if (output_dev_host_buft) {
  15180. buft = output_dev_host_buft;
  15181. }
  15182. lctx.buf_output.reset(ggml_backend_buft_alloc_buffer(buft, new_size));
  15183. if (lctx.buf_output == nullptr) {
  15184. LLAMA_LOG_ERROR("%s: failed to allocate output buffer of size %.2f MiB\n", __func__, new_size / (1024.0 * 1024.0));
  15185. return 0;
  15186. }
  15187. }
  15188. float * output_base = (float *) ggml_backend_buffer_get_base(lctx.buf_output.get());
  15189. lctx.logits = has_logits ? output_base : nullptr;
  15190. lctx.embd = has_embd ? output_base + logits_size : nullptr;
  15191. lctx.output_size = n_outputs_max;
  15192. lctx.logits_size = logits_size;
  15193. lctx.embd_size = embd_size;
  15194. // set all ids as invalid (negative)
  15195. std::fill(lctx.output_ids.begin(), lctx.output_ids.end(), -1);
  15196. ggml_backend_buffer_clear(lctx.buf_output.get(), 0);
  15197. lctx.n_outputs = 0;
  15198. return n_outputs_max;
  15199. }
  15200. // make the outputs have the same order they had in the user-provided batch
  15201. static void llama_output_reorder(struct llama_context * ctx) {
  15202. std::vector<size_t> & out_ids = ctx->sbatch.out_ids;
  15203. if (!out_ids.empty()) {
  15204. uint32_t n_vocab = ctx->model.hparams.n_vocab;
  15205. uint32_t n_embd = ctx->model.hparams.n_embd;
  15206. int32_t n_outputs = ctx->n_outputs;
  15207. GGML_ASSERT((size_t) n_outputs == out_ids.size());
  15208. // TODO: is there something more efficient which also minimizes swaps?
  15209. // selection sort, to minimize swaps (from https://en.wikipedia.org/wiki/Selection_sort)
  15210. for (int32_t i = 0; i < n_outputs - 1; ++i) {
  15211. int32_t j_min = i;
  15212. for (int32_t j = i + 1; j < n_outputs; ++j) {
  15213. if (out_ids[j] < out_ids[j_min]) {
  15214. j_min = j;
  15215. }
  15216. }
  15217. if (j_min == i) { continue; }
  15218. std::swap(out_ids[i], out_ids[j_min]);
  15219. if (ctx->logits_size > 0) {
  15220. for (uint32_t k = 0; k < n_vocab; k++) {
  15221. std::swap(ctx->logits[i*n_vocab + k], ctx->logits[j_min*n_vocab + k]);
  15222. }
  15223. }
  15224. if (ctx->embd_size > 0) {
  15225. for (uint32_t k = 0; k < n_embd; k++) {
  15226. std::swap(ctx->embd[i*n_embd + k], ctx->embd[j_min*n_embd + k]);
  15227. }
  15228. }
  15229. }
  15230. std::fill(ctx->output_ids.begin(), ctx->output_ids.end(), -1);
  15231. for (int32_t i = 0; i < n_outputs; ++i) {
  15232. ctx->output_ids[out_ids[i]] = i;
  15233. }
  15234. out_ids.clear();
  15235. }
  15236. }
  15237. // returns the result of ggml_backend_sched_graph_compute_async execution
  15238. static enum ggml_status llama_graph_compute(
  15239. llama_context & lctx,
  15240. ggml_cgraph * gf,
  15241. int n_threads,
  15242. ggml_threadpool * threadpool) {
  15243. if (lctx.backend_cpu != nullptr) {
  15244. auto * reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(lctx.backend_cpu));
  15245. auto * set_threadpool_fn = (decltype(ggml_backend_cpu_set_threadpool) *) ggml_backend_reg_get_proc_address(reg, "ggml_backend_cpu_set_threadpool");
  15246. set_threadpool_fn(lctx.backend_cpu, threadpool);
  15247. }
  15248. // set the number of threads for all the backends
  15249. for (const auto & set_n_threads_fn : lctx.set_n_threads_fns) {
  15250. set_n_threads_fn.second(set_n_threads_fn.first, n_threads);
  15251. }
  15252. auto status = ggml_backend_sched_graph_compute_async(lctx.sched.get(), gf);
  15253. if (status != GGML_STATUS_SUCCESS) {
  15254. LLAMA_LOG_ERROR("%s: ggml_backend_sched_graph_compute_async failed with error %d\n", __func__, status);
  15255. }
  15256. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  15257. return status;
  15258. }
  15259. // decode a batch of tokens by evaluating the transformer
  15260. // in case of unsuccessful decoding (error or warning),
  15261. // the kv_cache state will be returned to its original state
  15262. // (for non-recurrent models) or cleaned (for recurrent models)
  15263. //
  15264. // - lctx: llama context
  15265. // - batch: batch to evaluate
  15266. //
  15267. // return 0 on success
  15268. // return positive int on warning
  15269. // return negative int on error
  15270. //
  15271. static int llama_decode_internal(
  15272. llama_context & lctx,
  15273. llama_batch inp_batch) {
  15274. lctx.is_encoding = false;
  15275. if (inp_batch.n_tokens == 0) {
  15276. LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__);
  15277. return -1;
  15278. }
  15279. // temporary allocate memory for the input batch if needed
  15280. llama_batch_allocr batch_allocr(lctx, inp_batch);
  15281. const llama_batch & batch = batch_allocr.batch;
  15282. const uint32_t n_tokens_all = batch.n_tokens;
  15283. const auto & model = lctx.model;
  15284. const auto & hparams = model.hparams;
  15285. const auto & cparams = lctx.cparams;
  15286. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  15287. if (batch.token) {
  15288. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  15289. if (batch.token[i] < 0 || (uint32_t)batch.token[i] >= model.vocab.n_vocab) {
  15290. LLAMA_LOG_ERROR("%s: invalid token[%d] = %d\n", __func__, i, batch.token[i]);
  15291. return -1;
  15292. }
  15293. }
  15294. }
  15295. GGML_ASSERT(n_tokens_all <= cparams.n_batch);
  15296. GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
  15297. if (lctx.t_compute_start_us == 0) {
  15298. lctx.t_compute_start_us = ggml_time_us();
  15299. }
  15300. lctx.n_queued_tokens += n_tokens_all;
  15301. auto & kv_self = lctx.kv_self;
  15302. llama_kv_slot_restorer kv_slot_restorer(kv_self);
  15303. const int64_t n_embd = hparams.n_embd;
  15304. const int64_t n_vocab = hparams.n_vocab;
  15305. uint32_t n_outputs = 0;
  15306. uint32_t n_outputs_prev = 0;
  15307. const auto n_ubatch = cparams.n_ubatch;
  15308. // this indicates we are doing pooled embedding, so we ignore batch.logits and output all tokens
  15309. const bool embd_pooled = cparams.embeddings && cparams.pooling_type != LLAMA_POOLING_TYPE_NONE;
  15310. lctx.embd_seq.clear();
  15311. // count outputs
  15312. if (batch.logits && !embd_pooled) {
  15313. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  15314. n_outputs += batch.logits[i] != 0;
  15315. }
  15316. } else if (lctx.logits_all || embd_pooled) {
  15317. n_outputs = n_tokens_all;
  15318. } else {
  15319. // keep last output only
  15320. n_outputs = 1;
  15321. }
  15322. lctx.sbatch.from_batch(batch, batch.n_embd,
  15323. /* simple_split */ !kv_self.recurrent,
  15324. /* logits_all */ n_outputs == n_tokens_all);
  15325. // reserve output buffer
  15326. if (llama_output_reserve(lctx, n_outputs) < n_outputs) {
  15327. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_outputs);
  15328. return -2;
  15329. };
  15330. while (lctx.sbatch.n_tokens > 0) {
  15331. llama_ubatch ubatch;
  15332. if (kv_self.recurrent) {
  15333. if (embd_pooled) {
  15334. // Pooled embeddings cannot be split across ubatches (yet)
  15335. ubatch = lctx.sbatch.split_seq(n_ubatch);
  15336. } else {
  15337. // recurrent model architectures are easier to implement
  15338. // with equal-length sequences
  15339. ubatch = lctx.sbatch.split_equal(n_ubatch);
  15340. }
  15341. } else {
  15342. ubatch = lctx.sbatch.split_simple(n_ubatch);
  15343. }
  15344. const uint32_t n_tokens = ubatch.n_tokens;
  15345. // count the outputs in this u_batch
  15346. {
  15347. int32_t n_outputs_new = 0;
  15348. if (n_outputs == n_tokens_all) {
  15349. n_outputs_new = n_tokens;
  15350. } else {
  15351. GGML_ASSERT(ubatch.output);
  15352. for (uint32_t i = 0; i < n_tokens; i++) {
  15353. n_outputs_new += (int32_t) (ubatch.output[i] != 0);
  15354. }
  15355. }
  15356. // needs to happen before the graph is built
  15357. lctx.n_outputs = n_outputs_new;
  15358. }
  15359. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  15360. ggml_threadpool_t threadpool = n_tokens == 1 ? lctx.threadpool : lctx.threadpool_batch;
  15361. GGML_ASSERT(n_threads > 0);
  15362. // non-causal masks do not use the KV cache
  15363. if (hparams.causal_attn) {
  15364. llama_kv_cache_update(&lctx);
  15365. // if we have enough unused cells before the current head ->
  15366. // better to start searching from the beginning of the cache, hoping to fill it
  15367. if (kv_self.head > kv_self.used + 2*n_tokens) {
  15368. kv_self.head = 0;
  15369. }
  15370. auto slot = llama_kv_cache_find_slot(kv_self, ubatch);
  15371. if (!slot) {
  15372. llama_kv_cache_defrag(kv_self);
  15373. llama_kv_cache_update(&lctx);
  15374. slot = llama_kv_cache_find_slot(kv_self, ubatch);
  15375. }
  15376. if (!slot) {
  15377. return 1;
  15378. }
  15379. kv_slot_restorer.save(slot);
  15380. if (!kv_self.recurrent) {
  15381. // a heuristic, to avoid attending the full cache if it is not yet utilized
  15382. // after enough generations, the benefit from this heuristic disappears
  15383. // if we start defragmenting the cache, the benefit from this will be more important
  15384. const uint32_t pad = llama_kv_cache_get_padding(cparams);
  15385. kv_self.n = std::min(kv_self.size, std::max(pad, GGML_PAD(llama_kv_cache_cell_max(kv_self), pad)));
  15386. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  15387. }
  15388. }
  15389. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  15390. ggml_backend_sched_reset(lctx.sched.get());
  15391. ggml_backend_sched_set_eval_callback(lctx.sched.get(), lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  15392. ggml_cgraph * gf = llama_build_graph(lctx, ubatch, false);
  15393. // the output is always the last tensor in the graph
  15394. struct ggml_tensor * res = ggml_graph_node(gf, -1);
  15395. struct ggml_tensor * embd = ggml_graph_node(gf, -2);
  15396. if (lctx.n_outputs == 0) {
  15397. // no output
  15398. res = nullptr;
  15399. embd = nullptr;
  15400. } else if (cparams.embeddings) {
  15401. embd = nullptr;
  15402. for (int i = ggml_graph_n_nodes(gf) - 1; i >= 0; --i) {
  15403. if (strcmp(ggml_graph_node(gf, i)->name, "result_embd_pooled") == 0) {
  15404. embd = ggml_graph_node(gf, i);
  15405. break;
  15406. }
  15407. }
  15408. } else {
  15409. embd = nullptr; // do not extract embeddings when not needed
  15410. GGML_ASSERT(strcmp(res->name, "result_output") == 0 && "missing result_output tensor");
  15411. }
  15412. if (!cparams.causal_attn) {
  15413. res = nullptr; // do not extract logits when not needed
  15414. }
  15415. // 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);
  15416. ggml_backend_sched_alloc_graph(lctx.sched.get(), gf);
  15417. llama_set_inputs(lctx, ubatch);
  15418. const auto compute_status = llama_graph_compute(lctx, gf, n_threads, threadpool);
  15419. if (compute_status != GGML_STATUS_SUCCESS) {
  15420. kv_slot_restorer.restore(kv_self);
  15421. switch (compute_status) {
  15422. case GGML_STATUS_ABORTED:
  15423. return 2;
  15424. case GGML_STATUS_ALLOC_FAILED:
  15425. return -2;
  15426. case GGML_STATUS_FAILED:
  15427. default:
  15428. return -3;
  15429. }
  15430. }
  15431. // update the kv ring buffer
  15432. {
  15433. kv_self.head += n_tokens;
  15434. // Ensure kv cache head points to a valid index.
  15435. if (kv_self.head >= kv_self.size) {
  15436. kv_self.head = 0;
  15437. }
  15438. }
  15439. // plot the computation graph in dot format (for debugging purposes)
  15440. //if (n_past%100 == 0) {
  15441. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  15442. //}
  15443. // extract logits
  15444. if (res) {
  15445. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(lctx.sched.get(), res);
  15446. GGML_ASSERT(backend_res != nullptr);
  15447. GGML_ASSERT(lctx.logits != nullptr);
  15448. float * logits_out = lctx.logits + n_outputs_prev*n_vocab;
  15449. const int32_t n_outputs_new = lctx.n_outputs;
  15450. if (n_outputs_new) {
  15451. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  15452. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_vocab <= (int64_t) lctx.logits_size);
  15453. ggml_backend_tensor_get_async(backend_res, res, logits_out, 0, n_outputs_new*n_vocab*sizeof(float));
  15454. }
  15455. }
  15456. // extract embeddings
  15457. if (embd) {
  15458. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched.get(), embd);
  15459. GGML_ASSERT(backend_embd != nullptr);
  15460. switch (cparams.pooling_type) {
  15461. case LLAMA_POOLING_TYPE_NONE:
  15462. {
  15463. // extract token embeddings
  15464. GGML_ASSERT(lctx.embd != nullptr);
  15465. float * embd_out = lctx.embd + n_outputs_prev*n_embd;
  15466. const int32_t n_outputs_new = lctx.n_outputs;
  15467. if (n_outputs_new) {
  15468. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  15469. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_embd <= (int64_t) lctx.embd_size);
  15470. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_outputs_new*n_embd*sizeof(float));
  15471. }
  15472. } break;
  15473. case LLAMA_POOLING_TYPE_MEAN:
  15474. case LLAMA_POOLING_TYPE_CLS:
  15475. case LLAMA_POOLING_TYPE_LAST:
  15476. {
  15477. // extract sequence embeddings (cleared before processing each batch)
  15478. auto & embd_seq_out = lctx.embd_seq;
  15479. for (uint32_t s = 0; s < ubatch.n_seqs; ++s) {
  15480. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  15481. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  15482. continue;
  15483. }
  15484. embd_seq_out[seq_id].resize(n_embd);
  15485. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  15486. }
  15487. } break;
  15488. case LLAMA_POOLING_TYPE_RANK:
  15489. {
  15490. // extract the rerank score - a single float per sequence
  15491. auto & embd_seq_out = lctx.embd_seq;
  15492. for (uint32_t s = 0; s < ubatch.n_seqs; ++s) {
  15493. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  15494. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  15495. continue;
  15496. }
  15497. embd_seq_out[seq_id].resize(1);
  15498. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (seq_id)*sizeof(float), sizeof(float));
  15499. }
  15500. } break;
  15501. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  15502. {
  15503. GGML_ABORT("unknown pooling type");
  15504. }
  15505. }
  15506. }
  15507. n_outputs_prev += lctx.n_outputs;
  15508. }
  15509. // set output mappings
  15510. {
  15511. bool sorted_output = true;
  15512. GGML_ASSERT(lctx.sbatch.out_ids.size() == n_outputs);
  15513. for (size_t i = 0; i < n_outputs; ++i) {
  15514. size_t out_id = lctx.sbatch.out_ids[i];
  15515. lctx.output_ids[out_id] = i;
  15516. if (out_id != i) {
  15517. sorted_output = false;
  15518. }
  15519. }
  15520. if (sorted_output) {
  15521. lctx.sbatch.out_ids.clear();
  15522. }
  15523. }
  15524. // set to total number of outputs in the batch, for use in llama_get_logits_ith
  15525. lctx.n_outputs = n_outputs;
  15526. // wait for the computation to finish (automatically done when obtaining the model output)
  15527. //llama_synchronize(&lctx);
  15528. // decide if we need to defrag the kv cache
  15529. if (cparams.causal_attn && cparams.defrag_thold >= 0.0f) {
  15530. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used)/float(kv_self.n) : 0.0f;
  15531. // queue defragmentation for next llama_kv_cache_update
  15532. if (fragmentation > cparams.defrag_thold) {
  15533. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  15534. llama_kv_cache_defrag(kv_self);
  15535. }
  15536. }
  15537. // Reset state for the next token before backend sync, to allow the CPU activities in the reset to
  15538. // overlap with device computation.
  15539. ggml_backend_sched_reset(lctx.sched.get());
  15540. return 0;
  15541. }
  15542. // encode a batch of tokens by evaluating the encoder part of the transformer
  15543. //
  15544. // - lctx: llama context
  15545. // - batch: batch to evaluate
  15546. //
  15547. // return 0 on success
  15548. // return positive int on warning
  15549. // return negative int on error
  15550. //
  15551. static int llama_encode_internal(
  15552. llama_context & lctx,
  15553. llama_batch inp_batch) {
  15554. lctx.is_encoding = true;
  15555. if (inp_batch.n_tokens == 0) {
  15556. LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__);
  15557. return -1;
  15558. }
  15559. // temporary allocate memory for the input batch if needed
  15560. llama_batch_allocr batch_allocr(lctx, inp_batch);
  15561. const llama_batch & batch = batch_allocr.batch;
  15562. const uint32_t n_tokens = batch.n_tokens;
  15563. const auto & model = lctx.model;
  15564. const auto & hparams = model.hparams;
  15565. const auto & cparams = lctx.cparams;
  15566. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  15567. if (batch.token) {
  15568. for (uint32_t i = 0; i < n_tokens; ++i) {
  15569. if (batch.token[i] < 0 || (uint32_t)batch.token[i] >= model.vocab.n_vocab) {
  15570. LLAMA_LOG_ERROR("%s: invalid token[%d] = %d\n", __func__, i, batch.token[i]);
  15571. return -1;
  15572. }
  15573. }
  15574. }
  15575. // micro-batching is not possible for non-causal encoding, so we process the batch in a single shot
  15576. GGML_ASSERT(cparams.n_ubatch >= n_tokens && "encoder requires n_ubatch >= n_tokens");
  15577. if (lctx.t_compute_start_us == 0) {
  15578. lctx.t_compute_start_us = ggml_time_us();
  15579. }
  15580. lctx.n_queued_tokens += n_tokens;
  15581. const int64_t n_embd = hparams.n_embd;
  15582. lctx.sbatch.from_batch(batch, batch.n_embd, /* simple_split */ true, /* logits_all */ true);
  15583. const llama_ubatch ubatch = lctx.sbatch.split_simple(n_tokens);
  15584. // reserve output buffer
  15585. if (llama_output_reserve(lctx, n_tokens) < n_tokens) {
  15586. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_tokens);
  15587. return -2;
  15588. };
  15589. for (uint32_t i = 0; i < n_tokens; ++i) {
  15590. lctx.output_ids[i] = i;
  15591. }
  15592. lctx.inp_embd_enc = NULL;
  15593. lctx.n_outputs = n_tokens;
  15594. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  15595. ggml_threadpool_t threadpool = n_tokens == 1 ? lctx.threadpool : lctx.threadpool_batch;
  15596. GGML_ASSERT(n_threads > 0);
  15597. ggml_backend_sched_reset(lctx.sched.get());
  15598. ggml_backend_sched_set_eval_callback(lctx.sched.get(), lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  15599. ggml_cgraph * gf = llama_build_graph(lctx, ubatch, false);
  15600. // the output embeddings after the final encoder normalization
  15601. struct ggml_tensor * embd = nullptr;
  15602. // there are two cases here
  15603. if (llama_model_has_decoder(&lctx.model)) {
  15604. // first case is an encoder-decoder T5 model where embeddings are passed to decoder
  15605. embd = ggml_graph_node(gf, -1);
  15606. GGML_ASSERT(strcmp(embd->name, "result_norm") == 0 && "missing result_output tensor");
  15607. } else {
  15608. // second case is an encoder-only T5 model
  15609. if (cparams.embeddings) {
  15610. // only output embeddings if required
  15611. embd = ggml_graph_node(gf, -1);
  15612. if (strcmp(embd->name, "result_embd_pooled") != 0) {
  15613. embd = ggml_graph_node(gf, -2);
  15614. }
  15615. GGML_ASSERT(strcmp(embd->name, "result_embd_pooled") == 0 && "missing embeddings tensor");
  15616. }
  15617. }
  15618. ggml_backend_sched_alloc_graph(lctx.sched.get(), gf);
  15619. llama_set_inputs(lctx, ubatch);
  15620. const auto compute_status = llama_graph_compute(lctx, gf, n_threads, threadpool);
  15621. switch (compute_status) {
  15622. case GGML_STATUS_SUCCESS:
  15623. break;
  15624. case GGML_STATUS_ABORTED:
  15625. return 2;
  15626. case GGML_STATUS_ALLOC_FAILED:
  15627. return -2;
  15628. case GGML_STATUS_FAILED:
  15629. default:
  15630. return -3;
  15631. }
  15632. // extract embeddings
  15633. if (embd) {
  15634. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched.get(), embd);
  15635. GGML_ASSERT(backend_embd != nullptr);
  15636. if (llama_model_has_decoder(&lctx.model)) {
  15637. lctx.embd_enc.resize(n_tokens*n_embd);
  15638. float * embd_out = lctx.embd_enc.data();
  15639. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_tokens*n_embd*sizeof(float));
  15640. GGML_ASSERT(!ubatch.equal_seqs); // TODO: handle equal splits
  15641. // remember the sequence ids used during the encoding - needed for cross attention later
  15642. lctx.seq_ids_enc.resize(n_tokens);
  15643. for (uint32_t i = 0; i < n_tokens; i++) {
  15644. for (int s = 0; s < ubatch.n_seq_id[i]; s++) {
  15645. llama_seq_id seq_id = ubatch.seq_id[i][s];
  15646. lctx.seq_ids_enc[i].insert(seq_id);
  15647. }
  15648. }
  15649. } else {
  15650. GGML_ASSERT(lctx.embd != nullptr);
  15651. switch (cparams.pooling_type) {
  15652. case LLAMA_POOLING_TYPE_NONE:
  15653. {
  15654. // extract token embeddings
  15655. GGML_ASSERT(lctx.embd != nullptr);
  15656. float * embd_out = lctx.embd;
  15657. GGML_ASSERT(n_tokens*n_embd <= (int64_t) lctx.embd_size);
  15658. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_tokens*n_embd*sizeof(float));
  15659. } break;
  15660. case LLAMA_POOLING_TYPE_MEAN:
  15661. case LLAMA_POOLING_TYPE_CLS:
  15662. case LLAMA_POOLING_TYPE_LAST:
  15663. {
  15664. // extract sequence embeddings
  15665. auto & embd_seq_out = lctx.embd_seq;
  15666. embd_seq_out.clear();
  15667. GGML_ASSERT(!ubatch.equal_seqs); // TODO: handle equal splits
  15668. for (uint32_t i = 0; i < n_tokens; i++) {
  15669. const llama_seq_id seq_id = ubatch.seq_id[i][0];
  15670. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  15671. continue;
  15672. }
  15673. embd_seq_out[seq_id].resize(n_embd);
  15674. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  15675. }
  15676. } break;
  15677. case LLAMA_POOLING_TYPE_RANK:
  15678. {
  15679. // TODO: this likely should be the same logic as in llama_decoder_internal, but better to
  15680. // wait for an encoder model that requires this pooling type in order to test it
  15681. // https://github.com/ggerganov/llama.cpp/pull/9510
  15682. GGML_ABORT("RANK pooling not implemented yet");
  15683. }
  15684. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  15685. {
  15686. GGML_ABORT("unknown pooling type");
  15687. }
  15688. }
  15689. }
  15690. }
  15691. // Reset state for the next token before backend sync, to allow the CPU activities in the reset to
  15692. // overlap with device computation.
  15693. ggml_backend_sched_reset(lctx.sched.get());
  15694. return 0;
  15695. }
  15696. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  15697. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  15698. auto & kv_self = lctx.kv_self;
  15699. const auto & hparams = lctx.model.hparams;
  15700. const uint32_t n_layer = hparams.n_layer;
  15701. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  15702. const uint32_t n_used = kv_self.used;
  15703. assert(n_used <= n_kv);
  15704. //const int64_t t_start = ggml_time_us();
  15705. // groups of cells moved
  15706. std::vector<struct llama_kv_defrag_move> moves;
  15707. // each move requires 6*n_layer tensors (see build_defrag)
  15708. // - source view, destination view, copy operation
  15709. // - x2 for keys and values
  15710. //const uint32_t max_moves = llama_model_max_nodes(model)/(6*n_layer);
  15711. // TODO: tmp fix https://github.com/ggerganov/llama.cpp/issues/6685#issuecomment-2057579516
  15712. const uint32_t max_moves = (llama_model_max_nodes(lctx.model) - 2*n_layer)/(6*n_layer);
  15713. // determine which KV cells to move where
  15714. //
  15715. // cell i moves to ids[i]
  15716. //
  15717. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  15718. //
  15719. std::vector<uint32_t> ids(n_kv, n_kv);
  15720. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  15721. const auto & cell0 = kv_self.cells[i0];
  15722. if (!cell0.is_empty()) {
  15723. ids[i0] = i0;
  15724. continue;
  15725. }
  15726. // found a hole - fill it with data from the end of the cache
  15727. uint32_t nh = 1;
  15728. // determine the size of the hole
  15729. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  15730. nh++;
  15731. }
  15732. uint32_t nf = 0;
  15733. uint32_t is = n_kv - 1;
  15734. // starting from the end, find nh non-empty cells
  15735. for (; is > i0; --is) {
  15736. const auto & cell1 = kv_self.cells[is];
  15737. if (cell1.is_empty() || ids[is] != n_kv) {
  15738. continue;
  15739. }
  15740. // non-empty cell which is not yet moved
  15741. nf++;
  15742. if (nf == nh) {
  15743. break;
  15744. }
  15745. }
  15746. // this can only happen if `n_used` is not accurate, which would be a bug
  15747. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  15748. nf = 0;
  15749. uint32_t i1 = is;
  15750. // are we moving a continuous block of memory?
  15751. bool cont = false;
  15752. // go back and move the nf cells to the hole
  15753. for (; i1 < n_kv; ++i1) {
  15754. auto & cell1 = kv_self.cells[i1];
  15755. if (cell1.is_empty() || ids[i1] != n_kv) {
  15756. cont = false;
  15757. continue;
  15758. }
  15759. // this cell goes to (i0 + nf)
  15760. ids[i1] = i0 + nf;
  15761. // move the cell meta data
  15762. kv_self.cells[i0 + nf] = cell1;
  15763. // clear the old cell and move the head there
  15764. cell1 = llama_kv_cell();
  15765. kv_self.head = n_used;
  15766. if (!cont) {
  15767. moves.push_back({i1, i0 + nf, 1});
  15768. cont = true;
  15769. } else {
  15770. moves.back().len++;
  15771. }
  15772. nf++;
  15773. if (nf == nh) {
  15774. break;
  15775. }
  15776. }
  15777. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  15778. i0 += nh - 1;
  15779. }
  15780. if (moves.size() == 0) {
  15781. return;
  15782. }
  15783. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", moves.size());
  15784. #if 0
  15785. // CPU defrag
  15786. //
  15787. // TODO: optimizations are possible:
  15788. // - multiple threads
  15789. // - avoid copying to the host memory when already there
  15790. //
  15791. // likely not worth the effort, as we have ggml_graph based defrag
  15792. //
  15793. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  15794. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  15795. const uint32_t kv_size = kv_self.size;
  15796. std::vector<uint8_t> buf_k;
  15797. std::vector<uint8_t> buf_v;
  15798. for (uint32_t il = 0; il < n_layer; ++il) {
  15799. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  15800. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  15801. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  15802. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  15803. buf_k.resize(k_size);
  15804. buf_v.resize(v_size);
  15805. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  15806. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  15807. // batch move [i, i+nm) to [id, id+nm)
  15808. // note: cells can move only to a lower index
  15809. for (uint32_t i = 0; i < n_kv; ++i) {
  15810. const uint32_t id = ids[i];
  15811. if (i == id || id == n_kv) {
  15812. continue;
  15813. }
  15814. uint32_t nm = 1;
  15815. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  15816. nm++;
  15817. }
  15818. // move keys
  15819. {
  15820. const int64_t os = i*k_size_row;
  15821. const int64_t od = id*k_size_row;
  15822. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  15823. }
  15824. // move values (note: they are transposed)
  15825. {
  15826. const int64_t os = i;
  15827. const int64_t od = id;
  15828. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  15829. 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);
  15830. }
  15831. }
  15832. i += nm - 1;
  15833. }
  15834. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  15835. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  15836. }
  15837. #else
  15838. // ggml_graph defrag
  15839. for (std::size_t i = 0; i < moves.size(); i += max_moves) {
  15840. std::vector<struct llama_kv_defrag_move> chunk;
  15841. auto end = std::min(i + max_moves, moves.size());
  15842. chunk.assign(moves.begin() + i, moves.begin() + end);
  15843. ggml_backend_sched_reset(lctx.sched.get());
  15844. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*chunk.size()*n_layer);
  15845. ggml_cgraph * gf = llama_build_graph_defrag(lctx, chunk);
  15846. llama_graph_compute(lctx, gf, lctx.cparams.n_threads, lctx.threadpool);
  15847. }
  15848. #endif
  15849. //const int64_t t_end = ggml_time_us();
  15850. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  15851. }
  15852. static void llama_kv_cache_update_internal(struct llama_context & lctx) {
  15853. bool need_reserve = false;
  15854. if (lctx.kv_self.has_shift) {
  15855. if (!llama_kv_cache_can_shift(&lctx)) {
  15856. GGML_ABORT("The current context does not support K-shift");
  15857. }
  15858. // apply K-shift if needed
  15859. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE) {
  15860. ggml_backend_sched_reset(lctx.sched.get());
  15861. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  15862. ggml_backend_sched_alloc_graph(lctx.sched.get(), gf);
  15863. llama_set_k_shift(lctx);
  15864. llama_graph_compute(lctx, gf, lctx.cparams.n_threads, lctx.threadpool);
  15865. need_reserve = true;
  15866. }
  15867. {
  15868. auto & kv_self = lctx.kv_self;
  15869. kv_self.has_shift = false;
  15870. for (uint32_t i = 0; i < kv_self.size; ++i) {
  15871. kv_self.cells[i].delta = 0;
  15872. }
  15873. }
  15874. }
  15875. // defragment the KV cache if needed
  15876. if (lctx.kv_self.do_defrag) {
  15877. llama_kv_cache_defrag_internal(lctx);
  15878. need_reserve = true;
  15879. lctx.kv_self.do_defrag = false;
  15880. }
  15881. // reserve a worst case graph again
  15882. if (need_reserve) {
  15883. // TODO: extract to a function
  15884. // build worst-case graph
  15885. uint32_t n_seqs = 1; // TODO: worst-case number of sequences
  15886. uint32_t n_tokens = std::min(lctx.cparams.n_ctx, lctx.cparams.n_ubatch);
  15887. 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
  15888. llama_ubatch ubatch = { true, n_tokens, n_tokens / n_seqs, n_seqs, &token, nullptr, nullptr, nullptr, nullptr, nullptr};
  15889. ggml_cgraph * gf = llama_build_graph(lctx, ubatch, true);
  15890. // initialize scheduler with the worst-case graph
  15891. ggml_backend_sched_reset(lctx.sched.get());
  15892. if (!ggml_backend_sched_reserve(lctx.sched.get(), gf)) {
  15893. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  15894. }
  15895. }
  15896. }
  15897. //
  15898. // quantization
  15899. //
  15900. struct quantize_state_internal {
  15901. const llama_model & model;
  15902. const llama_model_quantize_params * params;
  15903. int n_attention_wv = 0;
  15904. int n_ffn_down = 0;
  15905. int n_ffn_gate = 0;
  15906. int n_ffn_up = 0;
  15907. int i_attention_wv = 0;
  15908. int i_ffn_down = 0;
  15909. int i_ffn_gate = 0;
  15910. int i_ffn_up = 0;
  15911. int n_k_quantized = 0;
  15912. int n_fallback = 0;
  15913. bool has_imatrix = false;
  15914. // used to figure out if a model shares tok_embd with the output weight
  15915. bool has_output = false;
  15916. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  15917. : model(model)
  15918. , params(params)
  15919. {}
  15920. };
  15921. static void llama_tensor_dequantize_internal(
  15922. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  15923. const size_t nelements, const int nthread
  15924. ) {
  15925. if (output.size() < nelements) {
  15926. output.resize(nelements);
  15927. }
  15928. float * f32_output = (float *) output.data();
  15929. const ggml_type_traits * qtype = ggml_get_type_traits(tensor->type);
  15930. if (ggml_is_quantized(tensor->type)) {
  15931. if (qtype->to_float == NULL) {
  15932. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  15933. }
  15934. } else if (tensor->type != GGML_TYPE_F16 &&
  15935. tensor->type != GGML_TYPE_BF16) {
  15936. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  15937. }
  15938. if (nthread < 2) {
  15939. if (tensor->type == GGML_TYPE_F16) {
  15940. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  15941. } else if (tensor->type == GGML_TYPE_BF16) {
  15942. ggml_bf16_to_fp32_row((ggml_bf16_t *)tensor->data, f32_output, nelements);
  15943. } else if (ggml_is_quantized(tensor->type)) {
  15944. qtype->to_float(tensor->data, f32_output, nelements);
  15945. } else {
  15946. GGML_ABORT("fatal error"); // unreachable
  15947. }
  15948. return;
  15949. }
  15950. size_t block_size;
  15951. if (tensor->type == GGML_TYPE_F16 ||
  15952. tensor->type == GGML_TYPE_BF16) {
  15953. block_size = 1;
  15954. } else {
  15955. block_size = (size_t)ggml_blck_size(tensor->type);
  15956. }
  15957. size_t block_size_bytes = ggml_type_size(tensor->type);
  15958. GGML_ASSERT(nelements % block_size == 0);
  15959. size_t nblocks = nelements / block_size;
  15960. size_t blocks_per_thread = nblocks / nthread;
  15961. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  15962. size_t in_buff_offs = 0;
  15963. size_t out_buff_offs = 0;
  15964. for (int tnum = 0; tnum < nthread; tnum++) {
  15965. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  15966. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  15967. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  15968. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  15969. if (typ == GGML_TYPE_F16) {
  15970. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  15971. } else if (typ == GGML_TYPE_BF16) {
  15972. ggml_bf16_to_fp32_row((ggml_bf16_t *)inbuf, outbuf, nels);
  15973. } else {
  15974. qtype->to_float(inbuf, outbuf, nels);
  15975. }
  15976. };
  15977. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  15978. in_buff_offs += thr_block_bytes;
  15979. out_buff_offs += thr_elems;
  15980. }
  15981. for (auto & w : workers) { w.join(); }
  15982. workers.clear();
  15983. }
  15984. static ggml_type llama_tensor_get_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  15985. const std::string name = ggml_get_name(tensor);
  15986. // TODO: avoid hardcoded tensor names - use the TN_* constants
  15987. const llm_arch arch = qs.model.arch;
  15988. const auto tn = LLM_TN(arch);
  15989. auto use_more_bits = [](int i_layer, int n_layers) -> bool {
  15990. return i_layer < n_layers/8 || i_layer >= 7*n_layers/8 || (i_layer - n_layers/8)%3 == 2;
  15991. };
  15992. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  15993. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  15994. if (n_expert > 1) {
  15995. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but occasionally randomly
  15996. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  15997. // for getting the current layer as I initially thought, and we need to resort to parsing the
  15998. // tensor name.
  15999. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  16000. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  16001. }
  16002. if (i_layer < 0 || i_layer >= n_layer) {
  16003. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  16004. }
  16005. }
  16006. return std::make_pair(i_layer, n_layer);
  16007. };
  16008. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  16009. // with the quantization of the output tensor
  16010. if (name == tn(LLM_TENSOR_OUTPUT, "weight") || (!qs.has_output && name == tn(LLM_TENSOR_TOKEN_EMBD, "weight"))) {
  16011. if (qs.params->output_tensor_type < GGML_TYPE_COUNT) {
  16012. new_type = qs.params->output_tensor_type;
  16013. } else {
  16014. int nx = tensor->ne[0];
  16015. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  16016. new_type = GGML_TYPE_Q8_0;
  16017. }
  16018. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  16019. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ||
  16020. ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  16021. new_type = GGML_TYPE_Q5_K;
  16022. }
  16023. else if (new_type != GGML_TYPE_Q8_0) {
  16024. new_type = GGML_TYPE_Q6_K;
  16025. }
  16026. }
  16027. } else if (name == "token_embd.weight") {
  16028. if (qs.params->token_embedding_type < GGML_TYPE_COUNT) {
  16029. new_type = qs.params->token_embedding_type;
  16030. } else {
  16031. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
  16032. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  16033. new_type = GGML_TYPE_Q2_K;
  16034. }
  16035. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  16036. new_type = GGML_TYPE_IQ3_S;
  16037. }
  16038. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  16039. new_type = GGML_TYPE_IQ3_S;
  16040. }
  16041. else if (ftype == LLAMA_FTYPE_MOSTLY_TQ1_0 || ftype == LLAMA_FTYPE_MOSTLY_TQ2_0) {
  16042. new_type = GGML_TYPE_Q4_K;
  16043. }
  16044. }
  16045. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  16046. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  16047. if (name.find("attn_v.weight") != std::string::npos) {
  16048. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  16049. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  16050. ++qs.i_attention_wv;
  16051. }
  16052. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  16053. new_type = GGML_TYPE_Q4_K;
  16054. }
  16055. else if (name.find("ffn_down") != std::string::npos) {
  16056. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  16057. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  16058. }
  16059. ++qs.i_ffn_down;
  16060. }
  16061. else if (name.find("attn_output.weight") != std::string::npos) {
  16062. if (qs.model.hparams.n_expert == 8) {
  16063. new_type = GGML_TYPE_Q5_K;
  16064. } else {
  16065. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) new_type = GGML_TYPE_IQ2_XXS;
  16066. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  16067. }
  16068. }
  16069. } else if (name.find("attn_v.weight") != std::string::npos) {
  16070. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  16071. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  16072. }
  16073. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  16074. new_type = GGML_TYPE_Q4_K;
  16075. }
  16076. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  16077. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  16078. }
  16079. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S) && qs.model.hparams.n_gqa() >= 4) {
  16080. new_type = GGML_TYPE_Q4_K;
  16081. }
  16082. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  16083. new_type = GGML_TYPE_Q4_K;
  16084. }
  16085. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  16086. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  16087. }
  16088. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  16089. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  16090. new_type = GGML_TYPE_Q5_K;
  16091. }
  16092. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  16093. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  16094. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  16095. if (qs.model.type == MODEL_70B) {
  16096. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  16097. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  16098. // nearly negligible increase in model size by quantizing this tensor with more bits:
  16099. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  16100. }
  16101. if (qs.model.hparams.n_expert == 8) {
  16102. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  16103. // TODO: explore better strategies
  16104. new_type = GGML_TYPE_Q8_0;
  16105. }
  16106. ++qs.i_attention_wv;
  16107. } else if (name.find("attn_k.weight") != std::string::npos) {
  16108. if (qs.model.hparams.n_expert == 8) {
  16109. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  16110. // TODO: explore better strategies
  16111. new_type = GGML_TYPE_Q8_0;
  16112. }
  16113. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  16114. new_type = GGML_TYPE_IQ3_XXS;
  16115. }
  16116. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  16117. new_type = GGML_TYPE_IQ2_S;
  16118. }
  16119. } else if (name.find("attn_q.weight") != std::string::npos) {
  16120. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  16121. new_type = GGML_TYPE_IQ3_XXS;
  16122. }
  16123. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  16124. new_type = GGML_TYPE_IQ2_S;
  16125. }
  16126. } else if (name.find("ffn_down") != std::string::npos) {
  16127. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  16128. int i_layer = info.first, n_layer = info.second;
  16129. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  16130. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  16131. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  16132. }
  16133. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  16134. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  16135. }
  16136. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  16137. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  16138. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  16139. : GGML_TYPE_Q3_K;
  16140. }
  16141. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  16142. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  16143. new_type = GGML_TYPE_Q4_K;
  16144. }
  16145. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  16146. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  16147. }
  16148. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  16149. if (arch == LLM_ARCH_FALCON) {
  16150. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  16151. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  16152. } else {
  16153. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  16154. }
  16155. }
  16156. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  16157. new_type = GGML_TYPE_Q5_K;
  16158. }
  16159. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  16160. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  16161. new_type = GGML_TYPE_Q5_K;
  16162. }
  16163. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  16164. && qs.has_imatrix && i_layer < n_layer/8) {
  16165. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  16166. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  16167. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  16168. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  16169. }
  16170. ++qs.i_ffn_down;
  16171. } else if (name.find("attn_output.weight") != std::string::npos) {
  16172. if (arch != LLM_ARCH_FALCON) {
  16173. if (qs.model.hparams.n_expert == 8) {
  16174. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  16175. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  16176. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  16177. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  16178. new_type = GGML_TYPE_Q5_K;
  16179. }
  16180. } else {
  16181. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  16182. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  16183. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  16184. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  16185. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  16186. }
  16187. } else {
  16188. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  16189. }
  16190. }
  16191. else if (name.find("attn_qkv.weight") != std::string::npos) {
  16192. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  16193. new_type = GGML_TYPE_Q4_K;
  16194. }
  16195. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  16196. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  16197. }
  16198. else if (name.find("ffn_gate") != std::string::npos) {
  16199. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  16200. int i_layer = info.first, n_layer = info.second;
  16201. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  16202. new_type = GGML_TYPE_IQ3_XXS;
  16203. }
  16204. ++qs.i_ffn_gate;
  16205. }
  16206. else if (name.find("ffn_up") != std::string::npos) {
  16207. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  16208. int i_layer = info.first, n_layer = info.second;
  16209. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  16210. new_type = GGML_TYPE_IQ3_XXS;
  16211. }
  16212. ++qs.i_ffn_up;
  16213. }
  16214. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  16215. //}
  16216. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  16217. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  16218. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  16219. //}
  16220. // This can be used to reduce the size of the Q5_K_S model.
  16221. // The associated PPL increase is fully in line with the size reduction
  16222. //else {
  16223. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  16224. //}
  16225. bool convert_incompatible_tensor = false;
  16226. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  16227. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  16228. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  16229. new_type == GGML_TYPE_IQ3_XXS || new_type == GGML_TYPE_IQ1_S || new_type == GGML_TYPE_IQ3_S ||
  16230. new_type == GGML_TYPE_IQ1_M) {
  16231. int nx = tensor->ne[0];
  16232. int ny = tensor->ne[1];
  16233. if (nx % QK_K != 0) {
  16234. 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));
  16235. convert_incompatible_tensor = true;
  16236. } else {
  16237. ++qs.n_k_quantized;
  16238. }
  16239. }
  16240. if (convert_incompatible_tensor) {
  16241. switch (new_type) {
  16242. case GGML_TYPE_TQ1_0:
  16243. case GGML_TYPE_TQ2_0: new_type = GGML_TYPE_Q4_0; break; // TODO: use a symmetric type instead
  16244. case GGML_TYPE_IQ2_XXS:
  16245. case GGML_TYPE_IQ2_XS:
  16246. case GGML_TYPE_IQ2_S:
  16247. case GGML_TYPE_IQ3_XXS:
  16248. case GGML_TYPE_IQ3_S:
  16249. case GGML_TYPE_IQ1_S:
  16250. case GGML_TYPE_IQ1_M:
  16251. case GGML_TYPE_Q2_K:
  16252. case GGML_TYPE_Q3_K:
  16253. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  16254. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  16255. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  16256. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  16257. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  16258. }
  16259. if (tensor->ne[0] % ggml_blck_size(new_type) != 0) {
  16260. new_type = GGML_TYPE_F16;
  16261. }
  16262. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  16263. ++qs.n_fallback;
  16264. }
  16265. return new_type;
  16266. }
  16267. 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) {
  16268. if (nthread < 2) {
  16269. // single-thread
  16270. size_t new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, imatrix);
  16271. if (!ggml_validate_row_data(new_type, new_data, new_size)) {
  16272. throw std::runtime_error("quantized data validation failed");
  16273. }
  16274. return new_size;
  16275. }
  16276. std::mutex mutex;
  16277. int64_t counter = 0;
  16278. size_t new_size = 0;
  16279. bool valid = true;
  16280. auto compute = [&mutex, &counter, &new_size, &valid, new_type, f32_data, new_data, chunk_size,
  16281. nrows, n_per_row, imatrix]() {
  16282. const int64_t nrows_per_chunk = chunk_size / n_per_row;
  16283. size_t local_size = 0;
  16284. while (true) {
  16285. std::unique_lock<std::mutex> lock(mutex);
  16286. int64_t first_row = counter; counter += nrows_per_chunk;
  16287. if (first_row >= nrows) {
  16288. if (local_size > 0) {
  16289. new_size += local_size;
  16290. }
  16291. break;
  16292. }
  16293. lock.unlock();
  16294. const int64_t this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  16295. size_t this_size = ggml_quantize_chunk(new_type, f32_data, new_data, first_row * n_per_row, this_nrow, n_per_row, imatrix);
  16296. local_size += this_size;
  16297. // validate the quantized data
  16298. const size_t row_size = ggml_row_size(new_type, n_per_row);
  16299. void * this_data = (char *) new_data + first_row * row_size;
  16300. if (!ggml_validate_row_data(new_type, this_data, this_size)) {
  16301. std::unique_lock<std::mutex> lock(mutex);
  16302. valid = false;
  16303. break;
  16304. }
  16305. }
  16306. };
  16307. for (int it = 0; it < nthread - 1; ++it) {
  16308. workers.emplace_back(compute);
  16309. }
  16310. compute();
  16311. for (auto & w : workers) { w.join(); }
  16312. workers.clear();
  16313. if (!valid) {
  16314. throw std::runtime_error("quantized data validation failed");
  16315. }
  16316. return new_size;
  16317. }
  16318. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  16319. ggml_type default_type;
  16320. llama_ftype ftype = params->ftype;
  16321. switch (params->ftype) {
  16322. case LLAMA_FTYPE_MOSTLY_Q4_0: default_type = GGML_TYPE_Q4_0; break;
  16323. case LLAMA_FTYPE_MOSTLY_Q4_1: default_type = GGML_TYPE_Q4_1; break;
  16324. case LLAMA_FTYPE_MOSTLY_Q5_0: default_type = GGML_TYPE_Q5_0; break;
  16325. case LLAMA_FTYPE_MOSTLY_Q5_1: default_type = GGML_TYPE_Q5_1; break;
  16326. case LLAMA_FTYPE_MOSTLY_Q8_0: default_type = GGML_TYPE_Q8_0; break;
  16327. case LLAMA_FTYPE_MOSTLY_F16: default_type = GGML_TYPE_F16; break;
  16328. case LLAMA_FTYPE_MOSTLY_BF16: default_type = GGML_TYPE_BF16; break;
  16329. case LLAMA_FTYPE_ALL_F32: default_type = GGML_TYPE_F32; break;
  16330. // K-quants
  16331. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  16332. case LLAMA_FTYPE_MOSTLY_Q2_K: default_type = GGML_TYPE_Q2_K; break;
  16333. case LLAMA_FTYPE_MOSTLY_IQ3_XS: default_type = GGML_TYPE_IQ3_S; break;
  16334. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  16335. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  16336. case LLAMA_FTYPE_MOSTLY_Q3_K_L: default_type = GGML_TYPE_Q3_K; break;
  16337. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  16338. case LLAMA_FTYPE_MOSTLY_Q4_K_M: default_type = GGML_TYPE_Q4_K; break;
  16339. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  16340. case LLAMA_FTYPE_MOSTLY_Q5_K_M: default_type = GGML_TYPE_Q5_K; break;
  16341. case LLAMA_FTYPE_MOSTLY_Q6_K: default_type = GGML_TYPE_Q6_K; break;
  16342. case LLAMA_FTYPE_MOSTLY_TQ1_0: default_type = GGML_TYPE_TQ1_0; break;
  16343. case LLAMA_FTYPE_MOSTLY_TQ2_0: default_type = GGML_TYPE_TQ2_0; break;
  16344. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: default_type = GGML_TYPE_IQ2_XXS; break;
  16345. case LLAMA_FTYPE_MOSTLY_IQ2_XS: default_type = GGML_TYPE_IQ2_XS; break;
  16346. case LLAMA_FTYPE_MOSTLY_IQ2_S: default_type = GGML_TYPE_IQ2_XS; break;
  16347. case LLAMA_FTYPE_MOSTLY_IQ2_M: default_type = GGML_TYPE_IQ2_S; break;
  16348. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: default_type = GGML_TYPE_IQ3_XXS; break;
  16349. case LLAMA_FTYPE_MOSTLY_IQ1_S: default_type = GGML_TYPE_IQ1_S; break;
  16350. case LLAMA_FTYPE_MOSTLY_IQ1_M: default_type = GGML_TYPE_IQ1_M; break;
  16351. case LLAMA_FTYPE_MOSTLY_IQ4_NL: default_type = GGML_TYPE_IQ4_NL; break;
  16352. case LLAMA_FTYPE_MOSTLY_IQ4_XS: default_type = GGML_TYPE_IQ4_XS; break;
  16353. case LLAMA_FTYPE_MOSTLY_IQ3_S: default_type = GGML_TYPE_IQ3_S; break;
  16354. case LLAMA_FTYPE_MOSTLY_IQ3_M: default_type = GGML_TYPE_IQ3_S; break;
  16355. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  16356. }
  16357. int nthread = params->nthread;
  16358. if (nthread <= 0) {
  16359. nthread = std::thread::hardware_concurrency();
  16360. }
  16361. // mmap consistently increases speed Linux, and also increases speed on Windows with
  16362. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  16363. #if defined(__linux__) || defined(_WIN32)
  16364. constexpr bool use_mmap = true;
  16365. #else
  16366. constexpr bool use_mmap = false;
  16367. #endif
  16368. llama_model_kv_override * kv_overrides = nullptr;
  16369. if (params->kv_overrides) {
  16370. auto v = (std::vector<llama_model_kv_override>*)params->kv_overrides;
  16371. kv_overrides = v->data();
  16372. }
  16373. llama_model_loader ml(fname_inp, use_mmap, /*check_tensors*/ true, kv_overrides);
  16374. ml.init_mappings(false); // no prefetching
  16375. llama_model model;
  16376. llm_load_arch(ml, model);
  16377. llm_load_hparams(ml, model);
  16378. llm_load_stats(ml, model);
  16379. struct quantize_state_internal qs(model, params);
  16380. if (params->only_copy) {
  16381. ftype = model.ftype;
  16382. }
  16383. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  16384. if (params->imatrix) {
  16385. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  16386. if (imatrix_data) {
  16387. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  16388. qs.has_imatrix = true;
  16389. // check imatrix for nans or infs
  16390. for (const auto & kv : *imatrix_data) {
  16391. for (float f : kv.second) {
  16392. if (!std::isfinite(f)) {
  16393. throw std::runtime_error(format("imatrix contains non-finite value %f\n", f));
  16394. }
  16395. }
  16396. }
  16397. }
  16398. }
  16399. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  16400. gguf_context_ptr ctx_out { gguf_init_empty() };
  16401. // copy the KV pairs from the input file
  16402. gguf_set_kv (ctx_out.get(), ml.meta.get());
  16403. gguf_set_val_u32(ctx_out.get(), "general.quantization_version", GGML_QNT_VERSION); // TODO: use LLM_KV
  16404. gguf_set_val_u32(ctx_out.get(), "general.file_type", ftype); // TODO: use LLM_KV
  16405. // Remove split metadata
  16406. gguf_remove_key(ctx_out.get(), ml.llm_kv(LLM_KV_SPLIT_NO).c_str());
  16407. gguf_remove_key(ctx_out.get(), ml.llm_kv(LLM_KV_SPLIT_COUNT).c_str());
  16408. gguf_remove_key(ctx_out.get(), ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str());
  16409. if (params->kv_overrides) {
  16410. const std::vector<llama_model_kv_override> & overrides = *(const std::vector<llama_model_kv_override> *)params->kv_overrides;
  16411. for (const auto & o : overrides) {
  16412. if (o.key[0] == 0) break;
  16413. if (o.tag == LLAMA_KV_OVERRIDE_TYPE_FLOAT) {
  16414. gguf_set_val_f32(ctx_out.get(), o.key, o.val_f64);
  16415. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_INT) {
  16416. gguf_set_val_i32(ctx_out.get(), o.key, o.val_i64);
  16417. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_BOOL) {
  16418. gguf_set_val_bool(ctx_out.get(), o.key, o.val_bool);
  16419. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_STR) {
  16420. gguf_set_val_str(ctx_out.get(), o.key, o.val_str);
  16421. } else {
  16422. LLAMA_LOG_WARN("%s: unknown KV override type for key %s\n", __func__, o.key);
  16423. }
  16424. }
  16425. }
  16426. // make a list of weights
  16427. std::vector<const llama_model_loader::llama_tensor_weight *> tensors;
  16428. tensors.reserve(ml.weights_map.size());
  16429. for (const auto & it : ml.weights_map) {
  16430. tensors.push_back(&it.second);
  16431. }
  16432. // keep_split requires that the weights are sorted by split index
  16433. if (params->keep_split) {
  16434. std::sort(tensors.begin(), tensors.end(), [](const llama_model_loader::llama_tensor_weight * a, const llama_model_loader::llama_tensor_weight * b) {
  16435. if (a->idx == b->idx) {
  16436. return a->offs < b->offs;
  16437. }
  16438. return a->idx < b->idx;
  16439. });
  16440. }
  16441. for (const auto * it : tensors) {
  16442. const struct ggml_tensor * tensor = it->tensor;
  16443. const std::string name = ggml_get_name(tensor);
  16444. // TODO: avoid hardcoded tensor names - use the TN_* constants
  16445. if (name.find("attn_v.weight") != std::string::npos ||
  16446. name.find("attn_qkv.weight") != std::string::npos ||
  16447. name.find("attn_kv_b.weight")!= std::string::npos) {
  16448. ++qs.n_attention_wv;
  16449. } else if (name == LLM_TN(model.arch)(LLM_TENSOR_OUTPUT, "weight")) {
  16450. qs.has_output = true;
  16451. }
  16452. }
  16453. qs.n_ffn_down = qs.n_ffn_gate = qs.n_ffn_up = (int)model.hparams.n_layer;
  16454. // sanity checks
  16455. {
  16456. const auto & n_head_kv_iter = model.hparams.n_head_kv_arr.begin();
  16457. // attention layers have a non-zero number of kv heads
  16458. int32_t n_attn_layer = model.hparams.n_layer - std::count(n_head_kv_iter, n_head_kv_iter + model.hparams.n_layer, 0);
  16459. if (llama_model_has_encoder(&model)) {
  16460. n_attn_layer *= 3;
  16461. }
  16462. if (qs.n_attention_wv != n_attn_layer) {
  16463. LLAMA_LOG_WARN("%s: n_attention_wv is unexpected, expected: %d, found: %d\n", __func__, n_attn_layer, qs.n_attention_wv);
  16464. }
  16465. }
  16466. size_t total_size_org = 0;
  16467. size_t total_size_new = 0;
  16468. std::vector<std::thread> workers;
  16469. workers.reserve(nthread);
  16470. int idx = 0;
  16471. std::vector<no_init<uint8_t>> read_data;
  16472. std::vector<no_init<uint8_t>> work;
  16473. std::vector<no_init<float>> f32_conv_buf;
  16474. uint16_t n_split = 1;
  16475. // Assume split index is continuous
  16476. if (params->keep_split) {
  16477. for (const auto * it : tensors) {
  16478. n_split = std::max(uint16_t(it->idx + 1), n_split);
  16479. }
  16480. }
  16481. std::vector<gguf_context_ptr> ctx_outs(n_split);
  16482. ctx_outs[0] = std::move(ctx_out);
  16483. // populate the original tensors so we get an initial meta data
  16484. for (const auto * it : tensors) {
  16485. uint16_t i_split = params->keep_split ? it->idx : 0;
  16486. struct ggml_tensor * tensor = it->tensor;
  16487. if (!ctx_outs[i_split]) {
  16488. ctx_outs[i_split].reset(gguf_init_empty());
  16489. }
  16490. gguf_add_tensor(ctx_outs[i_split].get(), tensor);
  16491. }
  16492. // Set split info if needed
  16493. if (n_split > 1) {
  16494. for (size_t i = 0; i < ctx_outs.size(); ++i) {
  16495. gguf_set_val_u16(ctx_outs[i].get(), ml.llm_kv(LLM_KV_SPLIT_NO).c_str(), i);
  16496. gguf_set_val_u16(ctx_outs[i].get(), ml.llm_kv(LLM_KV_SPLIT_COUNT).c_str(), n_split);
  16497. gguf_set_val_i32(ctx_outs[i].get(), ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str(), ml.n_tensors);
  16498. }
  16499. }
  16500. int cur_split = -1;
  16501. std::ofstream fout;
  16502. auto close_ofstream = [&]() {
  16503. // Write metadata and close file handler
  16504. if (fout.is_open()) {
  16505. fout.seekp(0);
  16506. std::vector<uint8_t> data(gguf_get_meta_size(ctx_outs[cur_split].get()));
  16507. gguf_get_meta_data(ctx_outs[cur_split].get(), data.data());
  16508. fout.write((const char *) data.data(), data.size());
  16509. fout.close();
  16510. }
  16511. };
  16512. auto new_ofstream = [&](int index) {
  16513. cur_split = index;
  16514. GGML_ASSERT(ctx_outs[cur_split] && "Find uninitialized gguf_context");
  16515. std::string fname = fname_out;
  16516. if (params->keep_split) {
  16517. char split_path[PATH_MAX] = {0};
  16518. llama_split_path(split_path, sizeof(split_path), fname_out.c_str(), cur_split, n_split);
  16519. fname = std::string(split_path);
  16520. }
  16521. fout = std::ofstream(fname, std::ios::binary);
  16522. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  16523. const size_t meta_size = gguf_get_meta_size(ctx_outs[cur_split].get());
  16524. // placeholder for the meta data
  16525. ::zeros(fout, meta_size);
  16526. };
  16527. const auto tn = LLM_TN(model.arch);
  16528. new_ofstream(0);
  16529. for (const auto * it : tensors) {
  16530. const auto & weight = *it;
  16531. struct ggml_tensor * tensor = weight.tensor;
  16532. if (weight.idx != cur_split && params->keep_split) {
  16533. close_ofstream();
  16534. new_ofstream(weight.idx);
  16535. }
  16536. const std::string name = ggml_get_name(tensor);
  16537. if (!ml.use_mmap) {
  16538. if (read_data.size() < ggml_nbytes(tensor)) {
  16539. read_data.resize(ggml_nbytes(tensor));
  16540. }
  16541. tensor->data = read_data.data();
  16542. }
  16543. ml.load_data_for(tensor);
  16544. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  16545. ++idx, ml.n_tensors,
  16546. ggml_get_name(tensor),
  16547. llama_format_tensor_shape(tensor).c_str(),
  16548. ggml_type_name(tensor->type));
  16549. // This used to be a regex, but <regex> has an extreme cost to compile times.
  16550. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  16551. // quantize only 2D and 3D tensors (experts)
  16552. quantize &= (ggml_n_dims(tensor) >= 2);
  16553. // do not quantize norm tensors
  16554. quantize &= name.find("_norm.weight") == std::string::npos;
  16555. quantize &= params->quantize_output_tensor || name != "output.weight";
  16556. quantize &= !params->only_copy;
  16557. // do not quantize expert gating tensors
  16558. // NOTE: can't use LLM_TN here because the layer number is not known
  16559. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  16560. // do not quantize positional embeddings and token types (BERT)
  16561. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  16562. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  16563. // do not quantize Mamba's small yet 2D weights
  16564. // NOTE: can't use LLM_TN here because the layer number is not known
  16565. quantize &= name.find("ssm_conv1d.weight") == std::string::npos;
  16566. // do not quantize RWKV's time_mix_first tensors
  16567. quantize &= name.find("time_mix_first.weight") == std::string::npos;
  16568. quantize &= name.find("time_mix_w1.weight") == std::string::npos;
  16569. quantize &= name.find("time_mix_w2.weight") == std::string::npos;
  16570. quantize &= name.find("time_mix_decay_w1.weight") == std::string::npos;
  16571. quantize &= name.find("time_mix_decay_w2.weight") == std::string::npos;
  16572. // do not quantize relative position bias (T5)
  16573. quantize &= name.find("attn_rel_b.weight") == std::string::npos;
  16574. enum ggml_type new_type;
  16575. void * new_data;
  16576. size_t new_size;
  16577. if (quantize) {
  16578. new_type = default_type;
  16579. // get more optimal quantization type based on the tensor shape, layer, etc.
  16580. if (!params->pure && ggml_is_quantized(default_type)) {
  16581. new_type = llama_tensor_get_type(qs, new_type, tensor, ftype);
  16582. }
  16583. if (params->token_embedding_type < GGML_TYPE_COUNT && strcmp(tensor->name, "token_embd.weight") == 0) {
  16584. new_type = params->token_embedding_type;
  16585. }
  16586. if (params->output_tensor_type < GGML_TYPE_COUNT && strcmp(tensor->name, "output.weight") == 0) {
  16587. new_type = params->output_tensor_type;
  16588. }
  16589. // If we've decided to quantize to the same type the tensor is already
  16590. // in then there's nothing to do.
  16591. quantize = tensor->type != new_type;
  16592. }
  16593. if (!quantize) {
  16594. new_type = tensor->type;
  16595. new_data = tensor->data;
  16596. new_size = ggml_nbytes(tensor);
  16597. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  16598. } else {
  16599. const int64_t nelements = ggml_nelements(tensor);
  16600. const float * imatrix = nullptr;
  16601. if (imatrix_data) {
  16602. auto it = imatrix_data->find(tensor->name);
  16603. if (it == imatrix_data->end()) {
  16604. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  16605. } else {
  16606. if (it->second.size() == (size_t)tensor->ne[0]*tensor->ne[2]) {
  16607. imatrix = it->second.data();
  16608. } else {
  16609. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  16610. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name);
  16611. // this can happen when quantizing an old mixtral model with split tensors with a new incompatible imatrix
  16612. // this is a significant error and it may be good idea to abort the process if this happens,
  16613. // since many people will miss the error and not realize that most of the model is being quantized without an imatrix
  16614. // tok_embd should be ignored in this case, since it always causes this warning
  16615. if (name != tn(LLM_TENSOR_TOKEN_EMBD, "weight")) {
  16616. throw std::runtime_error(format("imatrix size %d is different from tensor size %d for %s",
  16617. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name));
  16618. }
  16619. }
  16620. }
  16621. }
  16622. if ((new_type == GGML_TYPE_IQ2_XXS ||
  16623. new_type == GGML_TYPE_IQ2_XS ||
  16624. new_type == GGML_TYPE_IQ2_S ||
  16625. new_type == GGML_TYPE_IQ1_S ||
  16626. (new_type == GGML_TYPE_IQ1_M && strcmp(tensor->name, "token_embd.weight") && strcmp(tensor->name, "output.weight")) ||
  16627. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  16628. LLAMA_LOG_ERROR("\n\n============================================================\n");
  16629. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  16630. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  16631. LLAMA_LOG_ERROR("============================================================\n\n");
  16632. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  16633. }
  16634. float * f32_data;
  16635. if (tensor->type == GGML_TYPE_F32) {
  16636. f32_data = (float *) tensor->data;
  16637. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  16638. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  16639. } else {
  16640. llama_tensor_dequantize_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  16641. f32_data = (float *) f32_conv_buf.data();
  16642. }
  16643. LLAMA_LOG_INFO("converting to %s .. ", ggml_type_name(new_type));
  16644. fflush(stdout);
  16645. if (work.size() < (size_t)nelements * 4) {
  16646. work.resize(nelements * 4); // upper bound on size
  16647. }
  16648. new_data = work.data();
  16649. const int64_t n_per_row = tensor->ne[0];
  16650. const int64_t nrows = tensor->ne[1];
  16651. static const int64_t min_chunk_size = 32 * 512;
  16652. 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));
  16653. const int64_t nelements_matrix = tensor->ne[0] * tensor->ne[1];
  16654. const int64_t nchunk = (nelements_matrix + chunk_size - 1)/chunk_size;
  16655. const int64_t nthread_use = nthread > 1 ? std::max((int64_t)1, std::min((int64_t)nthread, nchunk)) : 1;
  16656. // quantize each expert separately since they have different importance matrices
  16657. new_size = 0;
  16658. for (int64_t i03 = 0; i03 < tensor->ne[2]; ++i03) {
  16659. const float * f32_data_03 = f32_data + i03 * nelements_matrix;
  16660. void * new_data_03 = (char *)new_data + ggml_row_size(new_type, n_per_row) * i03 * nrows;
  16661. const float * imatrix_03 = imatrix ? imatrix + i03 * n_per_row : nullptr;
  16662. 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);
  16663. }
  16664. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB\n", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  16665. }
  16666. total_size_org += ggml_nbytes(tensor);
  16667. total_size_new += new_size;
  16668. // update the gguf meta data as we go
  16669. gguf_set_tensor_type(ctx_outs[cur_split].get(), name.c_str(), new_type);
  16670. gguf_set_tensor_data(ctx_outs[cur_split].get(), name.c_str(), new_data, new_size);
  16671. // write tensor data + padding
  16672. fout.write((const char *) new_data, new_size);
  16673. zeros(fout, GGML_PAD(new_size, align) - new_size);
  16674. }
  16675. close_ofstream();
  16676. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  16677. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  16678. if (qs.n_fallback > 0) {
  16679. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n",
  16680. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  16681. }
  16682. }
  16683. static void llama_lora_adapter_init_internal(struct llama_model * model, const char * path_lora, struct llama_lora_adapter & adapter) {
  16684. LLAMA_LOG_INFO("%s: loading lora adapter from '%s' ...\n", __func__, path_lora);
  16685. ggml_context * ctx_init;
  16686. struct gguf_init_params meta_gguf_params = {
  16687. /* .no_alloc = */ true,
  16688. /* .ctx = */ &ctx_init,
  16689. };
  16690. gguf_context_ptr ctx_gguf { gguf_init_from_file(path_lora, meta_gguf_params) };
  16691. if (!ctx_gguf) {
  16692. throw std::runtime_error("failed to load lora adapter file from " + std::string(path_lora));
  16693. }
  16694. ggml_context_ptr ctx { ctx_init };
  16695. // check metadata
  16696. {
  16697. auto get_kv_str = [&](const std::string & key) -> std::string {
  16698. int id = gguf_find_key(ctx_gguf.get(), key.c_str());
  16699. return id < 0 ? "" : std::string(gguf_get_val_str(ctx_gguf.get(), id));
  16700. };
  16701. auto get_kv_f32 = [&](const std::string & key) -> float {
  16702. int id = gguf_find_key(ctx_gguf.get(), key.c_str());
  16703. return id < 0 ? 0.0f : gguf_get_val_f32(ctx_gguf.get(), id);
  16704. };
  16705. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  16706. auto general_type = get_kv_str(llm_kv(LLM_KV_GENERAL_TYPE));
  16707. if (general_type != "adapter") {
  16708. throw std::runtime_error("expect general.type to be 'adapter', but got: " + general_type);
  16709. }
  16710. auto general_arch_str = get_kv_str(llm_kv(LLM_KV_GENERAL_ARCHITECTURE));
  16711. auto general_arch = llm_arch_from_string(general_arch_str);
  16712. if (general_arch != model->arch) {
  16713. throw std::runtime_error("model arch and LoRA arch mismatch");
  16714. }
  16715. auto adapter_type = get_kv_str(llm_kv(LLM_KV_ADAPTER_TYPE));
  16716. if (adapter_type != "lora") {
  16717. throw std::runtime_error("expect adapter.type to be 'lora', but got: " + adapter_type);
  16718. }
  16719. adapter.alpha = get_kv_f32(llm_kv(LLM_KV_ADAPTER_LORA_ALPHA));
  16720. }
  16721. int n_tensors = gguf_get_n_tensors(ctx_gguf.get());
  16722. // contexts for each buffer type
  16723. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  16724. auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
  16725. auto it = ctx_map.find(buft);
  16726. if (it == ctx_map.end()) {
  16727. // add a new context
  16728. struct ggml_init_params params = {
  16729. /*.mem_size =*/ n_tensors*ggml_tensor_overhead(),
  16730. /*.mem_buffer =*/ NULL,
  16731. /*.no_alloc =*/ true,
  16732. };
  16733. ggml_context * buft_ctx = ggml_init(params);
  16734. if (!buft_ctx) {
  16735. return nullptr;
  16736. }
  16737. ctx_map[buft] = buft_ctx;
  16738. adapter.ctxs.emplace_back(buft_ctx);
  16739. return buft_ctx;
  16740. };
  16741. return it->second;
  16742. };
  16743. // bundle lora_a and lora_b into pairs
  16744. std::map<std::string, llama_lora_weight> ab_map;
  16745. auto str_endswith = [](const std::string & str, const std::string & suffix) {
  16746. return str.size() >= suffix.size() && str.compare(str.size()-suffix.size(), suffix.size(), suffix) == 0;
  16747. };
  16748. for (ggml_tensor * cur = ggml_get_first_tensor(ctx.get()); cur; cur = ggml_get_next_tensor(ctx.get(), cur)) {
  16749. std::string name(cur->name);
  16750. if (str_endswith(name, ".lora_a")) {
  16751. replace_all(name, ".lora_a", "");
  16752. if (ab_map.find(name) == ab_map.end()) {
  16753. ab_map[name] = llama_lora_weight(cur, nullptr);
  16754. } else {
  16755. ab_map[name].a = cur;
  16756. }
  16757. } else if (str_endswith(name, ".lora_b")) {
  16758. replace_all(name, ".lora_b", "");
  16759. if (ab_map.find(name) == ab_map.end()) {
  16760. ab_map[name] = llama_lora_weight(nullptr, cur);
  16761. } else {
  16762. ab_map[name].b = cur;
  16763. }
  16764. } else {
  16765. throw std::runtime_error("LoRA tensor '" + name + "' has unexpected suffix");
  16766. }
  16767. }
  16768. // add tensors
  16769. for (auto & it : ab_map) {
  16770. const std::string & name = it.first;
  16771. llama_lora_weight & w = it.second;
  16772. if (!w.a || !w.b) {
  16773. throw std::runtime_error("LoRA tensor pair for '" + name + "' is missing one component");
  16774. }
  16775. // device buft and device ctx
  16776. auto * model_tensor = llama_get_model_tensor(model, name.c_str());
  16777. if (!model_tensor) {
  16778. throw std::runtime_error("LoRA tensor '" + name + "' does not exist in base model");
  16779. }
  16780. struct ggml_context * dev_ctx = ctx_for_buft(ggml_backend_buffer_get_type(model_tensor->buffer));
  16781. // validate tensor shape
  16782. if (model_tensor->ne[0] != w.a->ne[0] || model_tensor->ne[1] != w.b->ne[1]) {
  16783. throw std::runtime_error("tensor '" + name + "' has incorrect shape");
  16784. }
  16785. if (w.a->ne[1] != w.b->ne[0]) {
  16786. throw std::runtime_error("lora_a tensor is not transposed (hint: adapter from \"finetune\" example is no longer supported)");
  16787. }
  16788. // save tensor to adapter
  16789. struct ggml_tensor * tensor_a = ggml_dup_tensor(dev_ctx, w.a);
  16790. struct ggml_tensor * tensor_b = ggml_dup_tensor(dev_ctx, w.b);
  16791. ggml_set_name(tensor_a, w.a->name);
  16792. ggml_set_name(tensor_b, w.b->name);
  16793. adapter.ab_map[name] = llama_lora_weight(tensor_a, tensor_b);
  16794. }
  16795. // allocate tensors / buffers and zero
  16796. {
  16797. adapter.ctxs.reserve(ctx_map.size());
  16798. adapter.bufs.reserve(ctx_map.size());
  16799. for (auto & it : ctx_map) {
  16800. ggml_backend_buffer_type_t buft = it.first;
  16801. ggml_context * ctx_dev = it.second;
  16802. ggml_backend_buffer_ptr buf { ggml_backend_alloc_ctx_tensors_from_buft(ctx_dev, buft) };
  16803. if (!buf) {
  16804. throw std::runtime_error("failed to allocate buffer for lora adapter\n");
  16805. }
  16806. 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);
  16807. adapter.bufs.emplace_back(std::move(buf));
  16808. }
  16809. }
  16810. // set tensor data
  16811. {
  16812. llama_file gguf_file(path_lora, "rb");
  16813. std::vector<uint8_t> read_buf;
  16814. auto set_tensor = [&](struct ggml_tensor * orig, struct ggml_tensor * dev) {
  16815. 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));
  16816. size_t size = ggml_nbytes(orig);
  16817. read_buf.resize(size);
  16818. gguf_file.seek(offs, SEEK_SET);
  16819. gguf_file.read_raw(read_buf.data(), size);
  16820. ggml_backend_tensor_set(dev, read_buf.data(), 0, size);
  16821. };
  16822. for (auto & it : adapter.ab_map) {
  16823. auto orig = ab_map[it.first];
  16824. auto dev = it.second;
  16825. set_tensor(orig.a, dev.a);
  16826. set_tensor(orig.b, dev.b);
  16827. }
  16828. }
  16829. LLAMA_LOG_INFO("%s: loaded %zu tensors from lora file\n", __func__, adapter.ab_map.size()*2);
  16830. }
  16831. int32_t llama_lora_adapter_set(
  16832. struct llama_context * ctx,
  16833. struct llama_lora_adapter * adapter,
  16834. float scale) {
  16835. if (ctx->cparams.flash_attn) {
  16836. LLAMA_LOG_ERROR("%s: flash_attn is not compatible with LoRA\n", __func__);
  16837. return -1;
  16838. }
  16839. ctx->lora_adapters[adapter] = scale;
  16840. return 0;
  16841. }
  16842. int32_t llama_lora_adapter_remove(
  16843. struct llama_context * ctx,
  16844. struct llama_lora_adapter * adapter) {
  16845. auto pos = ctx->lora_adapters.find(adapter);
  16846. if (pos != ctx->lora_adapters.end()) {
  16847. ctx->lora_adapters.erase(pos);
  16848. return 0;
  16849. }
  16850. return -1;
  16851. }
  16852. void llama_lora_adapter_clear(struct llama_context * ctx) {
  16853. ctx->lora_adapters.clear();
  16854. }
  16855. void llama_lora_adapter_free(struct llama_lora_adapter * adapter) {
  16856. delete adapter;
  16857. }
  16858. //
  16859. // interface implementation
  16860. //
  16861. struct llama_model_params llama_model_default_params() {
  16862. struct llama_model_params result = {
  16863. /*.devices =*/ nullptr,
  16864. /*.n_gpu_layers =*/ 0,
  16865. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  16866. /*.main_gpu =*/ 0,
  16867. /*.tensor_split =*/ nullptr,
  16868. /*.rpc_servers =*/ nullptr,
  16869. /*.progress_callback =*/ nullptr,
  16870. /*.progress_callback_user_data =*/ nullptr,
  16871. /*.kv_overrides =*/ nullptr,
  16872. /*.vocab_only =*/ false,
  16873. /*.use_mmap =*/ true,
  16874. /*.use_mlock =*/ false,
  16875. /*.check_tensors =*/ false,
  16876. };
  16877. #ifdef GGML_USE_METAL
  16878. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  16879. result.n_gpu_layers = 999;
  16880. #endif
  16881. return result;
  16882. }
  16883. struct llama_context_params llama_context_default_params() {
  16884. struct llama_context_params result = {
  16885. /*.n_ctx =*/ 512,
  16886. /*.n_batch =*/ 2048,
  16887. /*.n_ubatch =*/ 512,
  16888. /*.n_seq_max =*/ 1,
  16889. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  16890. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  16891. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  16892. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  16893. /*.attention_type =*/ LLAMA_ATTENTION_TYPE_UNSPECIFIED,
  16894. /*.rope_freq_base =*/ 0.0f,
  16895. /*.rope_freq_scale =*/ 0.0f,
  16896. /*.yarn_ext_factor =*/ -1.0f,
  16897. /*.yarn_attn_factor =*/ 1.0f,
  16898. /*.yarn_beta_fast =*/ 32.0f,
  16899. /*.yarn_beta_slow =*/ 1.0f,
  16900. /*.yarn_orig_ctx =*/ 0,
  16901. /*.defrag_thold =*/ -1.0f,
  16902. /*.cb_eval =*/ nullptr,
  16903. /*.cb_eval_user_data =*/ nullptr,
  16904. /*.type_k =*/ GGML_TYPE_F16,
  16905. /*.type_v =*/ GGML_TYPE_F16,
  16906. /*.logits_all =*/ false,
  16907. /*.embeddings =*/ false,
  16908. /*.offload_kqv =*/ true,
  16909. /*.flash_attn =*/ false,
  16910. /*.no_perf =*/ true,
  16911. /*.abort_callback =*/ nullptr,
  16912. /*.abort_callback_data =*/ nullptr,
  16913. };
  16914. return result;
  16915. }
  16916. struct llama_sampler_chain_params llama_sampler_chain_default_params() {
  16917. struct llama_sampler_chain_params result = {
  16918. /*.no_perf =*/ true,
  16919. };
  16920. return result;
  16921. }
  16922. struct llama_model_quantize_params llama_model_quantize_default_params() {
  16923. struct llama_model_quantize_params result = {
  16924. /*.nthread =*/ 0,
  16925. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  16926. /*.output_tensor_type =*/ GGML_TYPE_COUNT,
  16927. /*.token_embedding_type =*/ GGML_TYPE_COUNT,
  16928. /*.allow_requantize =*/ false,
  16929. /*.quantize_output_tensor =*/ true,
  16930. /*.only_copy =*/ false,
  16931. /*.pure =*/ false,
  16932. /*.keep_split =*/ false,
  16933. /*.imatrix =*/ nullptr,
  16934. /*.kv_overrides =*/ nullptr,
  16935. };
  16936. return result;
  16937. }
  16938. size_t llama_max_devices(void) {
  16939. return 16;
  16940. }
  16941. bool llama_supports_mmap(void) {
  16942. return llama_mmap::SUPPORTED;
  16943. }
  16944. bool llama_supports_mlock(void) {
  16945. return llama_mlock::SUPPORTED;
  16946. }
  16947. bool llama_supports_gpu_offload(void) {
  16948. return ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_GPU) != nullptr ||
  16949. llama_supports_rpc();
  16950. }
  16951. bool llama_supports_rpc(void) {
  16952. return ggml_backend_reg_by_name("RPC") != nullptr;
  16953. }
  16954. void llama_backend_init(void) {
  16955. ggml_time_init();
  16956. // needed to initialize f16 tables
  16957. {
  16958. struct ggml_init_params params = { 0, NULL, false };
  16959. struct ggml_context * ctx = ggml_init(params);
  16960. ggml_free(ctx);
  16961. }
  16962. }
  16963. void llama_numa_init(enum ggml_numa_strategy numa) {
  16964. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  16965. auto * dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
  16966. GGML_ASSERT(dev && "CPU backend is not loaded");
  16967. auto * reg = ggml_backend_dev_backend_reg(dev);
  16968. auto * numa_init_fn = (decltype(ggml_numa_init) *) ggml_backend_reg_get_proc_address(reg, "ggml_backend_cpu_numa_init");
  16969. numa_init_fn(numa);
  16970. }
  16971. }
  16972. void llama_attach_threadpool(
  16973. struct llama_context * ctx,
  16974. ggml_threadpool_t threadpool,
  16975. ggml_threadpool_t threadpool_batch) {
  16976. ctx->threadpool = threadpool;
  16977. ctx->threadpool_batch = threadpool_batch ? threadpool_batch : threadpool;
  16978. }
  16979. void llama_detach_threadpool(struct llama_context * ctx) {
  16980. ctx->threadpool = nullptr;
  16981. ctx->threadpool_batch = nullptr;
  16982. }
  16983. void llama_backend_free(void) {
  16984. ggml_quantize_free();
  16985. }
  16986. int64_t llama_time_us(void) {
  16987. return ggml_time_us();
  16988. }
  16989. struct llama_model * llama_load_model_from_file(
  16990. const char * path_model,
  16991. struct llama_model_params params) {
  16992. ggml_time_init();
  16993. llama_model * model = new llama_model;
  16994. unsigned cur_percentage = 0;
  16995. if (params.progress_callback == NULL) {
  16996. params.progress_callback_user_data = &cur_percentage;
  16997. params.progress_callback = [](float progress, void * ctx) {
  16998. unsigned * cur_percentage_p = (unsigned *) ctx;
  16999. unsigned percentage = (unsigned) (100 * progress);
  17000. while (percentage > *cur_percentage_p) {
  17001. *cur_percentage_p = percentage;
  17002. LLAMA_LOG_CONT(".");
  17003. if (percentage >= 100) {
  17004. LLAMA_LOG_CONT("\n");
  17005. }
  17006. }
  17007. return true;
  17008. };
  17009. }
  17010. if (params.rpc_servers != nullptr && params.rpc_servers[0] != '\0') {
  17011. // split the servers set them into model->rpc_servers
  17012. std::string servers(params.rpc_servers);
  17013. size_t pos = 0;
  17014. while ((pos = servers.find(',')) != std::string::npos) {
  17015. std::string server = servers.substr(0, pos);
  17016. model->rpc_servers.push_back(server);
  17017. servers.erase(0, pos + 1);
  17018. }
  17019. model->rpc_servers.push_back(servers);
  17020. }
  17021. // add RPC devices
  17022. if (!model->rpc_servers.empty()) {
  17023. ggml_backend_reg_t rpc_reg = ggml_backend_reg_by_name("RPC");
  17024. if (!rpc_reg) {
  17025. LLAMA_LOG_ERROR("%s: failed to find RPC backend\n", __func__);
  17026. llama_free_model(model);
  17027. return nullptr;
  17028. }
  17029. typedef ggml_backend_dev_t (*ggml_backend_rpc_add_device_t)(const char * endpoint);
  17030. 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");
  17031. if (!ggml_backend_rpc_add_device_fn) {
  17032. LLAMA_LOG_ERROR("%s: failed to find RPC device add function\n", __func__);
  17033. llama_free_model(model);
  17034. return nullptr;
  17035. }
  17036. for (const std::string & server : model->rpc_servers) {
  17037. ggml_backend_dev_t dev = ggml_backend_rpc_add_device_fn(server.c_str());
  17038. if (dev) {
  17039. model->devices.push_back(dev);
  17040. } else {
  17041. LLAMA_LOG_ERROR("%s: failed to add RPC device for server '%s'\n", __func__, server.c_str());
  17042. llama_free_model(model);
  17043. return nullptr;
  17044. }
  17045. }
  17046. }
  17047. // create list of devices to use with this model
  17048. if (params.devices) {
  17049. for (ggml_backend_dev_t * dev = params.devices; *dev; ++dev) {
  17050. model->devices.push_back(*dev);
  17051. }
  17052. } else {
  17053. // use all available devices
  17054. for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
  17055. ggml_backend_dev_t dev = ggml_backend_dev_get(i);
  17056. switch (ggml_backend_dev_type(dev)) {
  17057. case GGML_BACKEND_DEVICE_TYPE_CPU:
  17058. case GGML_BACKEND_DEVICE_TYPE_ACCEL:
  17059. // skip CPU backends since they are handled separately
  17060. break;
  17061. case GGML_BACKEND_DEVICE_TYPE_GPU:
  17062. model->devices.push_back(dev);
  17063. break;
  17064. }
  17065. }
  17066. }
  17067. // if using single GPU mode, remove all except the main GPU
  17068. if (params.split_mode == LLAMA_SPLIT_MODE_NONE) {
  17069. if (params.main_gpu < 0 || params.main_gpu >= (int)model->devices.size()) {
  17070. LLAMA_LOG_ERROR("%s: invalid value for main_gpu: %d (available devices: %d)\n", __func__, params.main_gpu, (int)model->devices.size());
  17071. llama_free_model(model);
  17072. return nullptr;
  17073. }
  17074. ggml_backend_dev_t main_gpu = model->devices[params.main_gpu];
  17075. model->devices.clear();
  17076. model->devices.push_back(main_gpu);
  17077. }
  17078. for (auto * dev : model->devices) {
  17079. size_t free, total; // NOLINT
  17080. ggml_backend_dev_memory(dev, &free, &total);
  17081. 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);
  17082. }
  17083. int status = llama_model_load(path_model, *model, params);
  17084. GGML_ASSERT(status <= 0);
  17085. if (status < 0) {
  17086. if (status == -1) {
  17087. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  17088. } else if (status == -2) {
  17089. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  17090. }
  17091. llama_free_model(model);
  17092. return nullptr;
  17093. }
  17094. return model;
  17095. }
  17096. void llama_free_model(struct llama_model * model) {
  17097. delete model;
  17098. }
  17099. struct llama_context * llama_new_context_with_model(
  17100. struct llama_model * model,
  17101. struct llama_context_params params) {
  17102. if (!model) {
  17103. LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
  17104. return nullptr;
  17105. }
  17106. if (params.n_batch == 0 && params.n_ubatch == 0) {
  17107. LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
  17108. return nullptr;
  17109. }
  17110. if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
  17111. LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
  17112. return nullptr;
  17113. }
  17114. if (params.flash_attn && model->arch == LLM_ARCH_GROK) {
  17115. LLAMA_LOG_WARN("%s: flash_attn is not compatible with Grok - forcing off\n", __func__);
  17116. params.flash_attn = false;
  17117. }
  17118. if (params.flash_attn && model->hparams.n_embd_head_k != model->hparams.n_embd_head_v) {
  17119. LLAMA_LOG_WARN("%s: flash_attn requires n_embd_head_k == n_embd_head_v - forcing off\n", __func__);
  17120. params.flash_attn = false;
  17121. }
  17122. if (ggml_is_quantized(params.type_v) && !params.flash_attn) {
  17123. LLAMA_LOG_ERROR("%s: V cache quantization requires flash_attn\n", __func__);
  17124. return nullptr;
  17125. }
  17126. llama_context * ctx = new llama_context(*model);
  17127. const auto & hparams = model->hparams;
  17128. auto & cparams = ctx->cparams;
  17129. cparams.n_seq_max = std::max(1u, params.n_seq_max);
  17130. cparams.n_threads = params.n_threads;
  17131. cparams.n_threads_batch = params.n_threads_batch;
  17132. cparams.yarn_ext_factor = params.yarn_ext_factor;
  17133. cparams.yarn_attn_factor = params.yarn_attn_factor;
  17134. cparams.yarn_beta_fast = params.yarn_beta_fast;
  17135. cparams.yarn_beta_slow = params.yarn_beta_slow;
  17136. cparams.defrag_thold = params.defrag_thold;
  17137. cparams.embeddings = params.embeddings;
  17138. cparams.offload_kqv = params.offload_kqv;
  17139. cparams.flash_attn = params.flash_attn;
  17140. cparams.no_perf = params.no_perf;
  17141. cparams.pooling_type = params.pooling_type;
  17142. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  17143. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  17144. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  17145. // this is necessary due to kv_self.n being padded later during inference
  17146. cparams.n_ctx = GGML_PAD(cparams.n_ctx, llama_kv_cache_get_padding(cparams));
  17147. // with causal attention, the batch size is limited by the context size
  17148. cparams.n_batch = hparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
  17149. // the batch has to be at least GGML_KQ_MASK_PAD because we will be padding the KQ_mask
  17150. // this is required by GPU kernels in order to avoid out-of-bounds accesses (e.g. ggml_flash_attn_ext)
  17151. // ref: https://github.com/ggerganov/llama.cpp/pull/5021
  17152. if (cparams.n_batch < GGML_KQ_MASK_PAD) {
  17153. LLAMA_LOG_WARN("%s: n_batch is less than GGML_KQ_MASK_PAD - increasing to %d\n", __func__, GGML_KQ_MASK_PAD);
  17154. cparams.n_batch = GGML_KQ_MASK_PAD;
  17155. }
  17156. cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
  17157. cparams.n_ctx_orig_yarn = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  17158. hparams.n_ctx_orig_yarn != 0 ? hparams.n_ctx_orig_yarn :
  17159. hparams.n_ctx_train;
  17160. cparams.cb_eval = params.cb_eval;
  17161. cparams.cb_eval_user_data = params.cb_eval_user_data;
  17162. auto rope_scaling_type = params.rope_scaling_type;
  17163. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  17164. rope_scaling_type = hparams.rope_scaling_type_train;
  17165. }
  17166. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  17167. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  17168. }
  17169. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  17170. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  17171. }
  17172. cparams.yarn_attn_factor *= hparams.rope_attn_factor;
  17173. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  17174. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  17175. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  17176. } else {
  17177. cparams.pooling_type = hparams.pooling_type;
  17178. }
  17179. }
  17180. if (params.attention_type == LLAMA_ATTENTION_TYPE_UNSPECIFIED) {
  17181. cparams.causal_attn = hparams.causal_attn;
  17182. } else {
  17183. cparams.causal_attn = params.attention_type == LLAMA_ATTENTION_TYPE_CAUSAL;
  17184. }
  17185. const uint32_t n_ctx_per_seq = cparams.n_ctx / cparams.n_seq_max;
  17186. LLAMA_LOG_INFO("%s: n_seq_max = %u\n", __func__, cparams.n_seq_max);
  17187. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  17188. LLAMA_LOG_INFO("%s: n_ctx_per_seq = %u\n", __func__, n_ctx_per_seq);
  17189. LLAMA_LOG_INFO("%s: n_batch = %u\n", __func__, cparams.n_batch);
  17190. LLAMA_LOG_INFO("%s: n_ubatch = %u\n", __func__, cparams.n_ubatch);
  17191. LLAMA_LOG_INFO("%s: flash_attn = %d\n", __func__, cparams.flash_attn);
  17192. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  17193. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  17194. if (n_ctx_per_seq < hparams.n_ctx_train) {
  17195. LLAMA_LOG_WARN("%s: n_ctx_per_seq (%u) < n_ctx_train (%u) -- the full capacity of the model will not be utilized\n",
  17196. __func__, n_ctx_per_seq, hparams.n_ctx_train);
  17197. }
  17198. if (n_ctx_per_seq > hparams.n_ctx_train) {
  17199. LLAMA_LOG_WARN("%s: n_ctx_pre_seq (%u) > n_ctx_train (%u) -- possible training context overflow\n",
  17200. __func__, n_ctx_per_seq, hparams.n_ctx_train);
  17201. }
  17202. ctx->logits_all = params.logits_all;
  17203. // build worst-case graph for encoder if a model contains encoder
  17204. ctx->is_encoding = llama_model_has_encoder(model);
  17205. uint32_t kv_size = cparams.n_ctx;
  17206. ggml_type type_k = params.type_k;
  17207. ggml_type type_v = params.type_v;
  17208. // Mamba only needs a constant number of KV cache cells per sequence
  17209. if (llama_model_is_recurrent(model)) {
  17210. // Mamba needs at least as many KV cells as there are sequences kept at any time
  17211. kv_size = std::max((uint32_t) 1, params.n_seq_max);
  17212. // it's probably best to keep as much precision as possible for the states
  17213. type_k = GGML_TYPE_F32; // required by ggml_ssm_conv for Mamba's conv_states
  17214. type_v = GGML_TYPE_F32; // required by ggml_ssm_scan for Mamba's ssm_states
  17215. }
  17216. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  17217. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  17218. if (!hparams.vocab_only) {
  17219. // GPU backends
  17220. for (auto * dev : model->devices) {
  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. // add ACCEL backends (such as BLAS)
  17230. for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
  17231. ggml_backend_dev_t dev = ggml_backend_dev_get(i);
  17232. if (ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_ACCEL) {
  17233. ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr);
  17234. if (backend == nullptr) {
  17235. LLAMA_LOG_ERROR("%s: failed to initialize %s backend\n", __func__, ggml_backend_dev_name(dev));
  17236. llama_free(ctx);
  17237. return nullptr;
  17238. }
  17239. ctx->backends.emplace_back(backend);
  17240. }
  17241. }
  17242. // add CPU backend
  17243. ctx->backend_cpu = ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr);
  17244. if (ctx->backend_cpu == nullptr) {
  17245. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  17246. llama_free(ctx);
  17247. return nullptr;
  17248. }
  17249. ctx->backends.emplace_back(ctx->backend_cpu);
  17250. // create a list of the set_n_threads functions in the backends
  17251. for (auto & backend : ctx->backends) {
  17252. ggml_backend_dev_t dev = ggml_backend_get_device(backend.get());
  17253. ggml_backend_reg_t reg = dev ? ggml_backend_dev_backend_reg(dev) : nullptr;
  17254. if (reg) {
  17255. 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");
  17256. if (ggml_backend_set_n_threads_fn) {
  17257. ctx->set_n_threads_fns.emplace_back(backend.get(), ggml_backend_set_n_threads_fn);
  17258. }
  17259. }
  17260. }
  17261. llama_set_abort_callback(ctx, params.abort_callback, params.abort_callback_data);
  17262. if (!llama_kv_cache_init(ctx->kv_self, ctx, type_k, type_v, kv_size, cparams.offload_kqv)) {
  17263. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  17264. llama_free(ctx);
  17265. return nullptr;
  17266. }
  17267. {
  17268. size_t memory_size_k = 0;
  17269. size_t memory_size_v = 0;
  17270. for (auto & k : ctx->kv_self.k_l) {
  17271. memory_size_k += ggml_nbytes(k);
  17272. }
  17273. for (auto & v : ctx->kv_self.v_l) {
  17274. memory_size_v += ggml_nbytes(v);
  17275. }
  17276. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  17277. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  17278. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  17279. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  17280. }
  17281. // graph outputs buffer
  17282. {
  17283. // resized during inference when a batch uses more outputs
  17284. if (llama_output_reserve(*ctx, params.n_seq_max) < params.n_seq_max) {
  17285. LLAMA_LOG_ERROR("%s: failed to reserve initial output buffer\n", __func__);
  17286. llama_free(ctx);
  17287. return nullptr;
  17288. }
  17289. LLAMA_LOG_INFO("%s: %10s output buffer size = %8.2f MiB\n", __func__,
  17290. ggml_backend_buffer_name(ctx->buf_output.get()),
  17291. ggml_backend_buffer_get_size(ctx->buf_output.get()) / 1024.0 / 1024.0);
  17292. }
  17293. // scheduler and compute buffers
  17294. {
  17295. // buffer types used for the compute buffer of each backend
  17296. std::vector<ggml_backend_buffer_type_t> backend_buft;
  17297. std::vector<ggml_backend_t> backend_ptrs;
  17298. for (auto & backend : ctx->backends) {
  17299. auto * buft = ggml_backend_get_default_buffer_type(backend.get());
  17300. auto backend_type = ggml_backend_dev_type(ggml_backend_get_device(backend.get()));
  17301. if (backend_type == GGML_BACKEND_DEVICE_TYPE_CPU && !model->devices.empty()) {
  17302. // use the host buffer of the first device CPU for faster transfer of the intermediate state
  17303. auto * dev = model->devices[0];
  17304. auto * host_buft = ggml_backend_dev_host_buffer_type(dev);
  17305. if (host_buft) {
  17306. buft = host_buft;
  17307. }
  17308. }
  17309. backend_buft.push_back(buft);
  17310. backend_ptrs.push_back(backend.get());
  17311. }
  17312. const size_t max_nodes = llama_model_max_nodes(*model);
  17313. // buffer used to store the computation graph and the tensor meta data
  17314. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*max_nodes + ggml_graph_overhead_custom(max_nodes, false));
  17315. // TODO: move these checks to ggml_backend_sched
  17316. // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
  17317. bool pipeline_parallel =
  17318. llama_get_device_count(*model) > 1 &&
  17319. model->n_gpu_layers > (int)model->hparams.n_layer &&
  17320. model->split_mode == LLAMA_SPLIT_MODE_LAYER &&
  17321. params.offload_kqv;
  17322. // pipeline parallelism requires support for async compute and events in all devices
  17323. if (pipeline_parallel) {
  17324. for (auto & backend : ctx->backends) {
  17325. auto dev_type = ggml_backend_dev_type(ggml_backend_get_device(backend.get()));
  17326. if (dev_type == GGML_BACKEND_DEVICE_TYPE_CPU) {
  17327. // ignore CPU backend
  17328. continue;
  17329. }
  17330. auto * dev = ggml_backend_get_device(backend.get());
  17331. ggml_backend_dev_props props;
  17332. ggml_backend_dev_get_props(dev, &props);
  17333. if (!props.caps.async || !props.caps.events) {
  17334. // device does not support async compute or events
  17335. pipeline_parallel = false;
  17336. break;
  17337. }
  17338. }
  17339. }
  17340. ctx->sched.reset(ggml_backend_sched_new(backend_ptrs.data(), backend_buft.data(), backend_ptrs.size(), max_nodes, pipeline_parallel));
  17341. if (pipeline_parallel) {
  17342. LLAMA_LOG_INFO("%s: pipeline parallelism enabled (n_copies=%d)\n", __func__, ggml_backend_sched_get_n_copies(ctx->sched.get()));
  17343. }
  17344. // initialize scheduler with the worst-case graph
  17345. uint32_t n_seqs = 1; // TODO: worst-case number of sequences
  17346. uint32_t n_tokens = std::min(cparams.n_ctx, cparams.n_ubatch);
  17347. 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
  17348. llama_ubatch ubatch_pp = { true, n_tokens, n_tokens / n_seqs, n_seqs, &token, nullptr, nullptr, nullptr, nullptr, nullptr};
  17349. ggml_cgraph * gf_pp = llama_build_graph(*ctx, ubatch_pp, true);
  17350. // reserve pp graph first so that buffers are only allocated once
  17351. ggml_backend_sched_reserve(ctx->sched.get(), gf_pp);
  17352. int n_splits_pp = ggml_backend_sched_get_n_splits(ctx->sched.get());
  17353. int n_nodes_pp = ggml_graph_n_nodes(gf_pp);
  17354. // reserve with tg graph to get the number of splits and nodes
  17355. llama_ubatch ubatch_tg = { true, 1, 1, n_seqs, &token, nullptr, nullptr, nullptr, nullptr, nullptr};
  17356. ggml_cgraph * gf_tg = llama_build_graph(*ctx, ubatch_tg, true);
  17357. ggml_backend_sched_reserve(ctx->sched.get(), gf_tg);
  17358. int n_splits_tg = ggml_backend_sched_get_n_splits(ctx->sched.get());
  17359. int n_nodes_tg = ggml_graph_n_nodes(gf_tg);
  17360. // reserve again with pp graph to avoid ggml-alloc reallocations during inference
  17361. gf_pp = llama_build_graph(*ctx, ubatch_pp, true);
  17362. if (!ggml_backend_sched_reserve(ctx->sched.get(), gf_pp)) {
  17363. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  17364. llama_free(ctx);
  17365. return nullptr;
  17366. }
  17367. for (size_t i = 0; i < backend_ptrs.size(); ++i) {
  17368. ggml_backend_t backend = backend_ptrs[i];
  17369. ggml_backend_buffer_type_t buft = backend_buft[i];
  17370. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched.get(), backend);
  17371. if (size > 1) {
  17372. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  17373. ggml_backend_buft_name(buft),
  17374. size / 1024.0 / 1024.0);
  17375. }
  17376. }
  17377. if (n_nodes_pp == n_nodes_tg) {
  17378. LLAMA_LOG_INFO("%s: graph nodes = %d\n", __func__, n_nodes_pp);
  17379. } else {
  17380. LLAMA_LOG_INFO("%s: graph nodes = %d (with bs=%d), %d (with bs=1)\n", __func__, n_nodes_pp, n_tokens, n_nodes_tg);
  17381. }
  17382. if (n_splits_pp == n_splits_tg) {
  17383. LLAMA_LOG_INFO("%s: graph splits = %d\n", __func__, n_splits_pp);
  17384. } else {
  17385. LLAMA_LOG_INFO("%s: graph splits = %d (with bs=%d), %d (with bs=1)\n", __func__, n_splits_pp, n_tokens, n_splits_tg);
  17386. }
  17387. }
  17388. }
  17389. return ctx;
  17390. }
  17391. void llama_free(struct llama_context * ctx) {
  17392. delete ctx;
  17393. }
  17394. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  17395. return ctx->cparams.n_ctx;
  17396. }
  17397. uint32_t llama_n_batch(const struct llama_context * ctx) {
  17398. return ctx->cparams.n_batch;
  17399. }
  17400. uint32_t llama_n_ubatch(const struct llama_context * ctx) {
  17401. return ctx->cparams.n_ubatch;
  17402. }
  17403. uint32_t llama_n_seq_max(const struct llama_context * ctx) {
  17404. return ctx->kv_self.size;
  17405. }
  17406. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  17407. return model->vocab.type;
  17408. }
  17409. int32_t llama_n_vocab(const struct llama_model * model) {
  17410. return model->hparams.n_vocab;
  17411. }
  17412. int32_t llama_n_ctx_train(const struct llama_model * model) {
  17413. return model->hparams.n_ctx_train;
  17414. }
  17415. int32_t llama_n_embd(const struct llama_model * model) {
  17416. return model->hparams.n_embd;
  17417. }
  17418. int32_t llama_n_layer(const struct llama_model * model) {
  17419. return model->hparams.n_layer;
  17420. }
  17421. int32_t llama_n_head(const struct llama_model * model) {
  17422. return model->hparams.n_head();
  17423. }
  17424. const struct llama_model * llama_get_model(const struct llama_context * ctx) {
  17425. return &ctx->model;
  17426. }
  17427. enum llama_pooling_type llama_pooling_type(const struct llama_context * ctx) {
  17428. return ctx->cparams.pooling_type;
  17429. }
  17430. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  17431. switch (model->arch) {
  17432. // these models do not use RoPE
  17433. case LLM_ARCH_GPT2:
  17434. case LLM_ARCH_GPTJ:
  17435. case LLM_ARCH_MPT:
  17436. case LLM_ARCH_REFACT:
  17437. case LLM_ARCH_BLOOM:
  17438. case LLM_ARCH_MAMBA:
  17439. case LLM_ARCH_JINA_BERT_V2:
  17440. case LLM_ARCH_T5:
  17441. case LLM_ARCH_T5ENCODER:
  17442. case LLM_ARCH_JAIS:
  17443. case LLM_ARCH_RWKV6:
  17444. return LLAMA_ROPE_TYPE_NONE;
  17445. // use what we call a normal RoPE, operating on pairs of consecutive head values
  17446. case LLM_ARCH_LLAMA:
  17447. case LLM_ARCH_MLLAMA:
  17448. case LLM_ARCH_BAICHUAN:
  17449. case LLM_ARCH_STARCODER:
  17450. case LLM_ARCH_PLAMO:
  17451. case LLM_ARCH_ORION:
  17452. case LLM_ARCH_INTERNLM2:
  17453. case LLM_ARCH_MINICPM:
  17454. case LLM_ARCH_XVERSE:
  17455. case LLM_ARCH_COMMAND_R:
  17456. case LLM_ARCH_OLMO:
  17457. case LLM_ARCH_ARCTIC:
  17458. case LLM_ARCH_DEEPSEEK2:
  17459. case LLM_ARCH_CHATGLM:
  17460. case LLM_ARCH_GRANITE:
  17461. case LLM_ARCH_GRANITE_MOE:
  17462. case LLM_ARCH_CHAMELEON:
  17463. case LLM_ARCH_SOLAR:
  17464. return LLAMA_ROPE_TYPE_NORM;
  17465. // the pairs of head values are offset by n_rot/2
  17466. case LLM_ARCH_FALCON:
  17467. case LLM_ARCH_GROK:
  17468. case LLM_ARCH_DBRX:
  17469. case LLM_ARCH_BERT:
  17470. case LLM_ARCH_NOMIC_BERT:
  17471. case LLM_ARCH_STABLELM:
  17472. case LLM_ARCH_BITNET:
  17473. case LLM_ARCH_QWEN:
  17474. case LLM_ARCH_QWEN2:
  17475. case LLM_ARCH_QWEN2MOE:
  17476. case LLM_ARCH_OLMO2:
  17477. case LLM_ARCH_OLMOE:
  17478. case LLM_ARCH_PHI2:
  17479. case LLM_ARCH_PHI3:
  17480. case LLM_ARCH_GEMMA:
  17481. case LLM_ARCH_GEMMA2:
  17482. case LLM_ARCH_STARCODER2:
  17483. case LLM_ARCH_OPENELM:
  17484. case LLM_ARCH_GPTNEOX:
  17485. case LLM_ARCH_CODESHELL:
  17486. case LLM_ARCH_NEMOTRON:
  17487. case LLM_ARCH_EXAONE:
  17488. case LLM_ARCH_MINICPM3:
  17489. return LLAMA_ROPE_TYPE_NEOX;
  17490. case LLM_ARCH_QWEN2VL:
  17491. return LLAMA_ROPE_TYPE_MROPE;
  17492. // all model arches should be listed explicitly here
  17493. case LLM_ARCH_UNKNOWN:
  17494. GGML_ABORT("unknown architecture");
  17495. }
  17496. return LLAMA_ROPE_TYPE_NONE;
  17497. }
  17498. float llama_rope_freq_scale_train(const struct llama_model * model) {
  17499. return model->hparams.rope_freq_scale_train;
  17500. }
  17501. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  17502. const auto & it = model->gguf_kv.find(key);
  17503. if (it == model->gguf_kv.end()) {
  17504. if (buf_size > 0) {
  17505. buf[0] = '\0';
  17506. }
  17507. return -1;
  17508. }
  17509. return snprintf(buf, buf_size, "%s", it->second.c_str());
  17510. }
  17511. int32_t llama_model_meta_count(const struct llama_model * model) {
  17512. return (int)model->gguf_kv.size();
  17513. }
  17514. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  17515. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  17516. if (buf_size > 0) {
  17517. buf[0] = '\0';
  17518. }
  17519. return -1;
  17520. }
  17521. auto it = model->gguf_kv.begin();
  17522. std::advance(it, i);
  17523. return snprintf(buf, buf_size, "%s", it->first.c_str());
  17524. }
  17525. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  17526. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  17527. if (buf_size > 0) {
  17528. buf[0] = '\0';
  17529. }
  17530. return -1;
  17531. }
  17532. auto it = model->gguf_kv.begin();
  17533. std::advance(it, i);
  17534. return snprintf(buf, buf_size, "%s", it->second.c_str());
  17535. }
  17536. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  17537. return snprintf(buf, buf_size, "%s %s %s",
  17538. llama_model_arch_name(model->arch),
  17539. llama_model_type_name(model->type),
  17540. llama_model_ftype_name(model->ftype).c_str());
  17541. }
  17542. uint64_t llama_model_size(const struct llama_model * model) {
  17543. return model->n_bytes;
  17544. }
  17545. uint64_t llama_model_n_params(const struct llama_model * model) {
  17546. return model->n_elements;
  17547. }
  17548. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  17549. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  17550. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  17551. return it.first == name;
  17552. });
  17553. if (it == model->tensors_by_name.end()) {
  17554. return nullptr;
  17555. }
  17556. return it->second;
  17557. }
  17558. bool llama_model_has_encoder(const struct llama_model * model) {
  17559. switch (model->arch) {
  17560. case LLM_ARCH_T5: return true;
  17561. case LLM_ARCH_T5ENCODER: return true;
  17562. default: return false;
  17563. }
  17564. }
  17565. bool llama_model_has_decoder(const struct llama_model * model) {
  17566. switch (model->arch) {
  17567. case LLM_ARCH_T5ENCODER: return false;
  17568. default: return true;
  17569. }
  17570. }
  17571. llama_token llama_model_decoder_start_token(const struct llama_model * model) {
  17572. return model->hparams.dec_start_token_id;
  17573. }
  17574. bool llama_model_is_recurrent(const struct llama_model * model) {
  17575. switch (model->arch) {
  17576. case LLM_ARCH_MAMBA: return true;
  17577. case LLM_ARCH_RWKV6: return true;
  17578. default: return false;
  17579. }
  17580. }
  17581. uint32_t llama_model_quantize(
  17582. const char * fname_inp,
  17583. const char * fname_out,
  17584. const llama_model_quantize_params * params) {
  17585. try {
  17586. llama_model_quantize_internal(fname_inp, fname_out, params);
  17587. return 0;
  17588. } catch (const std::exception & err) {
  17589. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  17590. return 1;
  17591. }
  17592. }
  17593. struct llama_lora_adapter * llama_lora_adapter_init(struct llama_model * model, const char * path_lora) {
  17594. try {
  17595. struct llama_lora_adapter * adapter = new llama_lora_adapter(model);
  17596. llama_lora_adapter_init_internal(model, path_lora, *adapter);
  17597. return adapter;
  17598. } catch (const std::exception & err) {
  17599. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  17600. return nullptr;
  17601. }
  17602. }
  17603. static bool llama_control_vector_init(struct llama_control_vector & cvec, const llama_model & model) {
  17604. GGML_ASSERT(cvec.tensors.empty());
  17605. GGML_ASSERT(cvec.ctxs.empty());
  17606. GGML_ASSERT(cvec.bufs.empty());
  17607. // create a context for each buffer type
  17608. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  17609. auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
  17610. auto it = ctx_map.find(buft);
  17611. if (it == ctx_map.end()) {
  17612. struct ggml_init_params params = {
  17613. /*.mem_size =*/ model.hparams.n_layer*ggml_tensor_overhead(),
  17614. /*.mem_buffer =*/ NULL,
  17615. /*.no_alloc =*/ true,
  17616. };
  17617. ggml_context * ctx = ggml_init(params);
  17618. if (!ctx) {
  17619. return nullptr;
  17620. }
  17621. ctx_map[buft] = ctx;
  17622. cvec.ctxs.emplace_back(ctx);
  17623. return ctx;
  17624. }
  17625. return it->second;
  17626. };
  17627. // make tensors
  17628. cvec.tensors.reserve(model.hparams.n_layer);
  17629. cvec.tensors.push_back(nullptr); // there's never a tensor for layer 0
  17630. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  17631. ggml_backend_buffer_type_t buft = select_buft(*model.dev_layer.at(il).buft_list,
  17632. [&](ggml_context * ctx) {
  17633. ggml_tensor * cur = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_embd);
  17634. ggml_tensor * layer_dir = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_embd);
  17635. return ggml_add(ctx, cur, layer_dir);
  17636. });
  17637. ggml_context * ctx = ctx_for_buft(buft);
  17638. if (!ctx) {
  17639. LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
  17640. return false;
  17641. }
  17642. ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_embd);
  17643. cvec.tensors.push_back(tensor);
  17644. }
  17645. // allocate tensors / buffers and zero
  17646. cvec.bufs.reserve(ctx_map.size());
  17647. for (auto it : ctx_map) {
  17648. ggml_backend_buffer_type_t buft = it.first;
  17649. ggml_context * ctx = it.second;
  17650. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  17651. if (!buf) {
  17652. LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
  17653. return false;
  17654. }
  17655. ggml_backend_buffer_clear(buf, 0);
  17656. cvec.bufs.emplace_back(buf);
  17657. }
  17658. return true;
  17659. }
  17660. 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) {
  17661. const llama_model & model = lctx->model;
  17662. llama_control_vector & cvec = lctx->cvec;
  17663. if (data == nullptr) {
  17664. // disable the current control vector (but leave allocated for later)
  17665. cvec.layer_start = -1;
  17666. cvec.layer_end = -1;
  17667. return 0;
  17668. }
  17669. if (n_embd != (int) model.hparams.n_embd) {
  17670. LLAMA_LOG_ERROR("%s: control vector n_embd does not match model\n", __func__);
  17671. return 1;
  17672. }
  17673. if (cvec.tensors.empty()) {
  17674. if (!llama_control_vector_init(cvec, model)) {
  17675. return 1;
  17676. }
  17677. }
  17678. cvec.layer_start = il_start;
  17679. cvec.layer_end = il_end;
  17680. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  17681. assert(cvec.tensors[il] != nullptr);
  17682. const size_t off = n_embd * (il - 1); // buffer doesn't have data for layer 0, since it's never present
  17683. if (off + n_embd <= len) {
  17684. ggml_backend_tensor_set(cvec.tensors[il], data + off, 0, n_embd * ggml_element_size(cvec.tensors[il]));
  17685. }
  17686. }
  17687. return 0;
  17688. }
  17689. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_seq_max) {
  17690. struct llama_kv_cache_view result = {
  17691. /*.n_cells = */ 0,
  17692. /*.n_seq_max = */ n_seq_max,
  17693. /*.token_count = */ 0,
  17694. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  17695. /*.max_contiguous = */ 0,
  17696. /*.max_contiguous_idx = */ -1,
  17697. /*.cells = */ nullptr,
  17698. /*.cells_sequences = */ nullptr,
  17699. };
  17700. return result;
  17701. }
  17702. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  17703. if (view->cells != nullptr) {
  17704. free(view->cells);
  17705. view->cells = nullptr;
  17706. }
  17707. if (view->cells_sequences != nullptr) {
  17708. free(view->cells_sequences);
  17709. view->cells_sequences = nullptr;
  17710. }
  17711. }
  17712. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  17713. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  17714. view->n_cells = int32_t(ctx->kv_self.size);
  17715. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  17716. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  17717. view->cells = (struct llama_kv_cache_view_cell *)p;
  17718. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_seq_max * view->n_cells);
  17719. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  17720. view->cells_sequences = (llama_seq_id *)p;
  17721. }
  17722. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  17723. llama_kv_cache_view_cell * c_curr = view->cells;
  17724. llama_seq_id * cs_curr = view->cells_sequences;
  17725. int32_t used_cells = 0;
  17726. int32_t token_count = 0;
  17727. int32_t curr_contig_idx = -1;
  17728. uint32_t max_contig = 0;
  17729. int32_t max_contig_idx = -1;
  17730. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_seq_max) {
  17731. const size_t curr_size = kv_cells[i].seq_id.size();
  17732. token_count += curr_size;
  17733. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  17734. if (curr_size > 0) {
  17735. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  17736. max_contig = i - curr_contig_idx;
  17737. max_contig_idx = curr_contig_idx;
  17738. }
  17739. curr_contig_idx = -1;
  17740. } else if (curr_contig_idx < 0) {
  17741. curr_contig_idx = i;
  17742. }
  17743. int seq_idx = 0;
  17744. for (const llama_seq_id it : kv_cells[i].seq_id) {
  17745. if (seq_idx >= view->n_seq_max) {
  17746. break;
  17747. }
  17748. cs_curr[seq_idx] = it;
  17749. seq_idx++;
  17750. }
  17751. if (seq_idx != 0) {
  17752. used_cells++;
  17753. }
  17754. for (; seq_idx < view->n_seq_max; seq_idx++) {
  17755. cs_curr[seq_idx] = -1;
  17756. }
  17757. }
  17758. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  17759. max_contig_idx = curr_contig_idx;
  17760. max_contig = kv_cells.size() - curr_contig_idx;
  17761. }
  17762. view->max_contiguous = max_contig;
  17763. view->max_contiguous_idx = max_contig_idx;
  17764. view->token_count = token_count;
  17765. view->used_cells = used_cells;
  17766. if (uint32_t(used_cells) != ctx->kv_self.used) {
  17767. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  17768. __func__, ctx->kv_self.used, used_cells);
  17769. }
  17770. }
  17771. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  17772. int result = 0;
  17773. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  17774. result += ctx->kv_self.cells[i].seq_id.size();
  17775. }
  17776. return result;
  17777. }
  17778. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  17779. return ctx->kv_self.used;
  17780. }
  17781. void llama_kv_cache_clear(struct llama_context * ctx) {
  17782. llama_kv_cache_clear(ctx->kv_self);
  17783. }
  17784. bool llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  17785. return llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  17786. }
  17787. 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) {
  17788. if (seq_id_src == seq_id_dst) {
  17789. return;
  17790. }
  17791. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  17792. }
  17793. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  17794. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  17795. }
  17796. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  17797. if (delta == 0) {
  17798. return;
  17799. }
  17800. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  17801. }
  17802. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  17803. if (d == 1) {
  17804. return;
  17805. }
  17806. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  17807. }
  17808. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  17809. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  17810. }
  17811. void llama_kv_cache_defrag(struct llama_context * ctx) {
  17812. llama_kv_cache_defrag(ctx->kv_self);
  17813. }
  17814. void llama_kv_cache_update(struct llama_context * ctx) {
  17815. llama_kv_cache_update_internal(*ctx);
  17816. }
  17817. bool llama_kv_cache_can_shift(struct llama_context * ctx) {
  17818. return !ctx->kv_self.recurrent && ctx->model.arch != LLM_ARCH_DEEPSEEK2; // not supported due to MLA
  17819. }
  17820. // deprecated
  17821. size_t llama_get_state_size(struct llama_context * ctx) {
  17822. return llama_state_get_size(ctx);
  17823. }
  17824. // deprecated
  17825. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  17826. return llama_state_get_data(ctx, dst, -1);
  17827. }
  17828. // deprecated
  17829. size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
  17830. return llama_state_set_data(ctx, src, -1);
  17831. }
  17832. // deprecated
  17833. 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) {
  17834. return llama_state_load_file(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  17835. }
  17836. // deprecated
  17837. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  17838. return llama_state_save_file(ctx, path_session, tokens, n_token_count);
  17839. }
  17840. // TODO: replace all non-fatal assertions with returned errors or exceptions
  17841. struct llama_data_write {
  17842. virtual void write(const void * src, size_t size) = 0;
  17843. virtual void write_tensor_data(const struct ggml_tensor * tensor, size_t offset, size_t size) = 0;
  17844. virtual size_t get_size_written() = 0;
  17845. virtual ~llama_data_write() = default;
  17846. void write_string(const std::string & str) {
  17847. uint32_t str_size = str.size();
  17848. write(&str_size, sizeof(str_size));
  17849. write(str.data(), str_size);
  17850. }
  17851. void write_model_info(const struct llama_context * ctx) {
  17852. std::string arch_str = LLM_ARCH_NAMES.at(ctx->model.arch);
  17853. write_string(arch_str);
  17854. // TODO: add more model-specific info which should prevent loading the session file if not identical
  17855. }
  17856. //void write_rng(const std::mt19937 & rng) {
  17857. // std::ostringstream rng_ss;
  17858. // rng_ss << rng;
  17859. // const std::string & rng_str = rng_ss.str();
  17860. // write_string(rng_str);
  17861. //}
  17862. void write_output_ids(struct llama_context * ctx) {
  17863. llama_output_reorder(ctx);
  17864. const uint32_t n_outputs = ctx->n_outputs;
  17865. std::vector<int32_t> output_pos;
  17866. const size_t n_batch = ctx->cparams.n_batch;
  17867. const auto & output_ids = ctx->output_ids;
  17868. GGML_ASSERT(n_outputs <= ctx->output_size);
  17869. output_pos.resize(n_outputs);
  17870. // build a more compact representation of the output ids
  17871. for (size_t i = 0; i < n_batch; ++i) {
  17872. // map an output id to a position in the batch
  17873. int32_t pos = output_ids[i];
  17874. if (pos >= 0) {
  17875. GGML_ASSERT((uint32_t) pos < n_outputs);
  17876. output_pos[pos] = i;
  17877. }
  17878. }
  17879. write(&n_outputs, sizeof(n_outputs));
  17880. if (n_outputs) {
  17881. write(output_pos.data(), n_outputs * sizeof(int32_t));
  17882. }
  17883. }
  17884. void write_logits(const struct llama_context * ctx) {
  17885. const uint64_t logits_size = std::min((uint64_t) ctx->logits_size, (uint64_t) ctx->n_outputs * ctx->model.hparams.n_vocab);
  17886. write(&logits_size, sizeof(logits_size));
  17887. if (logits_size) {
  17888. write(ctx->logits, logits_size * sizeof(float));
  17889. }
  17890. }
  17891. void write_embeddings(const struct llama_context * ctx) {
  17892. const uint64_t embeddings_size = std::min((uint64_t) ctx->embd_size, (uint64_t) ctx->n_outputs * ctx->model.hparams.n_embd);
  17893. write(&embeddings_size, sizeof(embeddings_size));
  17894. if (embeddings_size) {
  17895. write(ctx->embd, embeddings_size * sizeof(float));
  17896. }
  17897. }
  17898. 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) {
  17899. for (const auto & range : cell_ranges) {
  17900. for (uint32_t i = range.first; i < range.second; ++i) {
  17901. const auto & cell = kv_self.cells[i];
  17902. const llama_pos pos = cell.pos;
  17903. const uint32_t n_seq_id = seq_id == -1 ? cell.seq_id.size() : 0;
  17904. write(&pos, sizeof(pos));
  17905. write(&n_seq_id, sizeof(n_seq_id));
  17906. if (n_seq_id) {
  17907. for (auto seq_id : cell.seq_id) {
  17908. write(&seq_id, sizeof(seq_id));
  17909. }
  17910. }
  17911. }
  17912. }
  17913. }
  17914. void write_kv_cache_data(const struct llama_context * ctx, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges) {
  17915. const struct llama_kv_cache & kv_self = ctx->kv_self;
  17916. const struct llama_hparams & hparams = ctx->model.hparams;
  17917. const uint32_t v_trans = kv_self.v_trans ? 1 : 0;
  17918. const uint32_t n_layer = hparams.n_layer;
  17919. write(&v_trans, sizeof(v_trans));
  17920. write(&n_layer, sizeof(n_layer));
  17921. std::vector<uint8_t> tmp_buf;
  17922. // Iterate and write all the keys first, each row is a cell
  17923. // Get whole range at a time
  17924. for (uint32_t il = 0; il < n_layer; ++il) {
  17925. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  17926. // Write key type
  17927. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  17928. write(&k_type_i, sizeof(k_type_i));
  17929. // Write row size of key
  17930. const uint64_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  17931. write(&k_size_row, sizeof(k_size_row));
  17932. // Read each range of cells of k_size length each into tmp_buf and write out
  17933. for (const auto & range : cell_ranges) {
  17934. const size_t range_size = range.second - range.first;
  17935. const size_t buf_size = range_size * k_size_row;
  17936. write_tensor_data(kv_self.k_l[il], range.first * k_size_row, buf_size);
  17937. }
  17938. }
  17939. if (!kv_self.v_trans) {
  17940. for (uint32_t il = 0; il < n_layer; ++il) {
  17941. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  17942. // Write value type
  17943. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  17944. write(&v_type_i, sizeof(v_type_i));
  17945. // Write row size of value
  17946. const uint64_t v_size_row = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa);
  17947. write(&v_size_row, sizeof(v_size_row));
  17948. // Read each range of cells of v_size length each into tmp_buf and write out
  17949. for (const auto & range : cell_ranges) {
  17950. const size_t range_size = range.second - range.first;
  17951. const size_t buf_size = range_size * v_size_row;
  17952. write_tensor_data(kv_self.v_l[il], range.first * v_size_row, buf_size);
  17953. }
  17954. }
  17955. } else {
  17956. // When v is transposed, we also need the element size and get the element ranges from each row
  17957. const uint32_t kv_size = kv_self.size;
  17958. for (uint32_t il = 0; il < n_layer; ++il) {
  17959. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  17960. // Write value type
  17961. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  17962. write(&v_type_i, sizeof(v_type_i));
  17963. // Write element size
  17964. const uint32_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  17965. write(&v_size_el, sizeof(v_size_el));
  17966. // Write GQA embedding size
  17967. write(&n_embd_v_gqa, sizeof(n_embd_v_gqa));
  17968. // For each row, we get the element values of each cell
  17969. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  17970. // Read each range of cells of v_size_el length each into tmp_buf and write out
  17971. for (const auto & range : cell_ranges) {
  17972. const size_t range_size = range.second - range.first;
  17973. const size_t src_offset = (range.first + j * kv_size) * v_size_el;
  17974. const size_t buf_size = range_size * v_size_el;
  17975. write_tensor_data(kv_self.v_l[il], src_offset, buf_size);
  17976. }
  17977. }
  17978. }
  17979. }
  17980. }
  17981. void write_kv_cache(const struct llama_context * ctx, llama_seq_id seq_id = -1) {
  17982. const struct llama_kv_cache & kv_self = ctx->kv_self;
  17983. std::vector<std::pair<uint32_t, uint32_t>> cell_ranges; // ranges, from inclusive, to exclusive
  17984. uint32_t cell_count = 0;
  17985. // Count the number of cells with the specified seq_id
  17986. // Find all the ranges of cells with this seq id (or all, when -1)
  17987. uint32_t cell_range_begin = kv_self.size;
  17988. for (uint32_t i = 0; i < kv_self.size; ++i) {
  17989. const auto & cell = kv_self.cells[i];
  17990. if ((seq_id == -1 && !cell.is_empty()) || cell.has_seq_id(seq_id)) {
  17991. ++cell_count;
  17992. if (cell_range_begin == kv_self.size) {
  17993. cell_range_begin = i;
  17994. }
  17995. } else {
  17996. if (cell_range_begin != kv_self.size) {
  17997. cell_ranges.emplace_back(cell_range_begin, i);
  17998. cell_range_begin = kv_self.size;
  17999. }
  18000. }
  18001. }
  18002. if (cell_range_begin != kv_self.size) {
  18003. cell_ranges.emplace_back(cell_range_begin, kv_self.size);
  18004. }
  18005. // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
  18006. uint32_t cell_count_check = 0;
  18007. for (const auto & range : cell_ranges) {
  18008. cell_count_check += range.second - range.first;
  18009. }
  18010. GGML_ASSERT(cell_count == cell_count_check);
  18011. write(&cell_count, sizeof(cell_count));
  18012. write_kv_cache_meta(kv_self, cell_ranges, seq_id);
  18013. write_kv_cache_data(ctx, cell_ranges);
  18014. }
  18015. };
  18016. struct llama_data_read {
  18017. virtual const uint8_t * read(size_t size) = 0;
  18018. virtual void read_to(void * dst, size_t size) = 0;
  18019. virtual size_t get_size_read() = 0;
  18020. virtual ~llama_data_read() = default;
  18021. void read_string(std::string & str) {
  18022. uint32_t str_size;
  18023. read_to(&str_size, sizeof(str_size));
  18024. str.assign((const char *) read(str_size), str_size);
  18025. }
  18026. // validate model information
  18027. void read_model_info(const struct llama_context * ctx) {
  18028. std::string cur_arch_str = LLM_ARCH_NAMES.at(ctx->model.arch);
  18029. std::string arch_str;
  18030. read_string(arch_str);
  18031. if (cur_arch_str != arch_str) {
  18032. throw std::runtime_error(format("wrong model arch: '%s' instead of '%s'", arch_str.c_str(), cur_arch_str.c_str()));
  18033. }
  18034. // TODO: add more info which needs to be identical but which is not verified otherwise
  18035. }
  18036. //void read_rng(std::mt19937 & rng) {
  18037. // std::string rng_str;
  18038. // read_string(rng_str);
  18039. // std::istringstream rng_ss(rng_str);
  18040. // rng_ss >> rng;
  18041. // if (rng_ss.fail()) {
  18042. // throw std::runtime_error("failed to load RNG state");
  18043. // }
  18044. //}
  18045. void read_output_ids(struct llama_context * ctx) {
  18046. std::vector<int32_t> output_pos;
  18047. uint32_t n_outputs;
  18048. read_to(&n_outputs, sizeof(n_outputs));
  18049. if (n_outputs > llama_output_reserve(*ctx, n_outputs)) {
  18050. throw std::runtime_error("could not reserve outputs");
  18051. }
  18052. if (n_outputs) {
  18053. output_pos.resize(n_outputs);
  18054. read_to(output_pos.data(), n_outputs * sizeof(int32_t));
  18055. for (int32_t i = 0; i < (int32_t) output_pos.size(); ++i) {
  18056. int32_t id = output_pos[i];
  18057. if ((uint32_t) id >= ctx->cparams.n_batch) {
  18058. throw std::runtime_error(format("invalid output id, %d does not fit in batch size of %u", id, ctx->cparams.n_batch));
  18059. }
  18060. ctx->output_ids[id] = i;
  18061. }
  18062. ctx->n_outputs = n_outputs;
  18063. }
  18064. }
  18065. void read_logits(struct llama_context * ctx) {
  18066. uint64_t logits_size;
  18067. read_to(&logits_size, sizeof(logits_size));
  18068. if (ctx->logits_size < logits_size) {
  18069. throw std::runtime_error("logits buffer too small");
  18070. }
  18071. if (logits_size) {
  18072. read_to(ctx->logits, logits_size * sizeof(float));
  18073. }
  18074. }
  18075. void read_embeddings(struct llama_context * ctx) {
  18076. uint64_t embeddings_size;
  18077. read_to(&embeddings_size, sizeof(embeddings_size));
  18078. if (ctx->embd_size < embeddings_size) {
  18079. throw std::runtime_error("embeddings buffer too small");
  18080. }
  18081. if (embeddings_size) {
  18082. read_to(ctx->embd, embeddings_size * sizeof(float));
  18083. }
  18084. }
  18085. bool read_kv_cache_meta(struct llama_context * ctx, uint32_t cell_count, llama_seq_id dest_seq_id = -1) {
  18086. struct llama_kv_cache & kv_self = ctx->kv_self;
  18087. if (dest_seq_id != -1) {
  18088. // single sequence
  18089. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  18090. llama_ubatch batch = ctx->sbatch.reserve_ubatch(cell_count, /* has_embd */ false);
  18091. batch.n_tokens = cell_count;
  18092. batch.n_seq_tokens = cell_count;
  18093. batch.n_seqs = 1;
  18094. for (uint32_t i = 0; i < cell_count; ++i) {
  18095. llama_pos pos;
  18096. uint32_t n_seq_id;
  18097. read_to(&pos, sizeof(pos));
  18098. read_to(&n_seq_id, sizeof(n_seq_id));
  18099. if (n_seq_id != 0) {
  18100. LLAMA_LOG_ERROR("%s: invalid seq_id-agnostic kv cell\n", __func__);
  18101. return false;
  18102. }
  18103. batch.pos[i] = pos;
  18104. }
  18105. batch.n_seq_id[0] = 1;
  18106. batch.seq_id[0] = &dest_seq_id;
  18107. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  18108. LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
  18109. return false;
  18110. }
  18111. // 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)
  18112. // Assume that this is one contiguous block of cells
  18113. GGML_ASSERT(kv_self.head + cell_count <= kv_self.size);
  18114. GGML_ASSERT(kv_self.cells[kv_self.head].pos == batch.pos[0]);
  18115. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].pos == batch.pos[cell_count - 1]);
  18116. GGML_ASSERT(kv_self.cells[kv_self.head].has_seq_id(dest_seq_id));
  18117. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].has_seq_id(dest_seq_id));
  18118. } else {
  18119. // whole KV cache restore
  18120. if (cell_count > kv_self.size) {
  18121. LLAMA_LOG_ERROR("%s: not enough cells in kv cache\n", __func__);
  18122. return false;
  18123. }
  18124. llama_kv_cache_clear(kv_self);
  18125. for (uint32_t i = 0; i < cell_count; ++i) {
  18126. llama_kv_cell & cell = kv_self.cells[i];
  18127. llama_pos pos;
  18128. uint32_t n_seq_id;
  18129. read_to(&pos, sizeof(pos));
  18130. read_to(&n_seq_id, sizeof(n_seq_id));
  18131. cell.pos = pos;
  18132. for (uint32_t j = 0; j < n_seq_id; ++j) {
  18133. llama_seq_id seq_id;
  18134. read_to(&seq_id, sizeof(seq_id));
  18135. if (seq_id < 0 || (uint32_t) seq_id >= llama_n_seq_max(ctx)) {
  18136. LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, %u)\n", __func__, seq_id, llama_n_seq_max(ctx));
  18137. return false;
  18138. }
  18139. cell.seq_id.insert(seq_id);
  18140. if (kv_self.recurrent) {
  18141. int32_t & tail = kv_self.cells[seq_id].tail;
  18142. if (tail != -1) {
  18143. LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tail);
  18144. return false;
  18145. }
  18146. tail = i;
  18147. }
  18148. }
  18149. }
  18150. kv_self.head = 0;
  18151. kv_self.used = cell_count;
  18152. }
  18153. if (kv_self.recurrent) {
  18154. for (uint32_t i = 0; i < cell_count; ++i) {
  18155. uint32_t cell_id = kv_self.head + i;
  18156. // make sure the recurrent states will keep their restored state
  18157. kv_self.cells[cell_id].src = cell_id;
  18158. }
  18159. }
  18160. return true;
  18161. }
  18162. bool read_kv_cache_data(struct llama_context * ctx, uint32_t cell_count) {
  18163. const struct llama_hparams & hparams = ctx->model.hparams;
  18164. struct llama_kv_cache & kv_self = ctx->kv_self;
  18165. uint32_t v_trans;
  18166. uint32_t n_layer;
  18167. read_to(&v_trans, sizeof(v_trans));
  18168. read_to(&n_layer, sizeof(n_layer));
  18169. if (n_layer != hparams.n_layer) {
  18170. LLAMA_LOG_ERROR("%s: mismatched layer count (%u instead of %u)\n", __func__, n_layer, hparams.n_layer);
  18171. return false;
  18172. }
  18173. if (cell_count > kv_self.size) {
  18174. LLAMA_LOG_ERROR("%s: not enough cells in kv cache to restore state (%u > %u)\n", __func__, cell_count, kv_self.size);
  18175. return false;
  18176. }
  18177. if (kv_self.v_trans != (bool) v_trans) {
  18178. LLAMA_LOG_ERROR("%s: incompatible V transposition\n", __func__);
  18179. return false;
  18180. }
  18181. // For each layer, read the keys for each cell, one row is one cell, read as one contiguous block
  18182. for (uint32_t il = 0; il < n_layer; ++il) {
  18183. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  18184. // Read type of key
  18185. int32_t k_type_i_ref;
  18186. read_to(&k_type_i_ref, sizeof(k_type_i_ref));
  18187. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  18188. if (k_type_i != k_type_i_ref) {
  18189. LLAMA_LOG_ERROR("%s: mismatched key type (%d != %d, layer %d)\n", __func__, k_type_i, k_type_i_ref, il);
  18190. return false;
  18191. }
  18192. // Read row size of key
  18193. uint64_t k_size_row_ref;
  18194. read_to(&k_size_row_ref, sizeof(k_size_row_ref));
  18195. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  18196. if (k_size_row != k_size_row_ref) {
  18197. LLAMA_LOG_ERROR("%s: mismatched key row size (%zu != %zu, layer %d)\n", __func__, k_size_row, (size_t) k_size_row_ref, il);
  18198. return false;
  18199. }
  18200. if (cell_count) {
  18201. // Read and set the keys for the whole cell range
  18202. 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);
  18203. }
  18204. }
  18205. if (!kv_self.v_trans) {
  18206. for (uint32_t il = 0; il < n_layer; ++il) {
  18207. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  18208. // Read type of value
  18209. int32_t v_type_i_ref;
  18210. read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  18211. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  18212. if (v_type_i != v_type_i_ref) {
  18213. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  18214. return false;
  18215. }
  18216. // Read row size of value
  18217. uint64_t v_size_row_ref;
  18218. read_to(&v_size_row_ref, sizeof(v_size_row_ref));
  18219. const size_t v_size_row = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa);
  18220. if (v_size_row != v_size_row_ref) {
  18221. LLAMA_LOG_ERROR("%s: mismatched value row size (%zu != %zu, layer %d)\n", __func__, v_size_row, (size_t) v_size_row_ref, il);
  18222. return false;
  18223. }
  18224. if (cell_count) {
  18225. // Read and set the values for the whole cell range
  18226. 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);
  18227. }
  18228. }
  18229. } else {
  18230. // For each layer, read the values for each cell (transposed)
  18231. for (uint32_t il = 0; il < n_layer; ++il) {
  18232. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  18233. // Read type of value
  18234. int32_t v_type_i_ref;
  18235. read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  18236. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  18237. if (v_type_i != v_type_i_ref) {
  18238. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  18239. return false;
  18240. }
  18241. // Read element size of value
  18242. uint32_t v_size_el_ref;
  18243. read_to(&v_size_el_ref, sizeof(v_size_el_ref));
  18244. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  18245. if (v_size_el != v_size_el_ref) {
  18246. LLAMA_LOG_ERROR("%s: mismatched value element size (%zu != %zu, layer %d)\n", __func__, v_size_el, (size_t) v_size_el_ref, il);
  18247. return false;
  18248. }
  18249. // Read GQA embedding size
  18250. uint32_t n_embd_v_gqa_ref;
  18251. read_to(&n_embd_v_gqa_ref, sizeof(n_embd_v_gqa_ref));
  18252. if (n_embd_v_gqa != n_embd_v_gqa_ref) {
  18253. LLAMA_LOG_ERROR("%s: mismatched GQA embedding size (%u != %u, layer %d)\n", __func__, n_embd_v_gqa, n_embd_v_gqa_ref, il);
  18254. return false;
  18255. }
  18256. if (cell_count) {
  18257. // For each row in the transposed matrix, read the values for the whole cell range
  18258. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  18259. const size_t dst_offset = (kv_self.head + j * kv_self.size) * v_size_el;
  18260. ggml_backend_tensor_set(kv_self.v_l[il], read(cell_count * v_size_el), dst_offset, cell_count * v_size_el);
  18261. }
  18262. }
  18263. }
  18264. }
  18265. return true;
  18266. }
  18267. void read_kv_cache(struct llama_context * ctx, llama_seq_id seq_id = -1) {
  18268. uint32_t cell_count;
  18269. read_to(&cell_count, sizeof(cell_count));
  18270. bool res = read_kv_cache_meta(ctx, cell_count, seq_id) && read_kv_cache_data(ctx, cell_count);
  18271. if (!res) {
  18272. if (seq_id == -1) {
  18273. llama_kv_cache_clear(ctx);
  18274. } else {
  18275. llama_kv_cache_seq_rm(ctx, seq_id, -1, -1);
  18276. }
  18277. throw std::runtime_error("failed to restore kv cache");
  18278. }
  18279. }
  18280. };
  18281. struct llama_data_write_dummy : llama_data_write {
  18282. size_t size_written = 0;
  18283. llama_data_write_dummy() {}
  18284. void write(const void * /* src */, size_t size) override {
  18285. size_written += size;
  18286. }
  18287. void write_tensor_data(const struct ggml_tensor * /* tensor */, size_t /* offset */, size_t size) override {
  18288. size_written += size;
  18289. }
  18290. size_t get_size_written() override {
  18291. return size_written;
  18292. }
  18293. };
  18294. struct llama_data_write_buffer : llama_data_write {
  18295. uint8_t * ptr;
  18296. size_t buf_size = 0;
  18297. size_t size_written = 0;
  18298. llama_data_write_buffer(uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
  18299. void write(const void * src, size_t size) override {
  18300. if (size > buf_size) {
  18301. throw std::runtime_error("unexpectedly reached end of buffer");
  18302. }
  18303. memcpy(ptr, src, size);
  18304. ptr += size;
  18305. size_written += size;
  18306. buf_size -= size;
  18307. }
  18308. void write_tensor_data(const struct ggml_tensor * tensor, size_t offset, size_t size) override {
  18309. if (size > buf_size) {
  18310. throw std::runtime_error("unexpectedly reached end of buffer");
  18311. }
  18312. ggml_backend_tensor_get(tensor, ptr, offset, size);
  18313. ptr += size;
  18314. size_written += size;
  18315. buf_size -= size;
  18316. }
  18317. size_t get_size_written() override {
  18318. return size_written;
  18319. }
  18320. };
  18321. struct llama_data_read_buffer : llama_data_read {
  18322. const uint8_t * ptr;
  18323. size_t buf_size = 0;
  18324. size_t size_read = 0;
  18325. llama_data_read_buffer(const uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
  18326. const uint8_t * read(size_t size) override {
  18327. const uint8_t * base_ptr = ptr;
  18328. if (size > buf_size) {
  18329. throw std::runtime_error("unexpectedly reached end of buffer");
  18330. }
  18331. ptr += size;
  18332. size_read += size;
  18333. buf_size -= size;
  18334. return base_ptr;
  18335. }
  18336. void read_to(void * dst, size_t size) override {
  18337. memcpy(dst, read(size), size);
  18338. }
  18339. size_t get_size_read() override {
  18340. return size_read;
  18341. }
  18342. };
  18343. struct llama_data_write_file : llama_data_write {
  18344. llama_file * file;
  18345. size_t size_written = 0;
  18346. std::vector<uint8_t> temp_buffer;
  18347. llama_data_write_file(llama_file * f) : file(f) {}
  18348. void write(const void * src, size_t size) override {
  18349. file->write_raw(src, size);
  18350. size_written += size;
  18351. }
  18352. void write_tensor_data(const struct ggml_tensor * tensor, size_t offset, size_t size) override {
  18353. temp_buffer.resize(size);
  18354. ggml_backend_tensor_get(tensor, temp_buffer.data(), offset, size);
  18355. write(temp_buffer.data(), temp_buffer.size());
  18356. }
  18357. size_t get_size_written() override {
  18358. return size_written;
  18359. }
  18360. };
  18361. struct llama_data_read_file : llama_data_read {
  18362. llama_file * file;
  18363. size_t size_read = 0;
  18364. std::vector<uint8_t> temp_buffer;
  18365. llama_data_read_file(llama_file * f) : file(f) {}
  18366. void read_to(void * dst, size_t size) override {
  18367. file->read_raw(dst, size);
  18368. size_read += size;
  18369. }
  18370. const uint8_t * read(size_t size) override {
  18371. temp_buffer.resize(size);
  18372. read_to(temp_buffer.data(), size);
  18373. return temp_buffer.data();
  18374. }
  18375. size_t get_size_read() override {
  18376. return size_read;
  18377. }
  18378. };
  18379. /** copy state data into either a buffer or file depending on the passed in context
  18380. *
  18381. * file context:
  18382. * llama_file file("/path", "wb");
  18383. * llama_data_write_file data_ctx(&file);
  18384. * llama_state_get_data_internal(ctx, data_ctx);
  18385. *
  18386. * buffer context:
  18387. * std::vector<uint8_t> buf(max_size, 0);
  18388. * llama_data_write_buffer data_ctx(buf.data(), max_size);
  18389. * llama_state_get_data_internal(ctx, data_ctx);
  18390. *
  18391. */
  18392. static size_t llama_state_get_data_internal(struct llama_context * ctx, llama_data_write & data_ctx) {
  18393. llama_synchronize(ctx);
  18394. data_ctx.write_model_info(ctx);
  18395. // copy outputs
  18396. data_ctx.write_output_ids(ctx);
  18397. data_ctx.write_logits(ctx);
  18398. data_ctx.write_embeddings(ctx);
  18399. data_ctx.write_kv_cache(ctx);
  18400. return data_ctx.get_size_written();
  18401. }
  18402. size_t llama_state_get_data(struct llama_context * ctx, uint8_t * dst, size_t size) {
  18403. llama_data_write_buffer data_ctx(dst, size);
  18404. try {
  18405. return llama_state_get_data_internal(ctx, data_ctx);
  18406. } catch (const std::exception & err) {
  18407. LLAMA_LOG_ERROR("%s: error saving state: %s\n", __func__, err.what());
  18408. return 0;
  18409. }
  18410. }
  18411. // Returns the *actual* size of the state.
  18412. // Intended to be used when saving to state to a buffer.
  18413. size_t llama_state_get_size(struct llama_context * ctx) {
  18414. llama_data_write_dummy data_ctx;
  18415. try {
  18416. return llama_state_get_data_internal(ctx, data_ctx);
  18417. } catch (const std::exception & err) {
  18418. LLAMA_LOG_ERROR("%s: error getting state size: %s\n", __func__, err.what());
  18419. return 0;
  18420. }
  18421. }
  18422. static size_t llama_state_set_data_internal(struct llama_context * ctx, llama_data_read & data_ctx) {
  18423. llama_synchronize(ctx);
  18424. data_ctx.read_model_info(ctx);
  18425. // set outputs
  18426. data_ctx.read_output_ids(ctx);
  18427. data_ctx.read_logits(ctx);
  18428. data_ctx.read_embeddings(ctx);
  18429. data_ctx.read_kv_cache(ctx);
  18430. return data_ctx.get_size_read();
  18431. }
  18432. // Sets the state reading from the specified source address
  18433. size_t llama_state_set_data(struct llama_context * ctx, const uint8_t * src, size_t size) {
  18434. llama_data_read_buffer data_ctx(src, size);
  18435. try {
  18436. return llama_state_set_data_internal(ctx, data_ctx);
  18437. } catch (const std::exception & err) {
  18438. LLAMA_LOG_ERROR("%s: error loading state: %s\n", __func__, err.what());
  18439. return 0;
  18440. }
  18441. }
  18442. 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) {
  18443. llama_file file(path_session, "rb");
  18444. // sanity checks
  18445. {
  18446. const uint32_t magic = file.read_u32();
  18447. const uint32_t version = file.read_u32();
  18448. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  18449. LLAMA_LOG_ERROR("%s: unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  18450. return false;
  18451. }
  18452. }
  18453. // load the prompt
  18454. {
  18455. const uint32_t n_token_count = file.read_u32();
  18456. if (n_token_count > n_token_capacity) {
  18457. LLAMA_LOG_ERROR("%s: token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  18458. return false;
  18459. }
  18460. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  18461. *n_token_count_out = n_token_count;
  18462. }
  18463. // restore the context state
  18464. {
  18465. const size_t n_state_size_cur = file.size - file.tell();
  18466. llama_data_read_file data_ctx(&file);
  18467. const size_t n_read = llama_state_set_data_internal(ctx, data_ctx);
  18468. if (n_read != n_state_size_cur) {
  18469. 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);
  18470. return false;
  18471. }
  18472. }
  18473. return true;
  18474. }
  18475. 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) {
  18476. try {
  18477. return llama_state_load_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  18478. } catch (const std::exception & err) {
  18479. LLAMA_LOG_ERROR("%s: error loading session file: %s\n", __func__, err.what());
  18480. return false;
  18481. }
  18482. }
  18483. static bool llama_state_save_file_internal(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  18484. llama_file file(path_session, "wb");
  18485. file.write_u32(LLAMA_SESSION_MAGIC);
  18486. file.write_u32(LLAMA_SESSION_VERSION);
  18487. // save the prompt
  18488. file.write_u32((uint32_t) n_token_count);
  18489. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  18490. // save the context state using stream saving
  18491. llama_data_write_file data_ctx(&file);
  18492. llama_state_get_data_internal(ctx, data_ctx);
  18493. return true;
  18494. }
  18495. bool llama_state_save_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  18496. try {
  18497. return llama_state_save_file_internal(ctx, path_session, tokens, n_token_count);
  18498. } catch (const std::exception & err) {
  18499. LLAMA_LOG_ERROR("%s: error saving session file: %s\n", __func__, err.what());
  18500. return false;
  18501. }
  18502. }
  18503. static size_t llama_state_seq_get_data_internal(struct llama_context * ctx, llama_data_write & data_ctx, llama_seq_id seq_id) {
  18504. llama_synchronize(ctx);
  18505. data_ctx.write_kv_cache(ctx, seq_id);
  18506. return data_ctx.get_size_written();
  18507. }
  18508. size_t llama_state_seq_get_size(struct llama_context * ctx, llama_seq_id seq_id) {
  18509. llama_data_write_dummy data_ctx;
  18510. return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  18511. }
  18512. size_t llama_state_seq_get_data(struct llama_context * ctx, uint8_t * dst, size_t size, llama_seq_id seq_id) {
  18513. llama_data_write_buffer data_ctx(dst, size);
  18514. try {
  18515. return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  18516. } catch (const std::exception & err) {
  18517. LLAMA_LOG_ERROR("%s: error saving sequence state: %s\n", __func__, err.what());
  18518. return 0;
  18519. }
  18520. }
  18521. static size_t llama_state_seq_set_data_internal(struct llama_context * ctx, llama_data_read & data_ctx, llama_seq_id dest_seq_id) {
  18522. llama_synchronize(ctx);
  18523. data_ctx.read_kv_cache(ctx, dest_seq_id);
  18524. return data_ctx.get_size_read();
  18525. }
  18526. size_t llama_state_seq_set_data(struct llama_context * ctx, const uint8_t * src, size_t size, llama_seq_id dest_seq_id) {
  18527. llama_data_read_buffer data_ctx(src, size);
  18528. try {
  18529. return llama_state_seq_set_data_internal(ctx, data_ctx, dest_seq_id);
  18530. } catch (const std::exception & err) {
  18531. LLAMA_LOG_ERROR("%s: error loading sequence state: %s\n", __func__, err.what());
  18532. return 0;
  18533. }
  18534. }
  18535. 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) {
  18536. llama_file file(filepath, "wb");
  18537. file.write_u32(LLAMA_STATE_SEQ_MAGIC);
  18538. file.write_u32(LLAMA_STATE_SEQ_VERSION);
  18539. // save the prompt
  18540. file.write_u32((uint32_t) n_token_count);
  18541. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  18542. // save the context state using stream saving
  18543. llama_data_write_file data_ctx(&file);
  18544. llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  18545. const size_t res = file.tell();
  18546. GGML_ASSERT(res == sizeof(uint32_t) * 3 + sizeof(llama_token) * n_token_count + data_ctx.get_size_written());
  18547. return res;
  18548. }
  18549. 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) {
  18550. llama_file file(filepath, "rb");
  18551. // version checks
  18552. {
  18553. const uint32_t magic = file.read_u32();
  18554. const uint32_t version = file.read_u32();
  18555. if (magic != LLAMA_STATE_SEQ_MAGIC || version != LLAMA_STATE_SEQ_VERSION) {
  18556. LLAMA_LOG_ERROR("%s: unknown (magic, version) for sequence state file: %08x, %08x\n", __func__, magic, version);
  18557. return 0;
  18558. }
  18559. }
  18560. // load the prompt
  18561. {
  18562. const uint32_t n_token_count = file.read_u32();
  18563. if (n_token_count > n_token_capacity) {
  18564. LLAMA_LOG_ERROR("%s: token count in sequence state file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  18565. return 0;
  18566. }
  18567. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  18568. *n_token_count_out = n_token_count;
  18569. }
  18570. // restore the context state
  18571. {
  18572. const size_t state_size = file.size - file.tell();
  18573. llama_data_read_file data_ctx(&file);
  18574. const size_t nread = llama_state_seq_set_data_internal(ctx, data_ctx, dest_seq_id);
  18575. if (!nread) {
  18576. LLAMA_LOG_ERROR("%s: failed to restore sequence state\n", __func__);
  18577. return 0;
  18578. }
  18579. GGML_ASSERT(nread <= state_size);
  18580. GGML_ASSERT(nread + sizeof(uint32_t) * 3 + sizeof(llama_token) * *n_token_count_out == file.tell());
  18581. }
  18582. return file.tell();
  18583. }
  18584. 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) {
  18585. try {
  18586. return llama_state_seq_save_file_internal(ctx, filepath, seq_id, tokens, n_token_count);
  18587. } catch (const std::exception & err) {
  18588. LLAMA_LOG_ERROR("%s: error saving sequence state file: %s\n", __func__, err.what());
  18589. return 0;
  18590. }
  18591. }
  18592. 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) {
  18593. try {
  18594. return llama_state_seq_load_file_internal(ctx, filepath, dest_seq_id, tokens_out, n_token_capacity, n_token_count_out);
  18595. } catch (const std::exception & err) {
  18596. LLAMA_LOG_ERROR("%s: error loading sequence state file: %s\n", __func__, err.what());
  18597. return 0;
  18598. }
  18599. }
  18600. void llama_set_n_threads(struct llama_context * ctx, int32_t n_threads, int32_t n_threads_batch) {
  18601. ctx->cparams.n_threads = n_threads;
  18602. ctx->cparams.n_threads_batch = n_threads_batch;
  18603. }
  18604. int32_t llama_n_threads(struct llama_context * ctx) {
  18605. return ctx->cparams.n_threads;
  18606. }
  18607. int32_t llama_n_threads_batch(struct llama_context * ctx) {
  18608. return ctx->cparams.n_threads_batch;
  18609. }
  18610. void llama_set_abort_callback(struct llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
  18611. ctx->abort_callback = abort_callback;
  18612. ctx->abort_callback_data = abort_callback_data;
  18613. for (auto & backend : ctx->backends) {
  18614. auto * reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(backend.get()));
  18615. auto * set_abort_callback_fn = (ggml_backend_set_abort_callback_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_abort_callback");
  18616. if (set_abort_callback_fn) {
  18617. set_abort_callback_fn(backend.get(), ctx->abort_callback, ctx->abort_callback_data);
  18618. }
  18619. }
  18620. }
  18621. void llama_set_embeddings(struct llama_context * ctx, bool embeddings) {
  18622. ctx->cparams.embeddings = embeddings;
  18623. }
  18624. void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn) {
  18625. ctx->cparams.causal_attn = causal_attn;
  18626. }
  18627. void llama_set_cross_attention(struct llama_context * ctx, bool cross_attention) {
  18628. ctx->cparams.cross_attn = cross_attention;
  18629. }
  18630. struct llama_batch llama_batch_get_one(
  18631. llama_token * tokens,
  18632. int32_t n_tokens) {
  18633. return {
  18634. /*n_tokens =*/ n_tokens,
  18635. /*tokens =*/ tokens,
  18636. /*embd =*/ nullptr,
  18637. /*n_embd =*/ 0,
  18638. /*pos =*/ nullptr,
  18639. /*n_seq_id =*/ nullptr,
  18640. /*seq_id =*/ nullptr,
  18641. /*logits =*/ nullptr,
  18642. };
  18643. }
  18644. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  18645. llama_batch batch = {
  18646. /*n_tokens =*/ 0,
  18647. /*tokens =*/ nullptr,
  18648. /*embd =*/ nullptr,
  18649. /*n_embd =*/ 0,
  18650. /*pos =*/ nullptr,
  18651. /*n_seq_id =*/ nullptr,
  18652. /*seq_id =*/ nullptr,
  18653. /*logits =*/ nullptr,
  18654. };
  18655. if (embd) {
  18656. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  18657. batch.n_embd = embd;
  18658. } else {
  18659. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  18660. }
  18661. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  18662. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  18663. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  18664. for (int i = 0; i < n_tokens_alloc; ++i) {
  18665. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  18666. }
  18667. batch.seq_id[n_tokens_alloc] = nullptr;
  18668. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  18669. return batch;
  18670. }
  18671. void llama_batch_free(struct llama_batch batch) {
  18672. if (batch.token) free(batch.token);
  18673. if (batch.embd) free(batch.embd);
  18674. if (batch.pos) free(batch.pos);
  18675. if (batch.n_seq_id) free(batch.n_seq_id);
  18676. if (batch.seq_id) {
  18677. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  18678. free(batch.seq_id[i]);
  18679. }
  18680. free(batch.seq_id);
  18681. }
  18682. if (batch.logits) free(batch.logits);
  18683. }
  18684. int32_t llama_encode(
  18685. struct llama_context * ctx,
  18686. struct llama_batch batch) {
  18687. const int ret = llama_encode_internal(*ctx, batch);
  18688. if (ret != 0) {
  18689. LLAMA_LOG_ERROR("%s: failed to encode, ret = %d\n", __func__, ret);
  18690. }
  18691. return ret;
  18692. }
  18693. int32_t llama_decode(
  18694. struct llama_context * ctx,
  18695. struct llama_batch batch) {
  18696. const int ret = llama_decode_internal(*ctx, batch);
  18697. if (ret != 0) {
  18698. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  18699. }
  18700. return ret;
  18701. }
  18702. void llama_synchronize(struct llama_context * ctx) {
  18703. ggml_backend_sched_synchronize(ctx->sched.get());
  18704. // FIXME: if multiple single tokens are evaluated without a synchronization,
  18705. // the stats will be added to the prompt evaluation stats
  18706. // this should only happen when using batch size 1 to evaluate a batch
  18707. // add the evaluation to the stats
  18708. if (ctx->n_queued_tokens == 1) {
  18709. if (!ctx->cparams.no_perf) {
  18710. ctx->t_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  18711. }
  18712. ctx->n_eval++;
  18713. } else if (ctx->n_queued_tokens > 1) {
  18714. if (!ctx->cparams.no_perf) {
  18715. ctx->t_p_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  18716. }
  18717. ctx->n_p_eval += ctx->n_queued_tokens;
  18718. }
  18719. // get a more accurate load time, upon first eval
  18720. if (ctx->n_queued_tokens > 0 && !ctx->has_evaluated_once) {
  18721. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  18722. ctx->has_evaluated_once = true;
  18723. }
  18724. ctx->n_queued_tokens = 0;
  18725. ctx->t_compute_start_us = 0;
  18726. }
  18727. float * llama_get_logits(struct llama_context * ctx) {
  18728. llama_synchronize(ctx);
  18729. // reorder logits for backward compatibility
  18730. // TODO: maybe deprecate this
  18731. llama_output_reorder(ctx);
  18732. return ctx->logits;
  18733. }
  18734. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  18735. int32_t j = -1;
  18736. llama_synchronize(ctx);
  18737. try {
  18738. if (ctx->logits == nullptr) {
  18739. throw std::runtime_error("no logits");
  18740. }
  18741. if (i < 0) {
  18742. j = ctx->n_outputs + i;
  18743. if (j < 0) {
  18744. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  18745. }
  18746. } else if ((size_t) i >= ctx->output_ids.size()) {
  18747. throw std::runtime_error(format("out of range [0, %zu)", ctx->output_ids.size()));
  18748. } else {
  18749. j = ctx->output_ids[i];
  18750. }
  18751. if (j < 0) {
  18752. throw std::runtime_error(format("batch.logits[%d] != true", i));
  18753. }
  18754. if (j >= ctx->n_outputs) {
  18755. // This should not happen
  18756. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  18757. }
  18758. return ctx->logits + j*ctx->model.hparams.n_vocab;
  18759. } catch (const std::exception & err) {
  18760. LLAMA_LOG_ERROR("%s: invalid logits id %d, reason: %s\n", __func__, i, err.what());
  18761. #ifndef NDEBUG
  18762. GGML_ABORT("fatal error");
  18763. #else
  18764. return nullptr;
  18765. #endif
  18766. }
  18767. }
  18768. float * llama_get_embeddings(struct llama_context * ctx) {
  18769. llama_synchronize(ctx);
  18770. // reorder embeddings for backward compatibility
  18771. // TODO: maybe deprecate this
  18772. llama_output_reorder(ctx);
  18773. return ctx->embd;
  18774. }
  18775. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  18776. int32_t j = -1;
  18777. llama_synchronize(ctx);
  18778. try {
  18779. if (ctx->embd == nullptr) {
  18780. throw std::runtime_error("no embeddings");
  18781. }
  18782. if (i < 0) {
  18783. j = ctx->n_outputs + i;
  18784. if (j < 0) {
  18785. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  18786. }
  18787. } else if ((size_t) i >= ctx->output_ids.size()) {
  18788. throw std::runtime_error(format("out of range [0, %zu)", ctx->output_ids.size()));
  18789. } else {
  18790. j = ctx->output_ids[i];
  18791. }
  18792. if (j < 0) {
  18793. throw std::runtime_error(format("batch.logits[%d] != true", i));
  18794. }
  18795. if (j >= ctx->n_outputs) {
  18796. // This should not happen
  18797. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  18798. }
  18799. return ctx->embd + j*ctx->model.hparams.n_embd;
  18800. } catch (const std::exception & err) {
  18801. LLAMA_LOG_ERROR("%s: invalid embeddings id %d, reason: %s\n", __func__, i, err.what());
  18802. #ifndef NDEBUG
  18803. GGML_ABORT("fatal error");
  18804. #else
  18805. return nullptr;
  18806. #endif
  18807. }
  18808. }
  18809. float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id) {
  18810. llama_synchronize(ctx);
  18811. auto it = ctx->embd_seq.find(seq_id);
  18812. if (it == ctx->embd_seq.end()) {
  18813. return nullptr;
  18814. }
  18815. return it->second.data();
  18816. }
  18817. //
  18818. // vocab
  18819. //
  18820. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  18821. return llama_token_get_text_impl(model->vocab, token);
  18822. }
  18823. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  18824. return llama_token_get_score_impl(model->vocab, token);
  18825. }
  18826. enum llama_token_attr llama_token_get_attr(const struct llama_model * model, llama_token token) {
  18827. return llama_token_get_attr_impl(model->vocab, token);
  18828. }
  18829. bool llama_token_is_eog(const struct llama_model * model, llama_token token) {
  18830. return llama_token_is_eog_impl(model->vocab, token);
  18831. }
  18832. bool llama_token_is_control(const struct llama_model * model, llama_token token) {
  18833. return llama_token_is_control_impl(model->vocab, token);
  18834. }
  18835. llama_token llama_token_bos(const struct llama_model * model) {
  18836. return llama_token_bos_impl(model->vocab);
  18837. }
  18838. llama_token llama_token_eos(const struct llama_model * model) {
  18839. return llama_token_eos_impl(model->vocab);
  18840. }
  18841. llama_token llama_token_eot(const struct llama_model * model) {
  18842. return llama_token_eot_impl(model->vocab);
  18843. }
  18844. llama_token llama_token_cls(const struct llama_model * model) {
  18845. return llama_token_cls_impl(model->vocab);
  18846. }
  18847. llama_token llama_token_sep(const struct llama_model * model) {
  18848. return llama_token_sep_impl(model->vocab);
  18849. }
  18850. llama_token llama_token_nl (const struct llama_model * model) {
  18851. return llama_token_nl_impl(model->vocab);
  18852. }
  18853. llama_token llama_token_pad(const struct llama_model * model) {
  18854. return llama_token_pad_impl(model->vocab);
  18855. }
  18856. bool llama_add_bos_token(const struct llama_model * model) {
  18857. return llama_add_bos_token_impl(model->vocab);
  18858. }
  18859. bool llama_add_eos_token(const struct llama_model * model) {
  18860. return llama_add_eos_token_impl(model->vocab);
  18861. }
  18862. llama_token llama_token_prefix(const struct llama_model * model) {
  18863. return llama_token_prefix_impl(model->vocab);
  18864. }
  18865. llama_token llama_token_middle(const struct llama_model * model) {
  18866. return llama_token_middle_impl(model->vocab);
  18867. }
  18868. llama_token llama_token_suffix(const struct llama_model * model) {
  18869. return llama_token_suffix_impl(model->vocab);
  18870. }
  18871. llama_token llama_token_fim_pre(const struct llama_model * model) {
  18872. return llama_token_fim_pre_impl(model->vocab);
  18873. }
  18874. llama_token llama_token_fim_suf(const struct llama_model * model) {
  18875. return llama_token_fim_suf_impl(model->vocab);
  18876. }
  18877. llama_token llama_token_fim_mid(const struct llama_model * model) {
  18878. return llama_token_fim_mid_impl(model->vocab);
  18879. }
  18880. llama_token llama_token_fim_pad(const struct llama_model * model) {
  18881. return llama_token_fim_pad_impl(model->vocab);
  18882. }
  18883. llama_token llama_token_fim_rep(const struct llama_model * model) {
  18884. return llama_token_fim_rep_impl(model->vocab);
  18885. }
  18886. llama_token llama_token_fim_sep(const struct llama_model * model) {
  18887. return llama_token_fim_sep_impl(model->vocab);
  18888. }
  18889. //
  18890. // tokenization
  18891. //
  18892. int32_t llama_tokenize(
  18893. const struct llama_model * model,
  18894. const char * text,
  18895. int32_t text_len,
  18896. llama_token * tokens,
  18897. int32_t n_tokens_max,
  18898. bool add_special,
  18899. bool parse_special) {
  18900. return llama_tokenize_impl(model->vocab, text, text_len, tokens, n_tokens_max, add_special, parse_special);
  18901. }
  18902. int32_t llama_token_to_piece(
  18903. const struct llama_model * model,
  18904. llama_token token,
  18905. char * buf,
  18906. int32_t length,
  18907. int32_t lstrip,
  18908. bool special) {
  18909. return llama_token_to_piece_impl(model->vocab, token, buf, length, lstrip, special);
  18910. }
  18911. int32_t llama_detokenize(
  18912. const struct llama_model * model,
  18913. const llama_token * tokens,
  18914. int32_t n_tokens,
  18915. char * text,
  18916. int32_t text_len_max,
  18917. bool remove_special,
  18918. bool unparse_special) {
  18919. return llama_detokenize_impl(model->vocab, tokens, n_tokens, text, text_len_max, remove_special, unparse_special);
  18920. }
  18921. //
  18922. // chat templates
  18923. //
  18924. static llm_chat_template llama_chat_detect_template(const std::string & tmpl) {
  18925. if (LLM_CHAT_TEMPLATES.find(tmpl) != LLM_CHAT_TEMPLATES.end()) {
  18926. return LLM_CHAT_TEMPLATES.at(tmpl);
  18927. }
  18928. auto tmpl_contains = [&tmpl](const char * haystack) -> bool {
  18929. return tmpl.find(haystack) != std::string::npos;
  18930. };
  18931. if (tmpl_contains("<|im_start|>")) {
  18932. return LLM_CHAT_TEMPLATE_CHATML;
  18933. } else if (tmpl.find("mistral") == 0 || tmpl_contains("[INST]")) {
  18934. if (tmpl_contains("[SYSTEM_PROMPT]")) {
  18935. return LLM_CHAT_TEMPLATE_MISTRAL_V7;
  18936. } else if (
  18937. // catches official 'v1' template
  18938. tmpl_contains("' [INST] ' + system_message")
  18939. // catches official 'v3' and 'v3-tekken' templates
  18940. || tmpl_contains("[AVAILABLE_TOOLS]")
  18941. ) {
  18942. // Official mistral 'v1', 'v3' and 'v3-tekken' templates
  18943. // See: https://github.com/mistralai/cookbook/blob/main/concept-deep-dive/tokenization/chat_templates.md
  18944. // See: https://github.com/mistralai/cookbook/blob/main/concept-deep-dive/tokenization/templates.md
  18945. if (tmpl_contains(" [INST]")) {
  18946. return LLM_CHAT_TEMPLATE_MISTRAL_V1;
  18947. } else if (tmpl_contains("\"[INST]\"")) {
  18948. return LLM_CHAT_TEMPLATE_MISTRAL_V3_TEKKEN;
  18949. }
  18950. return LLM_CHAT_TEMPLATE_MISTRAL_V3;
  18951. } else {
  18952. // llama2 template and its variants
  18953. // [variant] support system message
  18954. // See: https://huggingface.co/blog/llama2#how-to-prompt-llama-2
  18955. bool support_system_message = tmpl_contains("<<SYS>>");
  18956. bool add_bos_inside_history = tmpl_contains("bos_token + '[INST]");
  18957. bool strip_message = tmpl_contains("content.strip()");
  18958. if (strip_message) {
  18959. return LLM_CHAT_TEMPLATE_LLAMA_2_SYS_STRIP;
  18960. } else if (add_bos_inside_history) {
  18961. return LLM_CHAT_TEMPLATE_LLAMA_2_SYS_BOS;
  18962. } else if (support_system_message) {
  18963. return LLM_CHAT_TEMPLATE_LLAMA_2_SYS;
  18964. } else {
  18965. return LLM_CHAT_TEMPLATE_LLAMA_2;
  18966. }
  18967. }
  18968. } else if (tmpl_contains("<|assistant|>") && tmpl_contains("<|end|>")) {
  18969. return LLM_CHAT_TEMPLATE_PHI_3;
  18970. } else if (tmpl_contains("<|user|>") && tmpl_contains("<|endoftext|>")) {
  18971. return LLM_CHAT_TEMPLATE_ZEPHYR;
  18972. } else if (tmpl_contains("bos_token + message['role']")) {
  18973. return LLM_CHAT_TEMPLATE_MONARCH;
  18974. } else if (tmpl_contains("<start_of_turn>")) {
  18975. return LLM_CHAT_TEMPLATE_GEMMA;
  18976. } else if (tmpl_contains("'\\n\\nAssistant: ' + eos_token")) {
  18977. // OrionStarAI/Orion-14B-Chat
  18978. return LLM_CHAT_TEMPLATE_ORION;
  18979. } else if (tmpl_contains("GPT4 Correct ")) {
  18980. // openchat/openchat-3.5-0106
  18981. return LLM_CHAT_TEMPLATE_OPENCHAT;
  18982. } else if (tmpl_contains("USER: ") && tmpl_contains("ASSISTANT: ")) {
  18983. // eachadea/vicuna-13b-1.1 (and Orca variant)
  18984. if (tmpl_contains("SYSTEM: ")) {
  18985. return LLM_CHAT_TEMPLATE_VICUNA_ORCA;
  18986. }
  18987. return LLM_CHAT_TEMPLATE_VICUNA;
  18988. } else if (tmpl_contains("### Instruction:") && tmpl_contains("<|EOT|>")) {
  18989. // deepseek-ai/deepseek-coder-33b-instruct
  18990. return LLM_CHAT_TEMPLATE_DEEPSEEK;
  18991. } else if (tmpl_contains("<|START_OF_TURN_TOKEN|>") && tmpl_contains("<|USER_TOKEN|>")) {
  18992. // CohereForAI/c4ai-command-r-plus
  18993. return LLM_CHAT_TEMPLATE_COMMAND_R;
  18994. } else if (tmpl_contains("<|start_header_id|>") && tmpl_contains("<|end_header_id|>")) {
  18995. return LLM_CHAT_TEMPLATE_LLAMA_3;
  18996. } else if (tmpl_contains("[gMASK]sop")) {
  18997. // chatglm3-6b
  18998. return LLM_CHAT_TEMPLATE_CHATGML_3;
  18999. } else if (tmpl_contains("[gMASK]<sop>")) {
  19000. return LLM_CHAT_TEMPLATE_CHATGML_4;
  19001. } else if (tmpl_contains(LU8("<用户>"))) {
  19002. // MiniCPM-3B-OpenHermes-2.5-v2-GGUF
  19003. return LLM_CHAT_TEMPLATE_MINICPM;
  19004. } else if (tmpl_contains("'Assistant: ' + message['content'] + eos_token")) {
  19005. return LLM_CHAT_TEMPLATE_DEEPSEEK_2;
  19006. } else if (tmpl_contains("[|system|]") && tmpl_contains("[|assistant|]") && tmpl_contains("[|endofturn|]")) {
  19007. // ref: https://huggingface.co/LGAI-EXAONE/EXAONE-3.0-7.8B-Instruct/discussions/8#66bae61b1893d14ee8ed85bb
  19008. // EXAONE-3.0-7.8B-Instruct
  19009. return LLM_CHAT_TEMPLATE_EXAONE_3;
  19010. } else if (tmpl_contains("rwkv-world")) {
  19011. return LLM_CHAT_TEMPLATE_RWKV_WORLD;
  19012. } else if (tmpl_contains("<|start_of_role|>")) {
  19013. return LLM_CHAT_TEMPLATE_GRANITE;
  19014. }
  19015. return LLM_CHAT_TEMPLATE_UNKNOWN;
  19016. }
  19017. // Simple version of "llama_apply_chat_template" that only works with strings
  19018. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  19019. static int32_t llama_chat_apply_template_internal(
  19020. const llm_chat_template tmpl,
  19021. const std::vector<const llama_chat_message *> & chat,
  19022. std::string & dest, bool add_ass) {
  19023. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  19024. std::stringstream ss;
  19025. if (tmpl == LLM_CHAT_TEMPLATE_CHATML) {
  19026. // chatml template
  19027. for (auto message : chat) {
  19028. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  19029. }
  19030. if (add_ass) {
  19031. ss << "<|im_start|>assistant\n";
  19032. }
  19033. } else if (tmpl == LLM_CHAT_TEMPLATE_MISTRAL_V7) {
  19034. // Official mistral 'v7' template
  19035. // See: https://huggingface.co/mistralai/Mistral-Large-Instruct-2411#basic-instruct-template-v7
  19036. for (auto message : chat) {
  19037. std::string role(message->role);
  19038. std::string content(message->content);
  19039. if (role == "system") {
  19040. ss << "[SYSTEM_PROMPT] " << content << "[/SYSTEM_PROMPT]";
  19041. } else if (role == "user") {
  19042. ss << "[INST] " << content << "[/INST]";
  19043. }
  19044. else {
  19045. ss << " " << content << "</s>";
  19046. }
  19047. }
  19048. } else if (tmpl == LLM_CHAT_TEMPLATE_MISTRAL_V1
  19049. || tmpl == LLM_CHAT_TEMPLATE_MISTRAL_V3
  19050. || tmpl == LLM_CHAT_TEMPLATE_MISTRAL_V3_TEKKEN) {
  19051. // See: https://github.com/mistralai/cookbook/blob/main/concept-deep-dive/tokenization/chat_templates.md
  19052. // See: https://github.com/mistralai/cookbook/blob/main/concept-deep-dive/tokenization/templates.md
  19053. std::string leading_space = tmpl == LLM_CHAT_TEMPLATE_MISTRAL_V1 ? " " : "";
  19054. std::string trailing_space = tmpl == LLM_CHAT_TEMPLATE_MISTRAL_V3_TEKKEN ? "" : " ";
  19055. bool trim_assistant_message = tmpl == LLM_CHAT_TEMPLATE_MISTRAL_V3;
  19056. bool is_inside_turn = false;
  19057. for (auto message : chat) {
  19058. if (!is_inside_turn) {
  19059. ss << leading_space << "[INST]" << trailing_space;
  19060. is_inside_turn = true;
  19061. }
  19062. std::string role(message->role);
  19063. std::string content(message->content);
  19064. if (role == "system") {
  19065. ss << content << "\n\n";
  19066. } else if (role == "user") {
  19067. ss << content << leading_space << "[/INST]";
  19068. } else {
  19069. ss << trailing_space << (trim_assistant_message ? trim(content) : content) << "</s>";
  19070. is_inside_turn = false;
  19071. }
  19072. }
  19073. } else if (
  19074. tmpl == LLM_CHAT_TEMPLATE_LLAMA_2
  19075. || tmpl == LLM_CHAT_TEMPLATE_LLAMA_2_SYS
  19076. || tmpl == LLM_CHAT_TEMPLATE_LLAMA_2_SYS_BOS
  19077. || tmpl == LLM_CHAT_TEMPLATE_LLAMA_2_SYS_STRIP) {
  19078. // llama2 template and its variants
  19079. // [variant] support system message
  19080. // See: https://huggingface.co/blog/llama2#how-to-prompt-llama-2
  19081. bool support_system_message = tmpl != LLM_CHAT_TEMPLATE_LLAMA_2;
  19082. // [variant] add BOS inside history
  19083. bool add_bos_inside_history = tmpl == LLM_CHAT_TEMPLATE_LLAMA_2_SYS_BOS;
  19084. // [variant] trim spaces from the input message
  19085. bool strip_message = tmpl == LLM_CHAT_TEMPLATE_LLAMA_2_SYS_STRIP;
  19086. // construct the prompt
  19087. bool is_inside_turn = true; // skip BOS at the beginning
  19088. ss << "[INST] ";
  19089. for (auto message : chat) {
  19090. std::string content = strip_message ? trim(message->content) : message->content;
  19091. std::string role(message->role);
  19092. if (!is_inside_turn) {
  19093. is_inside_turn = true;
  19094. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  19095. }
  19096. if (role == "system") {
  19097. if (support_system_message) {
  19098. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  19099. } else {
  19100. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  19101. ss << content << "\n";
  19102. }
  19103. } else if (role == "user") {
  19104. ss << content << " [/INST]";
  19105. } else {
  19106. ss << content << "</s>";
  19107. is_inside_turn = false;
  19108. }
  19109. }
  19110. } else if (tmpl == LLM_CHAT_TEMPLATE_PHI_3) {
  19111. // Phi 3
  19112. for (auto message : chat) {
  19113. std::string role(message->role);
  19114. ss << "<|" << role << "|>\n" << message->content << "<|end|>\n";
  19115. }
  19116. if (add_ass) {
  19117. ss << "<|assistant|>\n";
  19118. }
  19119. } else if (tmpl == LLM_CHAT_TEMPLATE_ZEPHYR) {
  19120. // zephyr template
  19121. for (auto message : chat) {
  19122. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  19123. }
  19124. if (add_ass) {
  19125. ss << "<|assistant|>\n";
  19126. }
  19127. } else if (tmpl == LLM_CHAT_TEMPLATE_MONARCH) {
  19128. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  19129. for (auto message : chat) {
  19130. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  19131. ss << bos << message->role << "\n" << message->content << "</s>\n";
  19132. }
  19133. if (add_ass) {
  19134. ss << "<s>assistant\n";
  19135. }
  19136. } else if (tmpl == LLM_CHAT_TEMPLATE_GEMMA) {
  19137. // google/gemma-7b-it
  19138. std::string system_prompt = "";
  19139. for (auto message : chat) {
  19140. std::string role(message->role);
  19141. if (role == "system") {
  19142. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  19143. system_prompt = trim(message->content);
  19144. continue;
  19145. }
  19146. // in gemma, "assistant" is "model"
  19147. role = role == "assistant" ? "model" : message->role;
  19148. ss << "<start_of_turn>" << role << "\n";
  19149. if (!system_prompt.empty() && role != "model") {
  19150. ss << system_prompt << "\n\n";
  19151. system_prompt = "";
  19152. }
  19153. ss << trim(message->content) << "<end_of_turn>\n";
  19154. }
  19155. if (add_ass) {
  19156. ss << "<start_of_turn>model\n";
  19157. }
  19158. } else if (tmpl == LLM_CHAT_TEMPLATE_ORION) {
  19159. // OrionStarAI/Orion-14B-Chat
  19160. std::string system_prompt = "";
  19161. for (auto message : chat) {
  19162. std::string role(message->role);
  19163. if (role == "system") {
  19164. // there is no system message support, we will merge it with user prompt
  19165. system_prompt = message->content;
  19166. continue;
  19167. } else if (role == "user") {
  19168. ss << "Human: ";
  19169. if (!system_prompt.empty()) {
  19170. ss << system_prompt << "\n\n";
  19171. system_prompt = "";
  19172. }
  19173. ss << message->content << "\n\nAssistant: </s>";
  19174. } else {
  19175. ss << message->content << "</s>";
  19176. }
  19177. }
  19178. } else if (tmpl == LLM_CHAT_TEMPLATE_OPENCHAT) {
  19179. // openchat/openchat-3.5-0106,
  19180. for (auto message : chat) {
  19181. std::string role(message->role);
  19182. if (role == "system") {
  19183. ss << message->content << "<|end_of_turn|>";
  19184. } else {
  19185. role[0] = toupper(role[0]);
  19186. ss << "GPT4 Correct " << role << ": " << message->content << "<|end_of_turn|>";
  19187. }
  19188. }
  19189. if (add_ass) {
  19190. ss << "GPT4 Correct Assistant:";
  19191. }
  19192. } else if (tmpl == LLM_CHAT_TEMPLATE_VICUNA || tmpl == LLM_CHAT_TEMPLATE_VICUNA_ORCA) {
  19193. // eachadea/vicuna-13b-1.1 (and Orca variant)
  19194. for (auto message : chat) {
  19195. std::string role(message->role);
  19196. if (role == "system") {
  19197. // Orca-Vicuna variant uses a system prefix
  19198. if (tmpl == LLM_CHAT_TEMPLATE_VICUNA_ORCA) {
  19199. ss << "SYSTEM: " << message->content << "\n";
  19200. } else {
  19201. ss << message->content << "\n\n";
  19202. }
  19203. } else if (role == "user") {
  19204. ss << "USER: " << message->content << "\n";
  19205. } else if (role == "assistant") {
  19206. ss << "ASSISTANT: " << message->content << "</s>\n";
  19207. }
  19208. }
  19209. if (add_ass) {
  19210. ss << "ASSISTANT:";
  19211. }
  19212. } else if (tmpl == LLM_CHAT_TEMPLATE_DEEPSEEK) {
  19213. // deepseek-ai/deepseek-coder-33b-instruct
  19214. for (auto message : chat) {
  19215. std::string role(message->role);
  19216. if (role == "system") {
  19217. ss << message->content;
  19218. } else if (role == "user") {
  19219. ss << "### Instruction:\n" << message->content << "\n";
  19220. } else if (role == "assistant") {
  19221. ss << "### Response:\n" << message->content << "\n<|EOT|>\n";
  19222. }
  19223. }
  19224. if (add_ass) {
  19225. ss << "### Response:\n";
  19226. }
  19227. } else if (tmpl == LLM_CHAT_TEMPLATE_COMMAND_R) {
  19228. // CohereForAI/c4ai-command-r-plus
  19229. for (auto message : chat) {
  19230. std::string role(message->role);
  19231. if (role == "system") {
  19232. ss << "<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  19233. } else if (role == "user") {
  19234. ss << "<|START_OF_TURN_TOKEN|><|USER_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  19235. } else if (role == "assistant") {
  19236. ss << "<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  19237. }
  19238. }
  19239. if (add_ass) {
  19240. ss << "<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>";
  19241. }
  19242. } else if (tmpl == LLM_CHAT_TEMPLATE_LLAMA_3) {
  19243. // Llama 3
  19244. for (auto message : chat) {
  19245. std::string role(message->role);
  19246. ss << "<|start_header_id|>" << role << "<|end_header_id|>\n\n" << trim(message->content) << "<|eot_id|>";
  19247. }
  19248. if (add_ass) {
  19249. ss << "<|start_header_id|>assistant<|end_header_id|>\n\n";
  19250. }
  19251. } else if (tmpl == LLM_CHAT_TEMPLATE_CHATGML_3) {
  19252. // chatglm3-6b
  19253. ss << "[gMASK]" << "sop";
  19254. for (auto message : chat) {
  19255. std::string role(message->role);
  19256. ss << "<|" << role << "|>" << "\n " << message->content;
  19257. }
  19258. if (add_ass) {
  19259. ss << "<|assistant|>";
  19260. }
  19261. } else if (tmpl == LLM_CHAT_TEMPLATE_CHATGML_4) {
  19262. ss << "[gMASK]" << "<sop>";
  19263. for (auto message : chat) {
  19264. std::string role(message->role);
  19265. ss << "<|" << role << "|>" << "\n" << message->content;
  19266. }
  19267. if (add_ass) {
  19268. ss << "<|assistant|>";
  19269. }
  19270. } else if (tmpl == LLM_CHAT_TEMPLATE_MINICPM) {
  19271. // MiniCPM-3B-OpenHermes-2.5-v2-GGUF
  19272. for (auto message : chat) {
  19273. std::string role(message->role);
  19274. if (role == "user") {
  19275. ss << LU8("<用户>");
  19276. ss << trim(message->content);
  19277. ss << "<AI>";
  19278. } else {
  19279. ss << trim(message->content);
  19280. }
  19281. }
  19282. } else if (tmpl == LLM_CHAT_TEMPLATE_DEEPSEEK_2) {
  19283. // DeepSeek-V2
  19284. for (auto message : chat) {
  19285. std::string role(message->role);
  19286. if (role == "system") {
  19287. ss << message->content << "\n\n";
  19288. } else if (role == "user") {
  19289. ss << "User: " << message->content << "\n\n";
  19290. } else if (role == "assistant") {
  19291. ss << "Assistant: " << message->content << LU8("<|end▁of▁sentence|>");
  19292. }
  19293. }
  19294. if (add_ass) {
  19295. ss << "Assistant:";
  19296. }
  19297. } else if (tmpl == LLM_CHAT_TEMPLATE_EXAONE_3) {
  19298. // ref: https://huggingface.co/LGAI-EXAONE/EXAONE-3.0-7.8B-Instruct/discussions/8#66bae61b1893d14ee8ed85bb
  19299. // EXAONE-3.0-7.8B-Instruct
  19300. for (auto message : chat) {
  19301. std::string role(message->role);
  19302. if (role == "system") {
  19303. ss << "[|system|]" << trim(message->content) << "[|endofturn|]\n";
  19304. } else if (role == "user") {
  19305. ss << "[|user|]" << trim(message->content) << "\n";
  19306. } else if (role == "assistant") {
  19307. ss << "[|assistant|]" << trim(message->content) << "[|endofturn|]\n";
  19308. }
  19309. }
  19310. if (add_ass) {
  19311. ss << "[|assistant|]";
  19312. }
  19313. } else if (tmpl == LLM_CHAT_TEMPLATE_RWKV_WORLD) {
  19314. // this template requires the model to have "\n\n" as EOT token
  19315. for (auto message : chat) {
  19316. std::string role(message->role);
  19317. if (role == "user") {
  19318. ss << "User: " << message->content << "\n\nAssistant:";
  19319. } else {
  19320. ss << message->content << "\n\n";
  19321. }
  19322. }
  19323. } else if (tmpl == LLM_CHAT_TEMPLATE_GRANITE) {
  19324. // IBM Granite template
  19325. for (const auto & message : chat) {
  19326. std::string role(message->role);
  19327. ss << "<|start_of_role|>" << role << "<|end_of_role|>";
  19328. if (role == "assistant_tool_call") {
  19329. ss << "<|tool_call|>";
  19330. }
  19331. ss << message->content << "<|end_of_text|>\n";
  19332. }
  19333. if (add_ass) {
  19334. ss << "<|start_of_role|>assistant<|end_of_role|>\n";
  19335. }
  19336. } else {
  19337. // template not supported
  19338. return -1;
  19339. }
  19340. dest = ss.str();
  19341. return dest.size();
  19342. }
  19343. int32_t llama_chat_apply_template(
  19344. const struct llama_model * model,
  19345. const char * tmpl,
  19346. const struct llama_chat_message * chat,
  19347. size_t n_msg,
  19348. bool add_ass,
  19349. char * buf,
  19350. int32_t length) {
  19351. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  19352. if (tmpl == nullptr) {
  19353. GGML_ASSERT(model != nullptr);
  19354. // load template from model
  19355. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  19356. std::string template_key = "tokenizer.chat_template";
  19357. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  19358. if (res < 0) {
  19359. // worst case: there is no information about template, we will use chatml by default
  19360. curr_tmpl = "chatml"; // see llama_chat_apply_template_internal
  19361. } else {
  19362. curr_tmpl = std::string(model_template.data(), model_template.size());
  19363. }
  19364. }
  19365. // format the chat to string
  19366. std::vector<const llama_chat_message *> chat_vec;
  19367. chat_vec.resize(n_msg);
  19368. for (size_t i = 0; i < n_msg; i++) {
  19369. chat_vec[i] = &chat[i];
  19370. }
  19371. std::string formatted_chat;
  19372. llm_chat_template detected_tmpl = llama_chat_detect_template(curr_tmpl);
  19373. if (detected_tmpl == LLM_CHAT_TEMPLATE_UNKNOWN) {
  19374. return -1;
  19375. }
  19376. int32_t res = llama_chat_apply_template_internal(detected_tmpl, chat_vec, formatted_chat, add_ass);
  19377. if (res < 0) {
  19378. return res;
  19379. }
  19380. if (buf && length > 0) {
  19381. strncpy(buf, formatted_chat.c_str(), length);
  19382. }
  19383. return res;
  19384. }
  19385. int32_t llama_chat_builtin_templates(const char ** output, size_t len) {
  19386. auto it = LLM_CHAT_TEMPLATES.begin();
  19387. for (size_t i = 0; i < std::min(len, LLM_CHAT_TEMPLATES.size()); i++) {
  19388. output[i] = it->first.c_str();
  19389. std::advance(it, 1);
  19390. }
  19391. return (int32_t) LLM_CHAT_TEMPLATES.size();
  19392. }
  19393. //
  19394. // sampling
  19395. //
  19396. // TODO: remove indirection when vocab becomes accesible in llama-sampling.cpp
  19397. struct llama_sampler * llama_sampler_init_grammar(const struct llama_model * model, const char * grammar_str, const char * grammar_root) {
  19398. return llama_sampler_init_grammar_impl(model->vocab, grammar_str, grammar_root);
  19399. }
  19400. struct llama_sampler * llama_sampler_init_infill(const struct llama_model * model) {
  19401. return llama_sampler_init_infill_impl(model->vocab);
  19402. }
  19403. 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) {
  19404. 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);
  19405. }
  19406. //
  19407. // model split
  19408. //
  19409. int llama_split_path(char * split_path, size_t maxlen, const char * path_prefix, int split_no, int split_count) {
  19410. static const char * const SPLIT_PATH_FORMAT = "%s-%05d-of-%05d.gguf";
  19411. if (snprintf(split_path, maxlen, SPLIT_PATH_FORMAT, path_prefix, split_no + 1, split_count)) {
  19412. return strlen(split_path);
  19413. }
  19414. return 0;
  19415. }
  19416. int llama_split_prefix(char * dest, size_t maxlen, const char * split_path, int split_no, int split_count) {
  19417. std::string str_split_path(split_path);
  19418. char postfix[32];
  19419. snprintf(postfix, 32, "-%05d-of-%05d.gguf", split_no + 1, split_count);
  19420. std::string str_postfix(postfix);
  19421. // check if dest ends with postfix
  19422. int size_prefix = str_split_path.size() - str_postfix.size();
  19423. if (size_prefix > 0 && str_split_path.find(str_postfix, size_prefix) != std::string::npos) {
  19424. snprintf(dest, std::min((size_t) size_prefix + 1, maxlen), "%s", split_path);
  19425. return size_prefix;
  19426. }
  19427. return 0;
  19428. }
  19429. const char * llama_print_system_info(void) {
  19430. static std::string s;
  19431. for (size_t i = 0; i < ggml_backend_reg_count(); i++) {
  19432. auto * reg = ggml_backend_reg_get(i);
  19433. auto * get_features_fn = (ggml_backend_get_features_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_get_features");
  19434. if (get_features_fn) {
  19435. ggml_backend_feature * features = get_features_fn(reg);
  19436. s += ggml_backend_reg_name(reg);
  19437. s += " : ";
  19438. for (; features->name; features++) {
  19439. s += features->name;
  19440. s += " = ";
  19441. s += features->value;
  19442. s += " | ";
  19443. }
  19444. }
  19445. }
  19446. return s.c_str();
  19447. }
  19448. struct llama_perf_context_data llama_perf_context(const struct llama_context * ctx) {
  19449. struct llama_perf_context_data data = {};
  19450. if (ctx == nullptr) {
  19451. return data;
  19452. }
  19453. data.t_start_ms = 1e-3 * ctx->t_start_us;
  19454. data.t_load_ms = 1e-3 * ctx->t_load_us;
  19455. data.t_p_eval_ms = 1e-3 * ctx->t_p_eval_us;
  19456. data.t_eval_ms = 1e-3 * ctx->t_eval_us;
  19457. data.n_p_eval = std::max(1, ctx->n_p_eval);
  19458. data.n_eval = std::max(1, ctx->n_eval);
  19459. return data;
  19460. }
  19461. void llama_perf_context_print(const struct llama_context * ctx) {
  19462. const auto data = llama_perf_context(ctx);
  19463. const double t_end_ms = 1e-3 * ggml_time_us();
  19464. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, data.t_load_ms);
  19465. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  19466. __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);
  19467. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  19468. __func__, data.t_eval_ms, data.n_eval, data.t_eval_ms / data.n_eval, 1e3 / data.t_eval_ms * data.n_eval);
  19469. 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));
  19470. }
  19471. void llama_perf_context_reset(struct llama_context * ctx) {
  19472. ctx->t_start_us = ggml_time_us();
  19473. ctx->t_eval_us = ctx->n_eval = 0;
  19474. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  19475. }
  19476. // For internal test use
  19477. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  19478. struct llama_context * ctx
  19479. ) {
  19480. return ctx->model.tensors_by_name;
  19481. }
  19482. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  19483. ggml_log_set(log_callback, user_data);
  19484. g_logger_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  19485. g_logger_state.log_callback_user_data = user_data;
  19486. }
  19487. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  19488. va_list args_copy;
  19489. va_copy(args_copy, args);
  19490. char buffer[128];
  19491. int len = vsnprintf(buffer, 128, format, args);
  19492. if (len < 128) {
  19493. g_logger_state.log_callback(level, buffer, g_logger_state.log_callback_user_data);
  19494. } else {
  19495. char * buffer2 = new char[len + 1];
  19496. vsnprintf(buffer2, len + 1, format, args_copy);
  19497. buffer2[len] = 0;
  19498. g_logger_state.log_callback(level, buffer2, g_logger_state.log_callback_user_data);
  19499. delete[] buffer2;
  19500. }
  19501. va_end(args_copy);
  19502. }
  19503. void llama_log_internal(ggml_log_level level, const char * format, ...) {
  19504. va_list args;
  19505. va_start(args, format);
  19506. llama_log_internal_v(level, format, args);
  19507. va_end(args);
  19508. }
  19509. void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  19510. (void) level;
  19511. (void) user_data;
  19512. fputs(text, stderr);
  19513. fflush(stderr);
  19514. }