llama.cpp 972 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236
  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. struct llama_control_vector {
  2805. std::vector<struct ggml_tensor *> tensors; // per layer
  2806. std::vector<ggml_context_ptr> ctxs;
  2807. std::vector<ggml_backend_buffer_ptr> bufs;
  2808. int32_t layer_start = -1;
  2809. int32_t layer_end = -1;
  2810. struct ggml_tensor * tensor_for(int il) const {
  2811. if (il < 0 || il < layer_start || il > layer_end || (size_t) il >= tensors.size()) {
  2812. return nullptr;
  2813. }
  2814. return tensors[il];
  2815. }
  2816. struct ggml_tensor * apply_to(struct ggml_context * ctx, struct ggml_tensor * cur, int il) const {
  2817. ggml_tensor * layer_dir = tensor_for(il);
  2818. if (layer_dir != nullptr) {
  2819. cur = ggml_add(ctx, cur, layer_dir);
  2820. }
  2821. return cur;
  2822. }
  2823. };
  2824. struct llama_model {
  2825. e_model type = MODEL_UNKNOWN;
  2826. llm_arch arch = LLM_ARCH_UNKNOWN;
  2827. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  2828. std::string name = "n/a";
  2829. llama_hparams hparams = {};
  2830. llama_vocab vocab;
  2831. struct ggml_tensor * tok_embd = nullptr;
  2832. struct ggml_tensor * type_embd = nullptr;
  2833. struct ggml_tensor * pos_embd = nullptr;
  2834. struct ggml_tensor * tok_norm = nullptr;
  2835. struct ggml_tensor * tok_norm_b = nullptr;
  2836. struct ggml_tensor * output_norm = nullptr;
  2837. struct ggml_tensor * output_norm_b = nullptr;
  2838. struct ggml_tensor * output = nullptr;
  2839. struct ggml_tensor * output_b = nullptr;
  2840. struct ggml_tensor * output_norm_enc = nullptr;
  2841. // classifier
  2842. struct ggml_tensor * cls = nullptr;
  2843. struct ggml_tensor * cls_b = nullptr;
  2844. struct ggml_tensor * cls_out = nullptr;
  2845. struct ggml_tensor * cls_out_b = nullptr;
  2846. std::vector<llama_layer> layers;
  2847. // gguf metadata
  2848. std::unordered_map<std::string, std::string> gguf_kv;
  2849. llama_split_mode split_mode;
  2850. int main_gpu;
  2851. int n_gpu_layers;
  2852. std::vector<std::string> rpc_servers;
  2853. // list of devices used in this model
  2854. std::vector<ggml_backend_dev_t> devices;
  2855. // lists of buffer types used for each layer
  2856. using buft_list_t = std::vector<std::pair<ggml_backend_dev_t, ggml_backend_buffer_type_t>>;
  2857. buft_list_t cpu_buft_list;
  2858. std::map<ggml_backend_dev_t, buft_list_t> gpu_buft_list;
  2859. struct layer_dev {
  2860. ggml_backend_dev_t dev;
  2861. buft_list_t * buft_list;
  2862. };
  2863. layer_dev dev_input = {};
  2864. layer_dev dev_output = {};
  2865. std::vector<layer_dev> dev_layer;
  2866. // contexts where the model tensors metadata is stored
  2867. std::vector<ggml_context_ptr> ctxs;
  2868. // the model memory buffers for the tensor data
  2869. std::vector<ggml_backend_buffer_ptr> bufs;
  2870. // model memory mapped files
  2871. llama_mmaps mappings;
  2872. // objects representing data potentially being locked in memory
  2873. llama_mlocks mlock_bufs;
  2874. llama_mlocks mlock_mmaps;
  2875. // for quantize-stats only
  2876. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  2877. int64_t t_load_us = 0;
  2878. int64_t t_start_us = 0;
  2879. // total number of parameters in the model
  2880. uint64_t n_elements = 0;
  2881. // total size of all the tensors in the model in bytes
  2882. size_t n_bytes = 0;
  2883. // keep track of loaded lora adapters
  2884. std::set<struct llama_lora_adapter *> lora_adapters;
  2885. ~llama_model() {
  2886. while (!lora_adapters.empty()) {
  2887. llama_lora_adapter_free(*lora_adapters.begin());
  2888. }
  2889. }
  2890. };
  2891. struct llama_sbatch_seq {
  2892. int32_t n_seq_id;
  2893. llama_seq_id * seq_id;
  2894. size_t offset;
  2895. size_t length;
  2896. };
  2897. // sequence-length-aware batch splitting
  2898. struct llama_sbatch {
  2899. // tokens left in this batch
  2900. size_t n_tokens;
  2901. size_t n_embd;
  2902. bool logits_all; // TODO: remove once lctx.logits_all is removed too
  2903. // sorted indices into the batch
  2904. std::vector<size_t> ids;
  2905. // batch indices of the output
  2906. std::vector<size_t> out_ids;
  2907. std::vector<llama_sbatch_seq> seq;
  2908. const llama_batch * batch = nullptr;
  2909. // buffers for the ubatch
  2910. std::vector<llama_token> ubatch_token;
  2911. std::vector<float> ubatch_embd;
  2912. std::vector<llama_pos> ubatch_pos;
  2913. std::vector<int32_t> ubatch_n_seq_id;
  2914. std::vector<llama_seq_id *> ubatch_seq_id;
  2915. std::vector<int8_t> ubatch_output;
  2916. llama_ubatch reserve_ubatch(size_t n_ubatch, bool has_embd = false) {
  2917. // clear empty sequences
  2918. // the previous ubatch is assumed to be gone,
  2919. // so nothing should refer to values in these sequences anymore.
  2920. for (size_t i = seq.size(); i-- > 0;) {
  2921. if (seq[i].length == 0) {
  2922. seq.pop_back();
  2923. } else {
  2924. break;
  2925. }
  2926. }
  2927. ubatch_token.resize(!has_embd ? n_ubatch : 0);
  2928. ubatch_embd.resize(has_embd ? n_embd * n_ubatch : 0);
  2929. ubatch_pos.resize(n_ubatch);
  2930. ubatch_n_seq_id.resize(n_ubatch);
  2931. ubatch_seq_id.resize(n_ubatch);
  2932. ubatch_output.resize(n_ubatch);
  2933. llama_ubatch ubatch = {
  2934. /*equal_seqs =*/ true,
  2935. /*n_tokens =*/ 0,
  2936. /*n_seq_tokens =*/ 0,
  2937. /*n_seqs =*/ 0,
  2938. /*token =*/ !has_embd ? ubatch_token.data() : nullptr,
  2939. /*embd =*/ has_embd ? ubatch_embd.data() : nullptr,
  2940. /*pos =*/ ubatch_pos.data(),
  2941. /*n_seq_id =*/ ubatch_n_seq_id.data(),
  2942. /*seq_id =*/ ubatch_seq_id.data(),
  2943. /*output =*/ ubatch_output.data(),
  2944. };
  2945. return ubatch;
  2946. }
  2947. void add_seq_to_ubatch(llama_ubatch & ubatch, llama_sbatch_seq & seq, size_t length) {
  2948. GGML_ASSERT(batch != nullptr);
  2949. GGML_ASSERT(length <= seq.length);
  2950. // Can only add sequences of equal lengths to a batch,
  2951. // otherwise it isn't clear to which sequence a token belongs
  2952. GGML_ASSERT(seq.n_seq_id == 0 || ubatch.n_seqs == 0 || length == (size_t) ubatch.n_tokens / ubatch.n_seqs);
  2953. GGML_ASSERT((seq.n_seq_id != 0) == ubatch.equal_seqs);
  2954. // NOTE: loops are separated for cache-friendliness
  2955. if (batch->token) {
  2956. if (ubatch.equal_seqs) {
  2957. for (size_t i = 0; i < length; ++i) {
  2958. ubatch.token[ubatch.n_tokens + i] = batch->token[ids[seq.offset + i]];
  2959. }
  2960. } else {
  2961. // simple split
  2962. ubatch.token = batch->token + seq.offset;
  2963. }
  2964. } else {
  2965. ubatch.token = nullptr;
  2966. }
  2967. if (batch->embd) {
  2968. if (ubatch.equal_seqs) {
  2969. for (size_t i = 0; i < length; ++i) {
  2970. memcpy(
  2971. ubatch.embd + n_embd * (ubatch.n_tokens + i),
  2972. batch->embd + n_embd * ids[seq.offset + i],
  2973. n_embd * sizeof(float)
  2974. );
  2975. }
  2976. } else {
  2977. // simple split
  2978. ubatch.embd = batch->embd + (n_embd * seq.offset);
  2979. }
  2980. } else {
  2981. ubatch.embd = nullptr;
  2982. }
  2983. if (ubatch.equal_seqs) {
  2984. for (size_t i = 0; i < length; ++i) {
  2985. ubatch.pos[ubatch.n_tokens + i] = batch->pos[ids[seq.offset + i]];
  2986. }
  2987. } else {
  2988. // simple split
  2989. ubatch.pos = batch->pos + seq.offset;
  2990. }
  2991. if (ubatch.equal_seqs) {
  2992. ubatch.n_seq_id[ubatch.n_seqs] = seq.n_seq_id;
  2993. if (seq.seq_id) {
  2994. ubatch.seq_id[ubatch.n_seqs] = seq.seq_id;
  2995. }
  2996. } else {
  2997. // simple split
  2998. if (batch->n_seq_id) {
  2999. ubatch.n_seq_id = batch->n_seq_id + seq.offset;
  3000. } else {
  3001. for (size_t i = 0; i < length; ++i) {
  3002. ubatch.n_seq_id[ubatch.n_seqs + i] = 1;
  3003. }
  3004. }
  3005. if (batch->seq_id) {
  3006. ubatch.seq_id = batch->seq_id + seq.offset;
  3007. }
  3008. }
  3009. if (logits_all) {
  3010. for (size_t i = 0; i < length; ++i) {
  3011. ubatch.output[ubatch.n_tokens + i] = 1;
  3012. out_ids.push_back(ids[seq.offset + i]);
  3013. }
  3014. } else if (batch->logits) {
  3015. if (ubatch.equal_seqs) {
  3016. for (size_t i = 0; i < length; ++i) {
  3017. size_t id = ids[seq.offset + i];
  3018. int8_t is_output = batch->logits[id];
  3019. ubatch.output[ubatch.n_tokens + i] = is_output;
  3020. if (is_output) { out_ids.push_back(id); }
  3021. }
  3022. } else {
  3023. // simple split
  3024. ubatch.output = batch->logits + seq.offset;
  3025. for (size_t i = 0; i < length; ++i) {
  3026. if (ubatch.output[i] != 0) { out_ids.push_back(seq.offset + i); }
  3027. }
  3028. }
  3029. } else {
  3030. // only get last output
  3031. for (size_t i = 0; i < length; ++i) {
  3032. size_t id = ids[seq.offset + i];
  3033. int8_t is_last = id == ids.size() - 1;
  3034. ubatch.output[ubatch.n_tokens + i] = is_last;
  3035. if (is_last) { out_ids.push_back(id); }
  3036. }
  3037. }
  3038. if (ubatch.n_tokens == 0 && ubatch.n_seqs == 0) {
  3039. ubatch.n_seq_tokens = ubatch.equal_seqs ? length : 1;
  3040. }
  3041. ubatch.n_tokens += length;
  3042. ubatch.n_seqs += ubatch.equal_seqs ? 1 : length; // virtual sequences for simple splits
  3043. seq.offset += length;
  3044. seq.length -= length;
  3045. n_tokens -= length;
  3046. GGML_ASSERT(ubatch.n_tokens == ubatch.n_seq_tokens * ubatch.n_seqs);
  3047. }
  3048. // simple split, unknown number of sequences of unequal lengths
  3049. llama_ubatch split_simple(size_t n_ubatch) {
  3050. n_ubatch = n_tokens < n_ubatch ? n_tokens : n_ubatch;
  3051. llama_ubatch ubatch = reserve_ubatch(n_ubatch, /* has_embd */ batch->embd != nullptr);
  3052. ubatch.equal_seqs = false;
  3053. if (!seq.empty()) {
  3054. llama_sbatch_seq & s = seq[0];
  3055. size_t length = s.length < n_ubatch ? s.length : n_ubatch;
  3056. GGML_ASSERT(seq.size() == 1 && s.n_seq_id == 0); // don't mix with other splits
  3057. add_seq_to_ubatch(ubatch, s, length);
  3058. }
  3059. return ubatch;
  3060. }
  3061. // make batches of equal-length sequences
  3062. llama_ubatch split_equal(size_t n_ubatch) {
  3063. n_ubatch = n_tokens < n_ubatch ? n_tokens : n_ubatch;
  3064. llama_ubatch ubatch = reserve_ubatch(n_ubatch, /* has_embd */ batch->embd != nullptr);
  3065. if (!seq.empty()) {
  3066. size_t length = 0;
  3067. size_t n_tokens_in_ubatch = 0;
  3068. GGML_ASSERT(seq[0].n_seq_id > 0); // should not be mixed with simple splits
  3069. // smallest first, because it's easier to split this way;
  3070. // starting from the end to pop in constant time.
  3071. for (size_t i = seq.size(); i-- > 0;) {
  3072. llama_sbatch_seq & s = seq[i];
  3073. GGML_ASSERT(s.length > 0);
  3074. if (length == 0) {
  3075. length = s.length < n_ubatch ? s.length : n_ubatch;
  3076. }
  3077. add_seq_to_ubatch(ubatch, s, length);
  3078. n_tokens_in_ubatch += length;
  3079. // shared prompts can't be mixed with any of their sequences,
  3080. // so it's safer to compute them in their own ubatch
  3081. if (s.n_seq_id > 1) { break; }
  3082. // stop when there isn't enough space for another sequence
  3083. if (length + n_tokens_in_ubatch > n_ubatch) { break; }
  3084. }
  3085. }
  3086. return ubatch;
  3087. }
  3088. // sequence-wise split
  3089. llama_ubatch split_seq(size_t n_ubatch) {
  3090. n_ubatch = n_tokens < n_ubatch ? n_tokens : n_ubatch;
  3091. llama_ubatch ubatch = reserve_ubatch(n_ubatch, /* has_embd */ batch->embd != nullptr);
  3092. if (!seq.empty()) {
  3093. llama_sbatch_seq & s = seq[seq.size() - 1];
  3094. size_t length = s.length < n_ubatch ? s.length : n_ubatch;
  3095. GGML_ASSERT(s.n_seq_id > 0); // should not be mixed with simple splits
  3096. add_seq_to_ubatch(ubatch, s, length);
  3097. }
  3098. return ubatch;
  3099. }
  3100. void from_batch(const llama_batch & batch, const size_t n_embd, const bool simple_split = false, const bool logits_all = false) {
  3101. GGML_ASSERT(batch.n_tokens >= 0);
  3102. this->batch = &batch;
  3103. this->n_embd = n_embd;
  3104. this->logits_all = logits_all;
  3105. n_tokens = batch.n_tokens;
  3106. ids.resize(n_tokens);
  3107. out_ids.clear();
  3108. // TODO: reserve out_ids and seq
  3109. for (size_t i = 0; i < n_tokens; ++i) {
  3110. ids[i] = i;
  3111. }
  3112. if (simple_split) {
  3113. seq.resize(1);
  3114. llama_sbatch_seq & s = seq[0];
  3115. s.n_seq_id = 0;
  3116. s.seq_id = nullptr;
  3117. s.offset = 0;
  3118. s.length = n_tokens;
  3119. return;
  3120. }
  3121. std::sort(ids.begin(), ids.end(),
  3122. [&batch](size_t a, size_t b) {
  3123. int32_t n_seq_a = batch.n_seq_id ? batch.n_seq_id[a] : 1;
  3124. int32_t n_seq_b = batch.n_seq_id ? batch.n_seq_id[b] : 1;
  3125. // sort by seq_id, then by pos
  3126. if (n_seq_a == n_seq_b) {
  3127. if (batch.seq_id) {
  3128. for (int32_t i = 0; i < n_seq_a; ++i) {
  3129. llama_seq_id seq_id_a = batch.seq_id[a][i];
  3130. llama_seq_id seq_id_b = batch.seq_id[b][i];
  3131. // smaller seq_ids go first
  3132. if (seq_id_a != seq_id_b) {
  3133. return seq_id_a < seq_id_b;
  3134. }
  3135. }
  3136. }
  3137. // when all else is equal, sort by pos
  3138. if (batch.pos) {
  3139. return batch.pos[a] < batch.pos[b];
  3140. }
  3141. // no pos, sort by id
  3142. return a < b;
  3143. }
  3144. // shared prompts go first
  3145. return n_seq_a > n_seq_b;
  3146. }
  3147. );
  3148. // init seq
  3149. llama_sbatch_seq * last_seq = nullptr;
  3150. for (size_t i = 0; i < n_tokens; ++i) {
  3151. const size_t bi = ids[i];
  3152. const int32_t n_seqs = batch.n_seq_id[bi];
  3153. llama_seq_id * seq_ids = batch.seq_id[bi];
  3154. if (last_seq != nullptr) {
  3155. bool same = n_seqs == last_seq->n_seq_id;
  3156. for (int32_t j = 0; same && j < n_seqs; ++j) {
  3157. if (seq_ids[j] != last_seq->seq_id[j]) {
  3158. same = false;
  3159. }
  3160. }
  3161. if (same) {
  3162. last_seq->length += 1;
  3163. continue;
  3164. }
  3165. }
  3166. llama_sbatch_seq new_seq = {n_seqs, seq_ids, i, 1};
  3167. seq.push_back(new_seq);
  3168. last_seq = &seq.back();
  3169. }
  3170. // keep shared prompts first at the end, then sort by length descending.
  3171. std::sort(seq.begin(), seq.end(),
  3172. [](llama_sbatch_seq & a, llama_sbatch_seq & b) {
  3173. if (a.n_seq_id == b.n_seq_id) {
  3174. return a.length > b.length;
  3175. }
  3176. return a.n_seq_id < b.n_seq_id;
  3177. }
  3178. );
  3179. }
  3180. };
  3181. struct llama_context {
  3182. llama_context(const llama_model & model)
  3183. : model(model)
  3184. , t_start_us(model.t_start_us)
  3185. , t_load_us(model.t_load_us) {}
  3186. const struct llama_model & model;
  3187. struct llama_cparams cparams;
  3188. struct llama_sbatch sbatch;
  3189. struct llama_kv_cache kv_self;
  3190. struct llama_control_vector cvec;
  3191. std::unordered_map<struct llama_lora_adapter *, float> lora_adapters;
  3192. std::vector<ggml_backend_ptr> backends;
  3193. std::vector<std::pair<ggml_backend_t, ggml_backend_set_n_threads_t>> set_n_threads_fns;
  3194. ggml_backend_t backend_cpu = nullptr;
  3195. ggml_threadpool_t threadpool = nullptr;
  3196. ggml_threadpool_t threadpool_batch = nullptr;
  3197. bool has_evaluated_once = false;
  3198. mutable int64_t t_start_us;
  3199. mutable int64_t t_load_us;
  3200. mutable int64_t t_p_eval_us = 0;
  3201. mutable int64_t t_eval_us = 0;
  3202. mutable int64_t t_compute_start_us = 0;
  3203. mutable int64_t n_queued_tokens = 0;
  3204. mutable int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  3205. mutable int32_t n_eval = 0; // number of eval calls
  3206. // host buffer for the model output (logits and embeddings)
  3207. ggml_backend_buffer_ptr buf_output;
  3208. // decode output (2-dimensional array: [n_outputs][n_vocab])
  3209. size_t logits_size = 0; // capacity (of floats) for logits
  3210. float * logits = nullptr;
  3211. std::vector<int32_t> output_ids; // map batch token positions to ids of the logits and embd buffers
  3212. size_t output_size = 0; // capacity (of tokens positions) for the output buffers
  3213. int32_t n_outputs = 0; // number of actually-used outputs in the current ubatch or last logical batch
  3214. bool logits_all = false;
  3215. // embeddings output (2-dimensional array: [n_outputs][n_embd])
  3216. // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE
  3217. size_t embd_size = 0; // capacity (of floats) for embeddings
  3218. float * embd = nullptr;
  3219. // sequence embeddings output (map of [n_embd] vectors)
  3220. // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE
  3221. std::map<llama_seq_id, std::vector<float>> embd_seq;
  3222. // whether we are computing encoder output or decoder output
  3223. bool is_encoding = false;
  3224. // TODO: find a better way to accommodate mutli-dimension position encoding methods
  3225. // number of position id each token get, 1 for each token in most cases.
  3226. // when using m-rope, it will be 3 position ids per token to representing 3 dimension coordinate.
  3227. int n_pos_per_token = 1;
  3228. // output of the encoder part of the encoder-decoder models
  3229. std::vector<float> embd_enc;
  3230. std::vector<std::set<llama_seq_id>> seq_ids_enc;
  3231. // memory buffers used to evaluate the model
  3232. std::vector<uint8_t> buf_compute_meta;
  3233. ggml_backend_sched_ptr sched;
  3234. ggml_abort_callback abort_callback = nullptr;
  3235. void * abort_callback_data = nullptr;
  3236. // input tensors
  3237. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  3238. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  3239. struct ggml_tensor * inp_pos; // I32 [n_batch]
  3240. struct ggml_tensor * inp_out_ids; // I32 [n_outputs]
  3241. struct ggml_tensor * inp_KQ_mask; // F32 [kv_size, n_batch]
  3242. struct ggml_tensor * inp_KQ_mask_swa; // F32 [kv_size, n_batch]
  3243. struct ggml_tensor * inp_K_shift; // I32 [kv_size]
  3244. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  3245. struct ggml_tensor * inp_cls; // I32 [n_batch]
  3246. struct ggml_tensor * inp_s_copy; // I32 [kv_size]
  3247. struct ggml_tensor * inp_s_mask; // F32 [1, n_kv]
  3248. struct ggml_tensor * inp_s_seq; // I32 [n_kv, n_batch]
  3249. struct ggml_tensor * inp_pos_bucket; // I32 [n_batch|n_kv, n_batch]
  3250. struct ggml_tensor * inp_embd_enc; // F32 [n_embd, n_outputs_enc]
  3251. struct ggml_tensor * inp_KQ_mask_cross; // F32 [n_outputs_enc, n_batch]
  3252. struct ggml_tensor * inp_cross_attn_state; // F32 [4, n_embd, 1061]
  3253. };
  3254. struct llama_lora_weight {
  3255. struct ggml_tensor * a = nullptr;
  3256. struct ggml_tensor * b = nullptr;
  3257. llama_lora_weight() = default;
  3258. llama_lora_weight(struct ggml_tensor * a, struct ggml_tensor * b): a(a), b(b) {}
  3259. };
  3260. struct llama_lora_adapter {
  3261. struct llama_model * base_model;
  3262. // map tensor name to lora_a_b
  3263. std::unordered_map<std::string, struct llama_lora_weight> ab_map;
  3264. std::vector<ggml_context_ptr> ctxs;
  3265. std::vector<ggml_backend_buffer_ptr> bufs;
  3266. float alpha;
  3267. llama_lora_adapter(struct llama_model * base_model): base_model(base_model) {
  3268. base_model->lora_adapters.insert(this);
  3269. }
  3270. llama_lora_weight * get_weight(struct ggml_tensor * w) {
  3271. std::string name(w->name);
  3272. auto pos = ab_map.find(name);
  3273. if (ab_map.find(name) != ab_map.end()) {
  3274. return &pos->second;
  3275. }
  3276. return nullptr;
  3277. }
  3278. ~llama_lora_adapter() {
  3279. auto pos = base_model->lora_adapters.find(this);
  3280. if (pos != base_model->lora_adapters.end()) {
  3281. base_model->lora_adapters.erase(pos);
  3282. }
  3283. }
  3284. };
  3285. static int llama_get_device_count(const llama_model & model) {
  3286. return (int) model.devices.size();
  3287. }
  3288. template<typename F>
  3289. static bool buft_supported(ggml_backend_buffer_type_t buft, ggml_backend_dev_t dev, F & fn) {
  3290. ggml_init_params params = {
  3291. /*.mem_size =*/ ggml_tensor_overhead()*8,
  3292. /*.mem_buffer =*/ NULL,
  3293. /*.no_alloc =*/ true,
  3294. };
  3295. ggml_context_ptr ctx { ggml_init(params) };
  3296. if (!ctx) {
  3297. throw std::runtime_error(format("failed to create ggml context"));
  3298. }
  3299. ggml_backend_buffer_ptr buf { ggml_backend_buft_alloc_buffer(buft, 0) };
  3300. ggml_tensor * op_tensor = fn(ctx.get());
  3301. for (int i = 0; i < GGML_MAX_SRC; i++) {
  3302. if (op_tensor->src[i] != nullptr) {
  3303. assert(op_tensor->src[i]->buffer == nullptr);
  3304. op_tensor->src[i]->buffer = buf.get();
  3305. }
  3306. }
  3307. bool op_supported = ggml_backend_dev_supports_op(dev, op_tensor);
  3308. return op_supported;
  3309. }
  3310. template<typename F>
  3311. static ggml_backend_buffer_type_t select_buft(const llama_model::buft_list_t & buft_list, const F & fn) {
  3312. for (const auto & cur : buft_list) {
  3313. ggml_backend_dev_t cur_dev = cur.first;
  3314. ggml_backend_buffer_type_t cur_buft = cur.second;
  3315. if (buft_supported(cur_buft, cur_dev, fn)) {
  3316. return cur_buft;
  3317. }
  3318. }
  3319. throw std::runtime_error(format("no suitable buffer type found"));
  3320. }
  3321. //
  3322. // kv cache helpers
  3323. //
  3324. static bool llama_kv_cache_init(
  3325. struct llama_kv_cache & cache,
  3326. const llama_context * ctx,
  3327. ggml_type type_k,
  3328. ggml_type type_v,
  3329. uint32_t kv_size,
  3330. bool offload) {
  3331. const llama_model & model = ctx->model;
  3332. const llama_cparams & cparams = ctx->cparams;
  3333. const struct llama_hparams & hparams = model.hparams;
  3334. const int64_t n_layer = hparams.n_layer;
  3335. cache.has_shift = false;
  3336. cache.recurrent = llama_model_is_recurrent(&model);
  3337. cache.v_trans = !cache.recurrent && !cparams.flash_attn;
  3338. cache.head = 0;
  3339. cache.size = kv_size;
  3340. cache.used = 0;
  3341. cache.type_k = type_k;
  3342. cache.type_v = type_v;
  3343. cache.cells.clear();
  3344. cache.cells.resize(kv_size);
  3345. // create a context for each buffer type
  3346. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3347. auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
  3348. auto it = ctx_map.find(buft);
  3349. if (it == ctx_map.end()) {
  3350. struct ggml_init_params params = {
  3351. /*.mem_size =*/ size_t(2u*n_layer*ggml_tensor_overhead()),
  3352. /*.mem_buffer =*/ NULL,
  3353. /*.no_alloc =*/ true,
  3354. };
  3355. ggml_context * ctx = ggml_init(params);
  3356. if (!ctx) {
  3357. return nullptr;
  3358. }
  3359. ctx_map[buft] = ctx;
  3360. cache.ctxs.emplace_back(ctx);
  3361. return ctx;
  3362. }
  3363. return it->second;
  3364. };
  3365. cache.k_l.reserve(n_layer);
  3366. cache.v_l.reserve(n_layer);
  3367. for (int i = 0; i < (int) n_layer; i++) {
  3368. // for cross attention layers
  3369. if (model.arch == LLM_ARCH_MLLAMA && hparams.cross_attention_layers(i)) {
  3370. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(i) + hparams.n_embd_k_s();
  3371. const llama_model::buft_list_t * buft_list;
  3372. if (offload) {
  3373. buft_list = model.dev_layer.at(i).buft_list;
  3374. } else {
  3375. buft_list = &model.cpu_buft_list;
  3376. }
  3377. ggml_backend_buffer_type_t buft = select_buft(*buft_list,
  3378. [&](ggml_context * ctx) {
  3379. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  3380. if (hparams.rope_type == LLAMA_ROPE_TYPE_NONE) {
  3381. return k;
  3382. }
  3383. ggml_tensor * p = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 1);
  3384. return ggml_rope(ctx, k, p, hparams.n_rot, hparams.rope_type);
  3385. });
  3386. ggml_context * ctx = ctx_for_buft(buft);
  3387. if (!ctx) {
  3388. LLAMA_LOG_ERROR("%s: failed to create ggml context for kv cache\n", __func__);
  3389. return false;
  3390. }
  3391. ggml_tensor * k = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, hparams.n_embd_head_k, 6404, hparams.n_head_kv(i));
  3392. ggml_tensor * v = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, hparams.n_embd_head_v, 6404, hparams.n_head_kv(i));
  3393. ggml_format_name(k, "cache_k_l%d", i);
  3394. ggml_format_name(v, "cache_v_l%d", i);
  3395. cache.k_l.push_back(k);
  3396. cache.v_l.push_back(v);
  3397. continue;
  3398. }
  3399. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(i) + hparams.n_embd_k_s();
  3400. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(i) + hparams.n_embd_v_s();
  3401. ggml_backend_buffer_type_t buft;
  3402. if (offload) {
  3403. auto * dev = model.dev_layer.at(i).dev;
  3404. buft = ggml_backend_dev_buffer_type(dev);
  3405. } else {
  3406. buft = ggml_backend_cpu_buffer_type();
  3407. }
  3408. ggml_context * ctx = ctx_for_buft(buft);
  3409. if (!ctx) {
  3410. LLAMA_LOG_ERROR("%s: failed to create ggml context for kv cache\n", __func__);
  3411. return false;
  3412. }
  3413. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  3414. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*kv_size);
  3415. ggml_format_name(k, "cache_k_l%d", i);
  3416. ggml_format_name(v, "cache_v_l%d", i);
  3417. cache.k_l.push_back(k);
  3418. cache.v_l.push_back(v);
  3419. }
  3420. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  3421. for (auto it : ctx_map) {
  3422. auto * buft = it.first;
  3423. auto * ctx = it.second;
  3424. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  3425. if (!buf) {
  3426. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  3427. return false;
  3428. }
  3429. ggml_backend_buffer_clear(buf, 0);
  3430. 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);
  3431. cache.bufs.emplace_back(buf);
  3432. }
  3433. return true;
  3434. }
  3435. // a structure holds information about the slot found in llama_kv_cache_find_slot
  3436. struct llama_kv_cache_slot_info {
  3437. std::pair<uint32_t, uint32_t> boundaries; // slot boundaries [begin, end)
  3438. bool found = false; // the slot was found
  3439. explicit llama_kv_cache_slot_info(bool found_) : found{found_} {}
  3440. llama_kv_cache_slot_info(uint32_t begin, uint32_t end) : boundaries{begin, end}, found{true} {}
  3441. operator bool() const { return found; }
  3442. };
  3443. static const llama_kv_cache_slot_info llama_kv_cache_slot_info_failed{false};
  3444. // find an empty slot of size "n_tokens" in the cache
  3445. // updates the cache head
  3446. // returns a structure holding information about the slot found
  3447. // Note: On success, it's important that cache.head points
  3448. // to the first cell of the slot.
  3449. static struct llama_kv_cache_slot_info llama_kv_cache_find_slot(
  3450. struct llama_kv_cache & cache,
  3451. const struct llama_ubatch & batch) {
  3452. const uint32_t n_tokens = batch.n_tokens;
  3453. const uint32_t n_seqs = batch.n_seqs;
  3454. const uint32_t n_seq_tokens = batch.n_seq_tokens;
  3455. if (cache.recurrent) {
  3456. // For recurrent state architectures (like Mamba or RWKV),
  3457. // each cache cell can store the state for a whole sequence.
  3458. // A slot should be always be contiguous.
  3459. // can only process batches with an equal number of new tokens in each sequence
  3460. GGML_ASSERT(batch.equal_seqs);
  3461. int32_t min = cache.size - 1;
  3462. int32_t max = 0;
  3463. // everything should fit if all seq_ids are smaller than the max
  3464. for (uint32_t s = 0; s < n_seqs; ++s) {
  3465. const uint32_t n_seq_id = batch.n_seq_id[s];
  3466. for (uint32_t j = 0; j < n_seq_id; ++j) {
  3467. const llama_seq_id seq_id = batch.seq_id[s][j];
  3468. if (seq_id < 0 || (uint32_t) seq_id >= cache.size) {
  3469. // too big seq_id
  3470. // TODO: would it be possible to resize the cache instead?
  3471. LLAMA_LOG_ERROR("%s: seq_id=%d >= n_seq_max=%d Try using a bigger --parallel value\n", __func__, seq_id, cache.size);
  3472. return llama_kv_cache_slot_info_failed;
  3473. }
  3474. if (j > 0) {
  3475. llama_kv_cell & seq = cache.cells[seq_id];
  3476. if (seq.tail >= 0) {
  3477. llama_kv_cell & cell = cache.cells[seq.tail];
  3478. // clear cells from seq_ids that become shared
  3479. // (should not normally happen, but let's handle it anyway)
  3480. cell.seq_id.erase(seq_id);
  3481. seq.tail = -1;
  3482. if (cell.seq_id.empty()) {
  3483. cell.pos = -1;
  3484. cell.src = -1;
  3485. cache.used -= 1;
  3486. }
  3487. }
  3488. }
  3489. }
  3490. }
  3491. #ifndef NDEBUG
  3492. {
  3493. std::vector<int32_t> tails_verif;
  3494. tails_verif.assign(cache.size, -1);
  3495. for (uint32_t i = 0; i < cache.size; ++i) {
  3496. llama_kv_cell & cell = cache.cells[i];
  3497. for (llama_seq_id seq_id : cell.seq_id) {
  3498. if (tails_verif[seq_id] != -1) {
  3499. LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tails_verif[seq_id]);
  3500. }
  3501. tails_verif[seq_id] = i;
  3502. }
  3503. }
  3504. for (uint32_t i = 0; i < cache.size; ++i) {
  3505. if (tails_verif[i] != cache.cells[i].tail) {
  3506. LLAMA_LOG_ERROR("%s: wrong tail for seq_id %d, (%d instead of %d)\n", __func__, i, cache.cells[i].tail, tails_verif[i]);
  3507. }
  3508. }
  3509. }
  3510. #endif
  3511. // find next empty cell
  3512. uint32_t next_empty_cell = cache.head;
  3513. for (uint32_t i = 0; i < cache.size; ++i) {
  3514. if (next_empty_cell >= cache.size) { next_empty_cell -= cache.size; }
  3515. llama_kv_cell & cell = cache.cells[next_empty_cell];
  3516. if (cell.is_empty()) { break; }
  3517. next_empty_cell += 1;
  3518. }
  3519. // find usable cell range
  3520. for (uint32_t s = 0; s < n_seqs; ++s) {
  3521. const llama_seq_id seq_id = batch.seq_id[s][0];
  3522. llama_kv_cell & seq_meta = cache.cells[seq_id];
  3523. bool has_cell = false;
  3524. if (seq_meta.tail >= 0) {
  3525. llama_kv_cell & cell = cache.cells[seq_meta.tail];
  3526. GGML_ASSERT(cell.has_seq_id(seq_id));
  3527. // does this seq_id "own" the cell?
  3528. if (cell.seq_id.size() == 1) { has_cell = true; }
  3529. }
  3530. if (!has_cell) {
  3531. llama_kv_cell & empty_cell = cache.cells[next_empty_cell];
  3532. GGML_ASSERT(empty_cell.is_empty());
  3533. // copy old tail into the empty cell
  3534. if (seq_meta.tail >= 0) {
  3535. llama_kv_cell & orig_cell = cache.cells[seq_meta.tail];
  3536. empty_cell.pos = orig_cell.pos;
  3537. empty_cell.src = orig_cell.src;
  3538. orig_cell.seq_id.erase(seq_id);
  3539. empty_cell.seq_id.insert(seq_id); // will be overwritten
  3540. }
  3541. seq_meta.tail = next_empty_cell;
  3542. // find next empty cell
  3543. if (s + 1 < n_seqs) {
  3544. next_empty_cell += 1;
  3545. for (uint32_t i = 0; i < cache.size; ++i) {
  3546. if (next_empty_cell >= cache.size) { next_empty_cell -= cache.size; }
  3547. llama_kv_cell & cell = cache.cells[next_empty_cell];
  3548. if (cell.is_empty()) { break; }
  3549. next_empty_cell += 1;
  3550. }
  3551. }
  3552. }
  3553. if (min > seq_meta.tail) { min = seq_meta.tail; }
  3554. if (max < seq_meta.tail) { max = seq_meta.tail; }
  3555. }
  3556. // gather and re-order
  3557. for (uint32_t s = 0; s < n_seqs; ++s) {
  3558. int32_t dst_id = s + min;
  3559. int32_t src_id = cache.cells[batch.seq_id[s][0]].tail;
  3560. if (dst_id != src_id) {
  3561. llama_kv_cell & dst_cell = cache.cells[dst_id];
  3562. llama_kv_cell & src_cell = cache.cells[src_id];
  3563. std::swap(dst_cell.pos, src_cell.pos);
  3564. std::swap(dst_cell.src, src_cell.src);
  3565. std::swap(dst_cell.seq_id, src_cell.seq_id);
  3566. // swap tails (assuming they NEVER overlap)
  3567. for (const llama_seq_id seq_id : src_cell.seq_id) {
  3568. cache.cells[seq_id].tail = src_id;
  3569. }
  3570. for (const llama_seq_id seq_id : dst_cell.seq_id) {
  3571. cache.cells[seq_id].tail = dst_id;
  3572. }
  3573. }
  3574. }
  3575. // update the pos of the used seqs
  3576. for (uint32_t s = 0; s < n_seqs; ++s) {
  3577. const llama_pos last_pos = batch.pos[n_seq_tokens * s + n_seq_tokens - 1];
  3578. int32_t cell_id = s + min;
  3579. llama_kv_cell & cell = cache.cells[cell_id];
  3580. if (cell.pos >= 0 && last_pos != cell.pos + (llama_pos) n_seq_tokens) {
  3581. // What should happen when the pos backtracks or skips a value?
  3582. // Clearing the state mid-batch would require special-casing which isn't done.
  3583. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d with %u new tokens\n",
  3584. __func__, last_pos, cell.pos, batch.seq_id[s][0], n_seq_tokens);
  3585. }
  3586. cell.pos = last_pos;
  3587. cell.seq_id.clear();
  3588. for (int32_t j = 0; j < batch.n_seq_id[s]; ++j) {
  3589. const llama_seq_id seq_id = batch.seq_id[s][j];
  3590. cell.seq_id.insert(seq_id);
  3591. cache.cells[seq_id].tail = cell_id;
  3592. }
  3593. }
  3594. // allow getting the range of used cells, from head to head + n
  3595. cache.head = min;
  3596. cache.n = max - min + 1;
  3597. cache.used = std::count_if(cache.cells.begin(), cache.cells.end(),
  3598. [](const llama_kv_cell& cell){ return !cell.is_empty(); });
  3599. // sanity check
  3600. return llama_kv_cache_slot_info(cache.n >= n_seqs);
  3601. }
  3602. // otherwise, one cell per token.
  3603. if (n_tokens > cache.size) {
  3604. LLAMA_LOG_ERROR("%s: n_tokens=%d > cache.size=%d\n", __func__, n_tokens, cache.size);
  3605. return llama_kv_cache_slot_info_failed;
  3606. }
  3607. uint32_t n_tested = 0;
  3608. while (true) {
  3609. if (cache.head + n_tokens > cache.size) {
  3610. n_tested += cache.size - cache.head;
  3611. cache.head = 0;
  3612. continue;
  3613. }
  3614. bool found = true;
  3615. for (uint32_t i = 0; i < n_tokens; i++) {
  3616. if (cache.cells[cache.head + i].pos >= 0) {
  3617. found = false;
  3618. cache.head += i + 1;
  3619. n_tested += i + 1;
  3620. break;
  3621. }
  3622. }
  3623. if (found) {
  3624. break;
  3625. }
  3626. if (n_tested >= cache.size) {
  3627. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  3628. return llama_kv_cache_slot_info_failed;
  3629. }
  3630. }
  3631. for (uint32_t s = 0; s < n_seqs; s++) {
  3632. for (uint32_t i = 0; i < n_seq_tokens; ++i) {
  3633. uint32_t k = s*n_seq_tokens + i;
  3634. cache.cells[cache.head + k].pos = batch.pos[k];
  3635. for (int32_t j = 0; j < batch.n_seq_id[s]; j++) {
  3636. cache.cells[cache.head + k].seq_id.insert(batch.seq_id[s][j]);
  3637. }
  3638. }
  3639. }
  3640. cache.used += n_tokens;
  3641. return llama_kv_cache_slot_info(cache.head, cache.head + n_tokens);
  3642. }
  3643. // find how many cells are currently in use
  3644. static uint32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  3645. for (uint32_t i = cache.size; i > 0; --i) {
  3646. const llama_kv_cell & cell = cache.cells[i - 1];
  3647. if (cell.pos >= 0 && !cell.is_empty()) {
  3648. return i;
  3649. }
  3650. }
  3651. return 0;
  3652. }
  3653. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  3654. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  3655. cache.cells[i].pos = -1;
  3656. cache.cells[i].seq_id.clear();
  3657. cache.cells[i].src = -1;
  3658. cache.cells[i].tail = -1;
  3659. }
  3660. cache.head = 0;
  3661. cache.used = 0;
  3662. for (auto & buf : cache.bufs) {
  3663. ggml_backend_buffer_clear(buf.get(), 0);
  3664. }
  3665. }
  3666. static bool llama_kv_cache_seq_rm(
  3667. struct llama_kv_cache & cache,
  3668. llama_seq_id seq_id,
  3669. llama_pos p0,
  3670. llama_pos p1) {
  3671. uint32_t new_head = cache.size;
  3672. if (p0 < 0) p0 = 0;
  3673. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3674. // models like Mamba or RWKV can't have a state partially erased
  3675. if (cache.recurrent) {
  3676. if (seq_id >= (int64_t) cache.size) {
  3677. // could be fatal
  3678. return false;
  3679. }
  3680. if (0 <= seq_id) {
  3681. int32_t & tail_id = cache.cells[seq_id].tail;
  3682. if (tail_id >= 0) {
  3683. const llama_kv_cell & cell = cache.cells[tail_id];
  3684. // partial intersection is invalid
  3685. if ((0 < p0 && p0 <= cell.pos) || (0 < p1 && p1 <= cell.pos)) {
  3686. return false;
  3687. }
  3688. // invalidate tails which will be cleared
  3689. if (p0 <= cell.pos && cell.pos < p1) {
  3690. tail_id = -1;
  3691. }
  3692. }
  3693. } else {
  3694. // seq_id is negative, then the range should include everything or nothing
  3695. if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
  3696. return false;
  3697. }
  3698. }
  3699. }
  3700. for (uint32_t i = 0; i < cache.size; ++i) {
  3701. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3702. if (seq_id < 0) {
  3703. cache.cells[i].seq_id.clear();
  3704. } else if (cache.cells[i].has_seq_id(seq_id)) {
  3705. cache.cells[i].seq_id.erase(seq_id);
  3706. } else {
  3707. continue;
  3708. }
  3709. if (cache.cells[i].is_empty()) {
  3710. // keep count of the number of used cells
  3711. if (cache.cells[i].pos >= 0) cache.used--;
  3712. cache.cells[i].pos = -1;
  3713. cache.cells[i].src = -1;
  3714. if (new_head == cache.size) new_head = i;
  3715. }
  3716. }
  3717. }
  3718. // If we freed up a slot, set head to it so searching can start there.
  3719. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  3720. return true;
  3721. }
  3722. static void llama_kv_cache_seq_cp(
  3723. struct llama_kv_cache & cache,
  3724. llama_seq_id seq_id_src,
  3725. llama_seq_id seq_id_dst,
  3726. llama_pos p0,
  3727. llama_pos p1) {
  3728. if (p0 < 0) p0 = 0;
  3729. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3730. if (cache.recurrent) {
  3731. if ((uint32_t) seq_id_dst < cache.size && (uint32_t) seq_id_src < cache.size) {
  3732. llama_kv_cell & tail_src = cache.cells[seq_id_src];
  3733. llama_kv_cell & tail_dst = cache.cells[seq_id_dst];
  3734. if (tail_dst.tail >= 0) {
  3735. // clear destination seq_id if it wasn't empty
  3736. llama_kv_cell & cell_dst = cache.cells[tail_dst.tail];
  3737. cell_dst.seq_id.erase(seq_id_dst);
  3738. tail_dst.tail = -1;
  3739. if (cell_dst.seq_id.empty()) {
  3740. cell_dst.pos = -1;
  3741. cell_dst.delta = -1;
  3742. cell_dst.src = -1;
  3743. cache.used -= 1;
  3744. }
  3745. }
  3746. if (tail_src.tail >= 0) {
  3747. llama_kv_cell & cell_src = cache.cells[tail_src.tail];
  3748. cell_src.seq_id.insert(seq_id_dst);
  3749. tail_dst.tail = tail_src.tail;
  3750. }
  3751. }
  3752. return;
  3753. }
  3754. // otherwise, this is the KV cache of a Transformer-like model
  3755. cache.head = 0;
  3756. for (uint32_t i = 0; i < cache.size; ++i) {
  3757. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3758. cache.cells[i].seq_id.insert(seq_id_dst);
  3759. }
  3760. }
  3761. }
  3762. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  3763. uint32_t new_head = cache.size;
  3764. for (uint32_t i = 0; i < cache.size; ++i) {
  3765. if (cache.recurrent && (llama_seq_id) i != seq_id) {
  3766. cache.cells[i].tail = -1;
  3767. }
  3768. if (!cache.cells[i].has_seq_id(seq_id)) {
  3769. if (cache.cells[i].pos >= 0) cache.used--;
  3770. cache.cells[i].pos = -1;
  3771. cache.cells[i].src = -1;
  3772. cache.cells[i].seq_id.clear();
  3773. if (new_head == cache.size) new_head = i;
  3774. } else {
  3775. cache.cells[i].seq_id.clear();
  3776. cache.cells[i].seq_id.insert(seq_id);
  3777. }
  3778. }
  3779. // If we freed up a slot, set head to it so searching can start there.
  3780. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  3781. }
  3782. static void llama_kv_cache_seq_add(
  3783. struct llama_kv_cache & cache,
  3784. llama_seq_id seq_id,
  3785. llama_pos p0,
  3786. llama_pos p1,
  3787. llama_pos delta) {
  3788. uint32_t new_head = cache.size;
  3789. if (p0 < 0) p0 = 0;
  3790. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3791. // If there is no range then return early to avoid looping over the cache.
  3792. if (p0 == p1) return;
  3793. if (cache.recurrent) {
  3794. // for Mamba-like or RWKV models, only the pos needs to be shifted
  3795. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  3796. const int32_t tail_id = cache.cells[seq_id].tail;
  3797. if (tail_id >= 0) {
  3798. llama_kv_cell & cell = cache.cells[tail_id];
  3799. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  3800. cell.pos += delta;
  3801. }
  3802. }
  3803. }
  3804. return;
  3805. }
  3806. for (uint32_t i = 0; i < cache.size; ++i) {
  3807. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3808. cache.has_shift = true;
  3809. cache.cells[i].pos += delta;
  3810. cache.cells[i].delta += delta;
  3811. if (cache.cells[i].pos < 0) {
  3812. if (!cache.cells[i].is_empty()) {
  3813. cache.used--;
  3814. }
  3815. cache.cells[i].pos = -1;
  3816. cache.cells[i].seq_id.clear();
  3817. if (new_head == cache.size) {
  3818. new_head = i;
  3819. }
  3820. }
  3821. }
  3822. }
  3823. // If we freed up a slot, set head to it so searching can start there.
  3824. // Otherwise we just start the next search from the beginning.
  3825. cache.head = new_head != cache.size ? new_head : 0;
  3826. }
  3827. static void llama_kv_cache_seq_div(
  3828. struct llama_kv_cache & cache,
  3829. llama_seq_id seq_id,
  3830. llama_pos p0,
  3831. llama_pos p1,
  3832. int d) {
  3833. if (p0 < 0) p0 = 0;
  3834. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3835. // If there is no range then return early to avoid looping over the cache.
  3836. if (p0 == p1) return;
  3837. if (cache.recurrent) {
  3838. // for Mamba-like or RWKV models, only the pos needs to be changed
  3839. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  3840. const int32_t tail_id = cache.cells[seq_id].tail;
  3841. if (tail_id >= 0) {
  3842. llama_kv_cell & cell = cache.cells[tail_id];
  3843. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  3844. cell.pos /= d;
  3845. }
  3846. }
  3847. }
  3848. return;
  3849. }
  3850. for (uint32_t i = 0; i < cache.size; ++i) {
  3851. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3852. cache.has_shift = true;
  3853. {
  3854. llama_pos p_old = cache.cells[i].pos;
  3855. cache.cells[i].pos /= d;
  3856. cache.cells[i].delta += cache.cells[i].pos - p_old;
  3857. }
  3858. }
  3859. }
  3860. }
  3861. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  3862. llama_pos result = 0;
  3863. for (uint32_t i = 0; i < cache.size; ++i) {
  3864. if (cache.cells[i].has_seq_id(seq_id)) {
  3865. result = std::max(result, cache.cells[i].pos);
  3866. }
  3867. }
  3868. return result;
  3869. }
  3870. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  3871. if (!cache.recurrent) {
  3872. cache.do_defrag = true;
  3873. }
  3874. }
  3875. static uint32_t llama_kv_cache_get_padding(const struct llama_cparams & cparams) {
  3876. // the FA kernels require padding to avoid extra runtime boundary checks
  3877. return cparams.flash_attn ? 256u : 32u;
  3878. }
  3879. // saves the kv_cache state for future recovery.
  3880. // used to rollback llama_kv_cache_find_slot changes.
  3881. struct llama_kv_slot_restorer {
  3882. struct llama_kv_cache_state {
  3883. uint32_t head = 0;
  3884. uint32_t n = 0;
  3885. } old_state;
  3886. // for non-recurrent models only
  3887. // list of slots to restore
  3888. std::vector<std::pair<uint32_t, uint32_t>> slot_boundaries;
  3889. bool do_restore = false;
  3890. explicit llama_kv_slot_restorer(const struct llama_kv_cache & cache) {
  3891. old_state.head = cache.head;
  3892. old_state.n = cache.n;
  3893. }
  3894. // saves a slot information for future restoration
  3895. void save(const struct llama_kv_cache_slot_info & slot) {
  3896. if (slot) {
  3897. do_restore = true;
  3898. if (slot.boundaries.first != slot.boundaries.second) {
  3899. slot_boundaries.push_back(slot.boundaries);
  3900. }
  3901. }
  3902. }
  3903. // must be explicitly called to restore the kv_cache state
  3904. // and rollback changes from all llama_kv_cache_find_slot calls
  3905. void restore(struct llama_kv_cache & cache) {
  3906. if (do_restore) {
  3907. cache.head = old_state.head;
  3908. cache.n = old_state.n;
  3909. if (cache.recurrent) { // recurrent models like Mamba or RWKV can't have a state partially erased
  3910. llama_kv_cache_seq_rm(cache, -1, -1, -1);
  3911. } else {
  3912. for (auto & slot : slot_boundaries) {
  3913. llama_kv_cache_seq_rm(cache, -1, slot.first, slot.second);
  3914. }
  3915. }
  3916. }
  3917. }
  3918. };
  3919. //
  3920. // model loading and saving
  3921. //
  3922. enum llama_fver {
  3923. GGUF_FILE_VERSION_V1 = 1,
  3924. GGUF_FILE_VERSION_V2 = 2,
  3925. GGUF_FILE_VERSION_V3 = 3,
  3926. };
  3927. static const char * llama_file_version_name(llama_fver version) {
  3928. switch (version) {
  3929. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  3930. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  3931. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  3932. }
  3933. return "unknown";
  3934. }
  3935. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  3936. char buf[256];
  3937. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  3938. for (size_t i = 1; i < ne.size(); i++) {
  3939. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  3940. }
  3941. return buf;
  3942. }
  3943. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  3944. char buf[256];
  3945. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  3946. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  3947. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  3948. }
  3949. return buf;
  3950. }
  3951. namespace GGUFMeta {
  3952. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  3953. struct GKV_Base_Type {
  3954. static constexpr gguf_type gt = gt_;
  3955. static T getter(const gguf_context * ctx, const int kid) {
  3956. return gfun(ctx, kid);
  3957. }
  3958. };
  3959. template<typename T> struct GKV_Base;
  3960. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  3961. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  3962. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  3963. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  3964. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  3965. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  3966. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  3967. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  3968. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  3969. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  3970. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  3971. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  3972. template<> struct GKV_Base<std::string> {
  3973. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  3974. static std::string getter(const gguf_context * ctx, const int kid) {
  3975. return gguf_get_val_str(ctx, kid);
  3976. }
  3977. };
  3978. struct ArrayInfo {
  3979. const gguf_type gt;
  3980. const size_t length;
  3981. const void * data;
  3982. };
  3983. template<> struct GKV_Base<ArrayInfo> {
  3984. public:
  3985. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  3986. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  3987. return ArrayInfo {
  3988. gguf_get_arr_type(ctx, k),
  3989. size_t(gguf_get_arr_n(ctx, k)),
  3990. gguf_get_arr_data(ctx, k),
  3991. };
  3992. }
  3993. };
  3994. template<typename T>
  3995. class GKV : public GKV_Base<T> {
  3996. GKV() = delete;
  3997. public:
  3998. static T get_kv(const gguf_context * ctx, const int k) {
  3999. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  4000. if (kt != GKV::gt) {
  4001. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  4002. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  4003. }
  4004. return GKV::getter(ctx, k);
  4005. }
  4006. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  4007. switch (ty) {
  4008. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  4009. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  4010. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  4011. case LLAMA_KV_OVERRIDE_TYPE_STR: return "str";
  4012. }
  4013. return "unknown";
  4014. }
  4015. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  4016. if (!ovrd) { return false; }
  4017. if (ovrd->tag == expected_type) {
  4018. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  4019. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  4020. switch (ovrd->tag) {
  4021. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  4022. LLAMA_LOG_INFO("%s\n", ovrd->val_bool ? "true" : "false");
  4023. } break;
  4024. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  4025. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->val_i64);
  4026. } break;
  4027. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  4028. LLAMA_LOG_INFO("%.6f\n", ovrd->val_f64);
  4029. } break;
  4030. case LLAMA_KV_OVERRIDE_TYPE_STR: {
  4031. LLAMA_LOG_INFO("%s\n", ovrd->val_str);
  4032. } break;
  4033. default:
  4034. // Shouldn't be possible to end up here, but just in case...
  4035. throw std::runtime_error(
  4036. format("Unsupported attempt to override %s type for metadata key %s\n",
  4037. override_type_to_str(ovrd->tag), ovrd->key));
  4038. }
  4039. return true;
  4040. }
  4041. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  4042. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  4043. return false;
  4044. }
  4045. template<typename OT>
  4046. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  4047. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  4048. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  4049. target = ovrd->val_bool;
  4050. return true;
  4051. }
  4052. return false;
  4053. }
  4054. template<typename OT>
  4055. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  4056. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  4057. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  4058. target = ovrd->val_i64;
  4059. return true;
  4060. }
  4061. return false;
  4062. }
  4063. template<typename OT>
  4064. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  4065. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  4066. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  4067. target = ovrd->val_f64;
  4068. return true;
  4069. }
  4070. return false;
  4071. }
  4072. template<typename OT>
  4073. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  4074. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  4075. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_STR, ovrd)) {
  4076. target = ovrd->val_str;
  4077. return true;
  4078. }
  4079. return false;
  4080. }
  4081. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  4082. if (try_override<T>(target, ovrd)) {
  4083. return true;
  4084. }
  4085. if (k < 0) { return false; }
  4086. target = get_kv(ctx, k);
  4087. return true;
  4088. }
  4089. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  4090. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  4091. }
  4092. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  4093. return set(ctx, key.c_str(), target, ovrd);
  4094. }
  4095. };
  4096. }
  4097. using llama_buf_map = std::unordered_map<uint32_t, ggml_backend_buffer_t>;
  4098. static size_t llama_model_max_nodes(const llama_model & model) {
  4099. return std::max<size_t>(8192, model.tensors_by_name.size()*5);
  4100. }
  4101. struct llama_model_loader {
  4102. int n_kv = 0;
  4103. int n_tensors = 0;
  4104. int n_created = 0;
  4105. uint64_t n_elements = 0;
  4106. size_t n_bytes = 0;
  4107. bool use_mmap = false;
  4108. bool check_tensors;
  4109. llama_files files;
  4110. llama_ftype ftype;
  4111. llama_fver fver;
  4112. llama_mmaps mappings;
  4113. // Holds information on a model weight
  4114. struct llama_tensor_weight {
  4115. uint16_t idx; // source file index
  4116. size_t offs; // tensor data offset in the original file
  4117. ggml_tensor * tensor;
  4118. llama_tensor_weight(const llama_file * file, uint16_t idx, const struct gguf_context * gguf_ctx, ggml_tensor * tensor) : idx(idx), tensor(tensor) {
  4119. const int tensor_idx = gguf_find_tensor(gguf_ctx, ggml_get_name(tensor));
  4120. if (tensor_idx < 0) {
  4121. throw std::runtime_error(format("tensor '%s' not found in the model", ggml_get_name(tensor)));
  4122. }
  4123. offs = gguf_get_data_offset(gguf_ctx) + gguf_get_tensor_offset(gguf_ctx, tensor_idx);
  4124. if (offs + ggml_nbytes(tensor) < offs || offs + ggml_nbytes(tensor) > file->size) {
  4125. throw std::runtime_error(format("tensor '%s' data is not within the file bounds, model is corrupted or incomplete", ggml_get_name(tensor)));
  4126. }
  4127. }
  4128. };
  4129. // custom comparator to sort weights more nicely by layer
  4130. struct weight_name_comparer {
  4131. bool operator()(const std::string & a, const std::string & b) const {
  4132. int a_layer = -1;
  4133. int b_layer = -1;
  4134. sscanf(a.c_str(), "blk.%d.", &a_layer);
  4135. sscanf(b.c_str(), "blk.%d.", &b_layer);
  4136. if (a_layer != b_layer) {
  4137. return a_layer < b_layer;
  4138. }
  4139. return a < b;
  4140. }
  4141. };
  4142. std::map<std::string, struct llama_tensor_weight, weight_name_comparer> weights_map;
  4143. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  4144. gguf_context_ptr meta;
  4145. std::vector<ggml_context_ptr> contexts;
  4146. std::string arch_name;
  4147. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  4148. llama_model_loader(const std::string & fname, bool use_mmap, bool check_tensors, const struct llama_model_kv_override * param_overrides_p) {
  4149. int trace = 0;
  4150. if (getenv("LLAMA_TRACE")) {
  4151. trace = atoi(getenv("LLAMA_TRACE"));
  4152. }
  4153. if (param_overrides_p != nullptr) {
  4154. for (const struct llama_model_kv_override * p = param_overrides_p; p->key[0] != 0; p++) {
  4155. kv_overrides.insert({std::string(p->key), *p});
  4156. }
  4157. }
  4158. struct ggml_context * ctx = NULL;
  4159. struct gguf_init_params params = {
  4160. /*.no_alloc = */ true,
  4161. /*.ctx = */ &ctx,
  4162. };
  4163. meta.reset(gguf_init_from_file(fname.c_str(), params));
  4164. if (!meta) {
  4165. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  4166. }
  4167. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  4168. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  4169. files.emplace_back(new llama_file(fname.c_str(), "rb"));
  4170. contexts.emplace_back(ctx);
  4171. // Save tensors data offset of the main file.
  4172. // For subsidiary files, `meta` tensor data offset must not be used,
  4173. // so we build a unified tensors index for weights.
  4174. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  4175. std::string tensor_name = std::string(cur->name);
  4176. // make sure there is no duplicated tensor names
  4177. if (weights_map.find(tensor_name) != weights_map.end()) {
  4178. throw std::runtime_error(format("invalid model: tensor '%s' is duplicated", ggml_get_name(cur)));
  4179. }
  4180. n_elements += ggml_nelements(cur);
  4181. n_bytes += ggml_nbytes(cur);
  4182. weights_map.emplace(tensor_name, llama_tensor_weight(files.back().get(), 0, meta.get(), cur));
  4183. }
  4184. uint16_t n_split = 0;
  4185. get_key(llm_kv(LLM_KV_SPLIT_COUNT), n_split, false);
  4186. // Load additional GGML contexts
  4187. if (n_split > 1) {
  4188. uint16_t idx = 0;
  4189. get_key(llm_kv(LLM_KV_SPLIT_NO), idx);
  4190. if (idx != 0) {
  4191. throw std::runtime_error(format("illegal split file: %d, model must be loaded with the first split", idx));
  4192. }
  4193. char split_prefix[PATH_MAX] = {0};
  4194. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), fname.c_str(), idx, n_split)) {
  4195. throw std::runtime_error(format("invalid split file: %s", fname.c_str()));
  4196. }
  4197. if (trace > 0) {
  4198. LLAMA_LOG_INFO("%s: loading additional %d GGUFs\n", __func__, n_split);
  4199. }
  4200. char split_path[PATH_MAX] = {0};
  4201. for (idx = 1; idx < n_split; idx++) {
  4202. llama_split_path(split_path, sizeof(split_path), split_prefix, idx, n_split);
  4203. struct gguf_init_params split_params = {
  4204. /*.no_alloc = */ true,
  4205. /*.ctx = */ &ctx,
  4206. };
  4207. gguf_context_ptr ctx_gguf { gguf_init_from_file(split_path, split_params) };
  4208. if (!ctx_gguf) {
  4209. throw std::runtime_error(format("%s: failed to load GGUF split from %s\n", __func__, split_path));
  4210. }
  4211. files.emplace_back(new llama_file(split_path, "rb"));
  4212. contexts.emplace_back(ctx);
  4213. // Save tensors data offset info of the shard.
  4214. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  4215. std::string tensor_name = std::string(cur->name);
  4216. // make sure there is no duplicated tensor names
  4217. if (weights_map.find(tensor_name) != weights_map.end()) {
  4218. throw std::runtime_error(format("invalid model: tensor '%s' is duplicated", ggml_get_name(cur)));
  4219. }
  4220. n_elements += ggml_nelements(cur);
  4221. n_bytes += ggml_nbytes(cur);
  4222. weights_map.emplace(tensor_name, llama_tensor_weight(files.back().get(), idx, ctx_gguf.get(), cur));
  4223. }
  4224. }
  4225. get_key(llm_kv(LLM_KV_SPLIT_TENSORS_COUNT), n_tensors);
  4226. // sanity check
  4227. {
  4228. const int n_tensors_loaded = (int) weights_map.size();
  4229. if (n_tensors != n_tensors_loaded) {
  4230. throw std::runtime_error(format("corrupted model: %d tensors expected but %d found", n_tensors, n_tensors_loaded));
  4231. }
  4232. }
  4233. LLAMA_LOG_INFO("%s: additional %d GGUFs metadata loaded.\n", __func__, n_split - 1);
  4234. }
  4235. n_kv = gguf_get_n_kv(meta.get());
  4236. n_tensors = weights_map.size();
  4237. fver = (enum llama_fver) gguf_get_version(meta.get());
  4238. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  4239. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  4240. // determine file type based on the number of tensors for each quantization and print meta data
  4241. // TODO: make optional
  4242. {
  4243. std::map<enum ggml_type, uint32_t> n_type;
  4244. uint32_t n_type_max = 0;
  4245. enum ggml_type type_max = GGML_TYPE_F32;
  4246. for (const auto & it : weights_map) {
  4247. const llama_tensor_weight & w = it.second;
  4248. const ggml_tensor * tensor = w.tensor;
  4249. enum ggml_type type = tensor->type;
  4250. n_type[type]++;
  4251. if (n_type_max < n_type[type]) {
  4252. n_type_max = n_type[type];
  4253. type_max = type;
  4254. }
  4255. if (trace > 0) {
  4256. const uint16_t sid = w.idx;
  4257. 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());
  4258. }
  4259. }
  4260. switch (type_max) {
  4261. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  4262. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  4263. case GGML_TYPE_BF16: ftype = LLAMA_FTYPE_MOSTLY_BF16; break;
  4264. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  4265. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  4266. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  4267. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  4268. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  4269. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  4270. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  4271. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  4272. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  4273. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  4274. case GGML_TYPE_TQ1_0: ftype = LLAMA_FTYPE_MOSTLY_TQ1_0; break;
  4275. case GGML_TYPE_TQ2_0: ftype = LLAMA_FTYPE_MOSTLY_TQ2_0; break;
  4276. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  4277. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  4278. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  4279. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  4280. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  4281. case GGML_TYPE_IQ1_M: ftype = LLAMA_FTYPE_MOSTLY_IQ1_M; break;
  4282. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  4283. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  4284. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  4285. default:
  4286. {
  4287. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  4288. ftype = LLAMA_FTYPE_ALL_F32;
  4289. } break;
  4290. }
  4291. // this is a way to mark that we have "guessed" the file type
  4292. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  4293. {
  4294. const int kid = gguf_find_key(meta.get(), "general.file_type"); // TODO: use LLM_KV
  4295. if (kid >= 0) {
  4296. ftype = (llama_ftype) gguf_get_val_u32(meta.get(), kid);
  4297. }
  4298. }
  4299. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  4300. for (int i = 0; i < n_kv; i++) {
  4301. const char * name = gguf_get_key(meta.get(), i);
  4302. const enum gguf_type type = gguf_get_kv_type(meta.get(), i);
  4303. const std::string type_name =
  4304. type == GGUF_TYPE_ARRAY
  4305. ? 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))
  4306. : gguf_type_name(type);
  4307. std::string value = gguf_kv_to_str(meta.get(), i);
  4308. const size_t MAX_VALUE_LEN = 40;
  4309. if (value.size() > MAX_VALUE_LEN) {
  4310. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  4311. }
  4312. replace_all(value, "\n", "\\n");
  4313. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  4314. }
  4315. // print type counts
  4316. for (auto & kv : n_type) {
  4317. if (kv.second == 0) {
  4318. continue;
  4319. }
  4320. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  4321. }
  4322. }
  4323. if (!llama_mmap::SUPPORTED) {
  4324. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  4325. use_mmap = false;
  4326. }
  4327. this->use_mmap = use_mmap;
  4328. this->check_tensors = check_tensors;
  4329. }
  4330. template<typename T>
  4331. typename std::enable_if<std::is_integral<T>::value, bool>::type
  4332. get_arr_n(const std::string & key, T & result, const bool required = true) {
  4333. const int kid = gguf_find_key(meta.get(), key.c_str());
  4334. if (kid < 0) {
  4335. if (required) {
  4336. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  4337. }
  4338. return false;
  4339. }
  4340. struct GGUFMeta::ArrayInfo arr_info =
  4341. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta.get(), kid);
  4342. result = arr_info.length;
  4343. return true;
  4344. }
  4345. template<typename T>
  4346. typename std::enable_if<std::is_integral<T>::value, bool>::type
  4347. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  4348. return get_arr_n(llm_kv(kid), result, required);
  4349. }
  4350. template<typename T>
  4351. bool get_arr(const std::string & key, std::vector<T> & result, const bool required = true) {
  4352. const int kid = gguf_find_key(meta.get(), key.c_str());
  4353. if (kid < 0 || gguf_get_kv_type(meta.get(), kid) != GGUF_TYPE_ARRAY) {
  4354. if (required) {
  4355. throw std::runtime_error(format("array key not found in model: %s", key.c_str()));
  4356. }
  4357. return false;
  4358. }
  4359. struct GGUFMeta::ArrayInfo arr_info =
  4360. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta.get(), kid);
  4361. switch (arr_info.gt) {
  4362. case GGUF_TYPE_FLOAT32: GGML_ASSERT((std::is_same<T, float>::value)); break;
  4363. case GGUF_TYPE_INT32: GGML_ASSERT(
  4364. (std::is_same<T, int32_t>::value) ||
  4365. (std::is_same<T, uint32_t>::value)); break;
  4366. default:
  4367. throw std::runtime_error(format("%s is not a float32, int32 array", key.c_str()));
  4368. }
  4369. result.resize(arr_info.length);
  4370. result.assign((const T*)arr_info.data, (const T *)arr_info.data + arr_info.length);
  4371. return true;
  4372. }
  4373. template<typename T, size_t N_MAX>
  4374. bool get_arr(const std::string & key, std::array<T, N_MAX> & result, const bool required = true) {
  4375. const int kid = gguf_find_key(meta.get(), key.c_str());
  4376. if (kid < 0 || gguf_get_kv_type(meta.get(), kid) != GGUF_TYPE_ARRAY) {
  4377. if (required) {
  4378. throw std::runtime_error(format("array key not found in model: %s", key.c_str()));
  4379. }
  4380. return false;
  4381. }
  4382. struct GGUFMeta::ArrayInfo arr_info =
  4383. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta.get(), kid);
  4384. switch (arr_info.gt) {
  4385. case GGUF_TYPE_FLOAT32: GGML_ASSERT((std::is_same<T, float>::value)); break;
  4386. case GGUF_TYPE_INT32: GGML_ASSERT(
  4387. (std::is_same<T, int32_t>::value) ||
  4388. (std::is_same<T, uint32_t>::value)); break;
  4389. default:
  4390. throw std::runtime_error(format("%s is not a float32, int32 array", key.c_str()));
  4391. }
  4392. if (arr_info.length > N_MAX) {
  4393. 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));
  4394. }
  4395. std::copy((const T*)arr_info.data, (const T *)arr_info.data + arr_info.length, result.begin());
  4396. return true;
  4397. }
  4398. template<typename T>
  4399. bool get_arr(const enum llm_kv kid, T & result, const bool required = true) {
  4400. return get_arr(llm_kv(kid), result, required);
  4401. }
  4402. template<typename T>
  4403. bool get_key(const std::string & key, T & result, const bool required = true) {
  4404. auto it = kv_overrides.find(key);
  4405. const struct llama_model_kv_override * override =
  4406. it != kv_overrides.end() ? &it->second : nullptr;
  4407. const bool found = GGUFMeta::GKV<T>::set(meta.get(), key, result, override);
  4408. if (required && !found) {
  4409. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  4410. }
  4411. return found;
  4412. }
  4413. template<typename T>
  4414. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  4415. return get_key(llm_kv(kid), result, required);
  4416. }
  4417. // get array of n <= N_MAX elements, or a single element repeated n times
  4418. template<typename T, size_t N_MAX>
  4419. bool get_key_or_arr(const std::string & key, std::array<T, N_MAX> & result, uint32_t n, const bool required = true) {
  4420. const int kid = gguf_find_key(meta.get(), key.c_str());
  4421. if (kid < 0) {
  4422. if (required) {
  4423. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  4424. }
  4425. return false;
  4426. }
  4427. if (n > N_MAX) {
  4428. throw std::runtime_error(format("n > N_MAX: %u > %u for key %s", (uint32_t) n, (uint32_t) N_MAX, key.c_str()));
  4429. }
  4430. if (gguf_get_kv_type(meta.get(), kid) == GGUF_TYPE_ARRAY) {
  4431. struct GGUFMeta::ArrayInfo arr_info =
  4432. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta.get(), kid);
  4433. if (n != arr_info.length) {
  4434. throw std::runtime_error(format("key %s has wrong array length; expected %u, got %u", key.c_str(), n, (uint32_t) arr_info.length));
  4435. }
  4436. return get_arr(key, result, required);
  4437. } else {
  4438. T value;
  4439. bool ok = get_key(key, value, required);
  4440. if (!ok) {
  4441. return false;
  4442. }
  4443. for (uint32_t i = 0; i < n; i++) {
  4444. result[i] = value;
  4445. }
  4446. return true;
  4447. }
  4448. }
  4449. template<typename T>
  4450. bool get_key_or_arr(const enum llm_kv kid, T & result, uint32_t n, const bool required = true) {
  4451. return get_key_or_arr(llm_kv(kid), result, n, required);
  4452. }
  4453. std::string get_arch_name() const {
  4454. return arch_name;
  4455. }
  4456. enum llm_arch get_arch() const {
  4457. return llm_kv.arch;
  4458. }
  4459. const llama_tensor_weight * get_weight(const char * name) const {
  4460. auto pos = weights_map.find(name);
  4461. if (pos != weights_map.end()) {
  4462. return &pos->second;
  4463. }
  4464. return nullptr;
  4465. }
  4466. const llama_tensor_weight & require_weight(const char * name) const {
  4467. const llama_tensor_weight * weight = get_weight(name);
  4468. if (!weight) {
  4469. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  4470. }
  4471. return *weight;
  4472. }
  4473. struct ggml_tensor * get_tensor_meta(const char * name) const {
  4474. const auto * weight = get_weight(name);
  4475. if (!weight) {
  4476. return nullptr;
  4477. }
  4478. return weight->tensor;
  4479. }
  4480. struct ggml_tensor * require_tensor_meta(const std::string & name) const {
  4481. struct ggml_tensor * tensor = get_tensor_meta(name.c_str());
  4482. if (!tensor) {
  4483. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  4484. }
  4485. return tensor;
  4486. }
  4487. const struct ggml_tensor * check_tensor_dims(const std::string & name, const std::vector<int64_t> & ne, bool required) const {
  4488. const struct ggml_tensor * cur = get_tensor_meta(name.c_str());
  4489. if (cur == NULL) {
  4490. if (!required) {
  4491. return NULL;
  4492. }
  4493. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  4494. }
  4495. {
  4496. bool is_ok = true;
  4497. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  4498. if ((i < ne.size() && ne[i] != cur->ne[i]) || (i >= ne.size() && cur->ne[i] != 1)) {
  4499. is_ok = false;
  4500. break;
  4501. }
  4502. }
  4503. if (!is_ok) {
  4504. throw std::runtime_error(
  4505. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  4506. __func__, name.c_str(),
  4507. llama_format_tensor_shape(ne).c_str(),
  4508. llama_format_tensor_shape(cur).c_str()));
  4509. }
  4510. }
  4511. return cur;
  4512. }
  4513. static const int TENSOR_NOT_REQUIRED = 1;
  4514. static const int TENSOR_DUPLICATED = 2;
  4515. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::initializer_list<int64_t> & ne, int flags = 0) {
  4516. const struct ggml_tensor * cur = check_tensor_dims(name, ne, !(flags & TENSOR_NOT_REQUIRED));
  4517. if (cur == NULL) {
  4518. return NULL;
  4519. }
  4520. bool duplicated = flags & TENSOR_DUPLICATED;
  4521. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, cur);
  4522. ggml_set_name(tensor, ggml_get_name(cur));
  4523. if (duplicated) {
  4524. size_data += ggml_nbytes(cur);
  4525. } else {
  4526. n_created++;
  4527. }
  4528. return tensor;
  4529. }
  4530. 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) {
  4531. const struct ggml_tensor * cur = check_tensor_dims(name, ne, required);
  4532. if (cur == NULL) {
  4533. return NULL;
  4534. }
  4535. if (cur->type != base->type) {
  4536. 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)));
  4537. }
  4538. std::array<int64_t, GGML_MAX_DIMS> dims;
  4539. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  4540. dims[i] = i < ne.size() ? ne.begin()[i] : 1;
  4541. }
  4542. struct ggml_tensor * tensor = ggml_view_4d(ctx, base,
  4543. dims[0], dims[1], dims[2], dims[3],
  4544. cur->nb[1], cur->nb[2], cur->nb[3],
  4545. offset);
  4546. ggml_set_name(tensor, name.c_str());
  4547. n_created++;
  4548. return tensor;
  4549. }
  4550. void done_getting_tensors() const {
  4551. if (n_created != n_tensors) {
  4552. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  4553. }
  4554. }
  4555. void init_mappings(bool prefetch = true, llama_mlocks * mlock_mmaps = nullptr) {
  4556. if (use_mmap) {
  4557. mappings.reserve(files.size());
  4558. mmaps_used.reserve(files.size());
  4559. for (const auto & file : files) {
  4560. auto * reg = ggml_backend_dev_backend_reg(ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU));
  4561. auto * is_numa_fn = (decltype(ggml_is_numa) *) ggml_backend_reg_get_proc_address(reg, "ggml_backend_cpu_is_numa");
  4562. std::unique_ptr<llama_mmap> mapping(new llama_mmap(file.get(), prefetch ? -1 : 0, is_numa_fn()));
  4563. mmaps_used.emplace_back(mapping->size, 0);
  4564. if (mlock_mmaps) {
  4565. std::unique_ptr<llama_mlock> mlock_mmap(new llama_mlock());
  4566. mlock_mmap->init(mapping->addr);
  4567. mlock_mmaps->emplace_back(std::move(mlock_mmap));
  4568. }
  4569. mappings.emplace_back(std::move(mapping));
  4570. }
  4571. }
  4572. // compute the total size of all tensors for progress reporting
  4573. for (const auto & it : weights_map) {
  4574. size_data += ggml_nbytes(it.second.tensor);
  4575. }
  4576. }
  4577. void get_mapping_range(size_t * first, size_t * last, void ** addr, int idx, ggml_context * ctx) const {
  4578. GGML_ASSERT(!mappings.empty());
  4579. const auto & mapping = mappings.at(idx);
  4580. *first = mapping->size;
  4581. *last = 0;
  4582. *addr = mapping->addr;
  4583. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  4584. const auto * weight = get_weight(ggml_get_name(tensor));
  4585. if (!weight || weight->idx != idx) {
  4586. continue;
  4587. }
  4588. *first = std::min(*first, weight->offs);
  4589. *last = std::max(*last, weight->offs + ggml_nbytes(tensor));
  4590. }
  4591. }
  4592. // for backwards compatibility, does not support ggml-backend
  4593. void load_data_for(struct ggml_tensor * cur) const {
  4594. const auto & w = require_weight(ggml_get_name(cur));
  4595. if (use_mmap) {
  4596. const auto & mapping = mappings.at(w.idx);
  4597. if (cur->data == nullptr) {
  4598. cur->data = (uint8_t *)mapping->addr + w.offs;
  4599. } else {
  4600. memcpy(cur->data, (uint8_t *)mapping->addr + w.offs, ggml_nbytes(cur));
  4601. }
  4602. } else {
  4603. GGML_ASSERT(cur->data != nullptr);
  4604. GGML_ASSERT(w.idx < files.size());
  4605. const auto & file = files.at(w.idx);
  4606. file->seek(w.offs, SEEK_SET);
  4607. file->read_raw(cur->data, ggml_nbytes(cur));
  4608. }
  4609. if (check_tensors && !ggml_validate_row_data(cur->type, cur->data, ggml_nbytes(cur))) {
  4610. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  4611. }
  4612. }
  4613. size_t size_done = 0;
  4614. size_t size_data = 0;
  4615. std::vector<std::pair<size_t, size_t>> mmaps_used;
  4616. // Returns false if cancelled by progress_callback
  4617. bool load_all_data(
  4618. struct ggml_context * ctx,
  4619. llama_buf_map & bufs,
  4620. llama_mlocks * lmlocks,
  4621. llama_progress_callback progress_callback,
  4622. void * progress_callback_user_data) {
  4623. GGML_ASSERT(size_data != 0 && "call init_mappings() first");
  4624. std::vector<no_init<uint8_t>> read_buf;
  4625. std::vector<std::future<std::pair<ggml_tensor *, bool>>> validation_result;
  4626. // 4 staging buffers for async uploads, each sized 1MB seems to be a good default for single NVMe drives.
  4627. // NVMe raid configurations might require more / larger buffers.
  4628. constexpr size_t n_buffers = 4;
  4629. constexpr size_t buffer_size = 1 * 1024 * 1024; // 1MB
  4630. std::vector<ggml_backend_buffer_t> host_buffers;
  4631. std::vector<ggml_backend_event_t> events;
  4632. std::vector<void *> host_ptrs;
  4633. size_t buffer_idx = 0; // buffer to use for async loads
  4634. ggml_backend_t upload_backend = [&](const char * func) -> ggml_backend_t {
  4635. if (use_mmap || check_tensors) {
  4636. return nullptr;
  4637. }
  4638. // When not using mmaped io use async uploads from pinned memory to GPU memory.
  4639. // First determine if the backend supports the necessary features for async uploads.
  4640. auto * buf = bufs.count(0) ? bufs.at(0) : nullptr;
  4641. if (!buf) {
  4642. LLAMA_LOG_DEBUG("%s: no buffer found for async uploads\n", func);
  4643. return nullptr;
  4644. }
  4645. auto * buft = ggml_backend_buffer_get_type(buf);
  4646. auto * dev = ggml_backend_buft_get_device(buft);
  4647. if (!dev) {
  4648. LLAMA_LOG_DEBUG("%s: no device found for buffer type %s for async uploads\n", func,
  4649. ggml_backend_buft_name(buft));
  4650. return nullptr;
  4651. }
  4652. if (buft != ggml_backend_dev_buffer_type(dev)) {
  4653. LLAMA_LOG_DEBUG("%s: buffer type %s is not the default buffer type for device %s for async uploads\n", func,
  4654. ggml_backend_buft_name(buft), ggml_backend_dev_name(dev));
  4655. return nullptr;
  4656. }
  4657. ggml_backend_dev_props props;
  4658. ggml_backend_dev_get_props(dev, &props);
  4659. if (!props.caps.async || !props.caps.host_buffer || !props.caps.events) {
  4660. LLAMA_LOG_DEBUG("%s: device %s does not support async, host buffers or events\n", func,
  4661. ggml_backend_dev_name(dev));
  4662. return nullptr;
  4663. }
  4664. auto * host_buft = ggml_backend_dev_host_buffer_type(dev);
  4665. if (!host_buft) {
  4666. LLAMA_LOG_DEBUG("%s: no host buffer type found for device %s\n", func,
  4667. ggml_backend_dev_name(dev));
  4668. return nullptr;
  4669. }
  4670. // If the backend is supported, create pinned memory buffers and events for synchronisation.
  4671. for (size_t idx = 0; idx < n_buffers; ++idx) {
  4672. auto * buf = ggml_backend_buft_alloc_buffer(host_buft, buffer_size);
  4673. if (!buf) {
  4674. LLAMA_LOG_DEBUG("%s: failed to allocate host buffer for async uploads for device %s\n", func,
  4675. ggml_backend_dev_name(dev));
  4676. return nullptr;
  4677. }
  4678. host_buffers.emplace_back(buf);
  4679. host_ptrs.emplace_back(ggml_backend_buffer_get_base(buf));
  4680. auto * event = ggml_backend_event_new(dev);
  4681. if (!event) {
  4682. LLAMA_LOG_DEBUG("%s: failed to create event for async uploads for device %s\n", func,
  4683. ggml_backend_dev_name(dev));
  4684. return nullptr;
  4685. }
  4686. events.emplace_back(event);
  4687. }
  4688. ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr);
  4689. if (!backend) {
  4690. LLAMA_LOG_DEBUG("%s: failed to initialize backend for device %s for async uploads\n", func,
  4691. ggml_backend_dev_name(dev));
  4692. return nullptr;
  4693. }
  4694. return backend;
  4695. }(__func__);
  4696. if (upload_backend) {
  4697. LLAMA_LOG_DEBUG("%s: using async uploads for device %s, buffer type %s, backend %s\n", __func__,
  4698. ggml_backend_dev_name(ggml_backend_get_device(upload_backend)),
  4699. ggml_backend_buft_name(ggml_backend_buffer_get_type(bufs.at(0))),
  4700. ggml_backend_name(upload_backend));
  4701. }
  4702. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  4703. const auto * weight = get_weight(ggml_get_name(cur));
  4704. if (weight == nullptr) {
  4705. // this can happen with split experts models
  4706. continue;
  4707. }
  4708. if (progress_callback) {
  4709. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  4710. return false;
  4711. }
  4712. }
  4713. size_t n_size = ggml_nbytes(cur);
  4714. if (use_mmap) {
  4715. const auto & mapping = mappings.at(weight->idx);
  4716. ggml_backend_buffer_t buf_mmap = nullptr;
  4717. if (bufs.count(weight->idx)) {
  4718. buf_mmap = bufs.at(weight->idx);
  4719. }
  4720. uint8_t * data = (uint8_t *) mapping->addr + weight->offs;
  4721. if (check_tensors) {
  4722. validation_result.emplace_back(std::async(std::launch::async, [cur, data, n_size] {
  4723. return std::make_pair(cur, ggml_validate_row_data(cur->type, data, n_size));
  4724. }));
  4725. }
  4726. GGML_ASSERT(buf_mmap || cur->data); // either we have a buffer to allocate the tensor in, or it is already allocated
  4727. if (buf_mmap && cur->data == nullptr) {
  4728. ggml_backend_tensor_alloc(buf_mmap, cur, data);
  4729. if (lmlocks) {
  4730. const auto & lmlock = lmlocks->at(weight->idx);
  4731. lmlock->grow_to(weight->offs + n_size);
  4732. }
  4733. auto & mmap_used = mmaps_used[weight->idx];
  4734. mmap_used.first = std::min(mmap_used.first, weight->offs);
  4735. mmap_used.second = std::max(mmap_used.second, weight->offs + n_size);
  4736. } else {
  4737. ggml_backend_tensor_set(cur, data, 0, n_size);
  4738. }
  4739. } else {
  4740. const auto & file = files.at(weight->idx);
  4741. if (ggml_backend_buffer_is_host(cur->buffer)) {
  4742. file->seek(weight->offs, SEEK_SET);
  4743. file->read_raw(cur->data, n_size);
  4744. if (check_tensors) {
  4745. validation_result.emplace_back(std::async(std::launch::async, [cur, n_size] {
  4746. return std::make_pair(cur, ggml_validate_row_data(cur->type, cur->data, n_size));
  4747. }));
  4748. }
  4749. } else {
  4750. // If upload_backend is valid load the tensor in chunks to pinned memory and upload the buffers asynchronously to the GPU.
  4751. if (upload_backend) {
  4752. file->seek(weight->offs, SEEK_SET);
  4753. size_t bytes_read = 0;
  4754. while (bytes_read < n_size) {
  4755. size_t read_iteration = std::min<size_t>(buffer_size, n_size - bytes_read);
  4756. ggml_backend_event_synchronize(events[buffer_idx]);
  4757. file->read_raw(host_ptrs[buffer_idx], read_iteration);
  4758. ggml_backend_tensor_set_async(upload_backend, cur, host_ptrs[buffer_idx], bytes_read, read_iteration);
  4759. ggml_backend_event_record(events[buffer_idx], upload_backend);
  4760. bytes_read += read_iteration;
  4761. ++buffer_idx;
  4762. buffer_idx %= n_buffers;
  4763. }
  4764. } else {
  4765. read_buf.resize(n_size);
  4766. file->seek(weight->offs, SEEK_SET);
  4767. file->read_raw(read_buf.data(), n_size);
  4768. ggml_backend_tensor_set(cur, read_buf.data(), 0, n_size);
  4769. if (check_tensors && !ggml_validate_row_data(cur->type, read_buf.data(), n_size)) {
  4770. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  4771. }
  4772. }
  4773. }
  4774. }
  4775. size_done += n_size;
  4776. }
  4777. // free temporary resources used for async uploads
  4778. for (auto * event : events) {
  4779. ggml_backend_event_synchronize(event);
  4780. ggml_backend_event_free(event);
  4781. }
  4782. for (auto * buf : host_buffers) {
  4783. ggml_backend_buffer_free(buf);
  4784. }
  4785. ggml_backend_free(upload_backend);
  4786. // check validation results
  4787. bool validation_failed = false;
  4788. for (auto & future : validation_result) {
  4789. auto result = future.get();
  4790. if (!result.second) {
  4791. LLAMA_LOG_ERROR("%s: tensor '%s' has invalid data\n", __func__, ggml_get_name(result.first));
  4792. validation_failed = true;
  4793. }
  4794. }
  4795. if (validation_failed) {
  4796. throw std::runtime_error("found tensors with invalid data");
  4797. }
  4798. // check if this is the last call and do final cleanup
  4799. if (size_done >= size_data) {
  4800. // unmap offloaded tensors and metadata
  4801. if (use_mmap) {
  4802. for (uint32_t idx = 0; idx < mappings.size(); idx++) {
  4803. const auto & mmap_used = mmaps_used.at(idx);
  4804. auto & mapping = mappings.at(idx);
  4805. mapping->unmap_fragment(0, mmap_used.first);
  4806. if (mmap_used.second != 0) {
  4807. mapping->unmap_fragment(mmap_used.second, mapping->size);
  4808. }
  4809. }
  4810. }
  4811. if (progress_callback) {
  4812. // Even though the model is done loading, we still honor
  4813. // cancellation since we need to free allocations.
  4814. return progress_callback(1.0f, progress_callback_user_data);
  4815. }
  4816. }
  4817. return true;
  4818. }
  4819. };
  4820. // temporary allocate memory for the input batch if needed
  4821. static const llama_seq_id batch_default_seq_id = 0;
  4822. struct llama_batch_allocr {
  4823. std::array<llama_seq_id, 1> seq_id_0 = {batch_default_seq_id};
  4824. std::vector<llama_pos> pos;
  4825. std::vector<int32_t> n_seq_id;
  4826. std::vector<llama_seq_id *> seq_id;
  4827. std::vector<int8_t> logits;
  4828. struct llama_batch batch;
  4829. // optionally fulfill the batch returned by llama_batch_get_one
  4830. llama_batch_allocr(llama_context & ctx, struct llama_batch in_batch) {
  4831. batch = in_batch;
  4832. GGML_ASSERT(batch.n_tokens > 0);
  4833. if (!batch.pos) {
  4834. // determine the last position in KV cache
  4835. llama_pos last_pos = -1;
  4836. for (const auto & cell : ctx.kv_self.cells) {
  4837. if (cell.has_seq_id(batch_default_seq_id)) {
  4838. last_pos = std::max(last_pos, cell.pos);
  4839. }
  4840. }
  4841. last_pos++; // next position
  4842. pos.resize(batch.n_tokens);
  4843. for (int32_t i = 0; i < batch.n_tokens; i++) {
  4844. pos[i] = i+last_pos;
  4845. }
  4846. batch.pos = pos.data();
  4847. }
  4848. if (!batch.n_seq_id) {
  4849. n_seq_id.resize(batch.n_tokens);
  4850. for (int32_t i = 0; i < batch.n_tokens; i++) {
  4851. n_seq_id[i] = seq_id_0.size();
  4852. }
  4853. batch.n_seq_id = n_seq_id.data();
  4854. }
  4855. if (!batch.seq_id) {
  4856. seq_id.resize(batch.n_tokens + 1);
  4857. seq_id[batch.n_tokens] = NULL;
  4858. for (int32_t i = 0; i < batch.n_tokens; i++) {
  4859. seq_id[i] = seq_id_0.data();
  4860. }
  4861. batch.seq_id = seq_id.data();
  4862. }
  4863. if (!batch.logits) {
  4864. logits.resize(batch.n_tokens);
  4865. logits[logits.size() - 1] = true;
  4866. batch.logits = logits.data();
  4867. }
  4868. }
  4869. };
  4870. template<>
  4871. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  4872. uint32_t tmp;
  4873. const bool found = get_key(kid, tmp, required);
  4874. if (found) {
  4875. result = (enum llama_pooling_type) tmp;
  4876. } else {
  4877. result = LLAMA_POOLING_TYPE_UNSPECIFIED;
  4878. }
  4879. return found;
  4880. }
  4881. //
  4882. // load LLaMA models
  4883. //
  4884. static const char * llama_model_arch_name(llm_arch arch) {
  4885. auto it = LLM_ARCH_NAMES.find(arch);
  4886. if (it == LLM_ARCH_NAMES.end()) {
  4887. return "unknown";
  4888. }
  4889. return it->second;
  4890. }
  4891. static std::string llama_model_ftype_name(llama_ftype ftype) {
  4892. if (ftype & LLAMA_FTYPE_GUESSED) {
  4893. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  4894. }
  4895. switch (ftype) {
  4896. case LLAMA_FTYPE_ALL_F32: return "all F32";
  4897. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  4898. case LLAMA_FTYPE_MOSTLY_BF16: return "BF16";
  4899. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  4900. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  4901. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  4902. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  4903. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  4904. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  4905. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  4906. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  4907. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  4908. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  4909. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  4910. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  4911. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  4912. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  4913. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  4914. case LLAMA_FTYPE_MOSTLY_TQ1_0: return "TQ1_0 - 1.69 bpw ternary";
  4915. case LLAMA_FTYPE_MOSTLY_TQ2_0: return "TQ2_0 - 2.06 bpw ternary";
  4916. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: return "IQ2_XXS - 2.0625 bpw";
  4917. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  4918. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  4919. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  4920. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  4921. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: return "IQ3_XXS - 3.0625 bpw";
  4922. case LLAMA_FTYPE_MOSTLY_IQ1_S: return "IQ1_S - 1.5625 bpw";
  4923. case LLAMA_FTYPE_MOSTLY_IQ1_M: return "IQ1_M - 1.75 bpw";
  4924. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  4925. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  4926. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  4927. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  4928. default: return "unknown, may not work";
  4929. }
  4930. }
  4931. static const char * llama_model_type_name(e_model type) {
  4932. switch (type) {
  4933. case MODEL_14M: return "14M";
  4934. case MODEL_17M: return "17M";
  4935. case MODEL_22M: return "22M";
  4936. case MODEL_33M: return "33M";
  4937. case MODEL_60M: return "60M";
  4938. case MODEL_70M: return "70M";
  4939. case MODEL_80M: return "80M";
  4940. case MODEL_109M: return "109M";
  4941. case MODEL_137M: return "137M";
  4942. case MODEL_160M: return "160M";
  4943. case MODEL_220M: return "220M";
  4944. case MODEL_250M: return "250M";
  4945. case MODEL_270M: return "270M";
  4946. case MODEL_335M: return "335M";
  4947. case MODEL_410M: return "410M";
  4948. case MODEL_450M: return "450M";
  4949. case MODEL_770M: return "770M";
  4950. case MODEL_780M: return "780M";
  4951. case MODEL_0_5B: return "0.5B";
  4952. case MODEL_1B: return "1B";
  4953. case MODEL_1_3B: return "1.3B";
  4954. case MODEL_1_4B: return "1.4B";
  4955. case MODEL_1_5B: return "1.5B";
  4956. case MODEL_1_6B: return "1.6B";
  4957. case MODEL_2B: return "2B";
  4958. case MODEL_2_8B: return "2.8B";
  4959. case MODEL_3B: return "3B";
  4960. case MODEL_4B: return "4B";
  4961. case MODEL_6B: return "6B";
  4962. case MODEL_6_9B: return "6.9B";
  4963. case MODEL_7B: return "7B";
  4964. case MODEL_8B: return "8B";
  4965. case MODEL_9B: return "9B";
  4966. case MODEL_11B: return "11B";
  4967. case MODEL_12B: return "12B";
  4968. case MODEL_13B: return "13B";
  4969. case MODEL_14B: return "14B";
  4970. case MODEL_15B: return "15B";
  4971. case MODEL_16B: return "16B";
  4972. case MODEL_20B: return "20B";
  4973. case MODEL_30B: return "30B";
  4974. case MODEL_32B: return "32B";
  4975. case MODEL_34B: return "34B";
  4976. case MODEL_35B: return "35B";
  4977. case MODEL_40B: return "40B";
  4978. case MODEL_65B: return "65B";
  4979. case MODEL_70B: return "70B";
  4980. case MODEL_236B: return "236B";
  4981. case MODEL_314B: return "314B";
  4982. case MODEL_SMALL: return "0.1B";
  4983. case MODEL_MEDIUM: return "0.4B";
  4984. case MODEL_LARGE: return "0.8B";
  4985. case MODEL_XL: return "1.5B";
  4986. case MODEL_A1_7B: return "A1.7B";
  4987. case MODEL_A2_7B: return "A2.7B";
  4988. case MODEL_8x7B: return "8x7B";
  4989. case MODEL_8x22B: return "8x22B";
  4990. case MODEL_16x12B: return "16x12B";
  4991. case MODEL_10B_128x3_66B: return "10B+128x3.66B";
  4992. case MODEL_57B_A14B: return "57B.A14B";
  4993. case MODEL_27B: return "27B";
  4994. default: return "?B";
  4995. }
  4996. }
  4997. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  4998. switch (type) {
  4999. case LLAMA_VOCAB_TYPE_NONE: return "no vocab";
  5000. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  5001. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  5002. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  5003. case LLAMA_VOCAB_TYPE_UGM: return "UGM";
  5004. case LLAMA_VOCAB_TYPE_RWKV: return "RWKV";
  5005. default: return "unknown";
  5006. }
  5007. }
  5008. static void llm_load_stats(llama_model_loader & ml, llama_model & model) {
  5009. model.n_elements = ml.n_elements;
  5010. model.n_bytes = ml.n_bytes;
  5011. }
  5012. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  5013. model.arch = ml.get_arch();
  5014. if (model.arch == LLM_ARCH_UNKNOWN) {
  5015. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  5016. }
  5017. }
  5018. static void llm_load_hparams(
  5019. llama_model_loader & ml,
  5020. llama_model & model) {
  5021. auto & hparams = model.hparams;
  5022. const gguf_context * ctx = ml.meta.get();
  5023. // get metadata as string
  5024. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  5025. enum gguf_type type = gguf_get_kv_type(ctx, i);
  5026. if (type == GGUF_TYPE_ARRAY) {
  5027. continue;
  5028. }
  5029. const char * name = gguf_get_key(ctx, i);
  5030. const std::string value = gguf_kv_to_str(ctx, i);
  5031. model.gguf_kv.emplace(name, value);
  5032. }
  5033. // get general kv
  5034. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  5035. // get hparams kv
  5036. ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab, false) || ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  5037. // everything past this point is not vocab-related
  5038. if (hparams.vocab_only) {
  5039. return;
  5040. }
  5041. ml.get_key(LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  5042. ml.get_key(LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  5043. ml.get_key(LLM_KV_BLOCK_COUNT, hparams.n_layer);
  5044. ml.get_key(LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  5045. ml.get_key(LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  5046. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  5047. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  5048. if (hparams.n_expert > 0) {
  5049. GGML_ASSERT(hparams.n_expert_used > 0);
  5050. } else {
  5051. GGML_ASSERT(hparams.n_expert_used == 0);
  5052. }
  5053. // zero-out the per-layer hparams
  5054. std::fill(hparams.n_head_arr.begin(), hparams.n_head_arr.end(), 0);
  5055. std::fill(hparams.n_head_kv_arr.begin(), hparams.n_head_kv_arr.end(), 0);
  5056. std::fill(hparams.n_ff_arr.begin(), hparams.n_ff_arr.end(), 0);
  5057. std::fill(hparams.cross_attn_layers.begin(), hparams.cross_attn_layers.end(), -1);
  5058. ml.get_key_or_arr(LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff_arr, hparams.n_layer);
  5059. ml.get_key_or_arr(LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head_arr, hparams.n_layer);
  5060. ml.get_arr(LLM_KV_ATTENTION_CROSS_ATTENTION_LAYERS, hparams.cross_attn_layers, false);
  5061. // n_head_kv is optional, default to n_head
  5062. hparams.n_head_kv_arr = hparams.n_head_arr;
  5063. ml.get_key_or_arr(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv_arr, hparams.n_layer, false);
  5064. bool rope_finetuned = false;
  5065. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  5066. hparams.rope_finetuned = rope_finetuned;
  5067. hparams.n_ctx_orig_yarn = hparams.n_ctx_train;
  5068. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_ctx_orig_yarn, false);
  5069. // rope_freq_base (optional)
  5070. hparams.rope_freq_base_train = 10000.0f;
  5071. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  5072. std::string rope_scaling("linear");
  5073. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  5074. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  5075. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  5076. // rope_freq_scale (inverse of the kv) is optional
  5077. float ropescale = 0.0f;
  5078. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  5079. // try the old key name
  5080. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  5081. }
  5082. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  5083. ml.get_key(LLM_KV_ROPE_SCALING_ATTN_FACTOR, hparams.rope_attn_factor, false);
  5084. // non-transformer models do not have attention heads
  5085. if (hparams.n_head() > 0) {
  5086. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  5087. // gpt-j n_rot = rotary_dim
  5088. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head();
  5089. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  5090. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head();
  5091. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  5092. // sanity check for n_rot (optional)
  5093. hparams.n_rot = hparams.n_embd_head_k;
  5094. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  5095. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_MLLAMA || model.arch == LLM_ARCH_FALCON) {
  5096. if (hparams.n_rot != hparams.n_embd_head_k) {
  5097. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd_head_k));
  5098. }
  5099. }
  5100. } else {
  5101. hparams.n_rot = 0;
  5102. hparams.n_embd_head_k = 0;
  5103. hparams.n_embd_head_v = 0;
  5104. }
  5105. // arch-specific KVs
  5106. switch (model.arch) {
  5107. case LLM_ARCH_LLAMA:
  5108. {
  5109. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5110. if (hparams.n_expert == 8) {
  5111. switch (hparams.n_layer) {
  5112. case 32: model.type = e_model::MODEL_8x7B; break;
  5113. case 56: model.type = e_model::MODEL_8x22B; break;
  5114. default: model.type = e_model::MODEL_UNKNOWN;
  5115. }
  5116. } else {
  5117. switch (hparams.n_layer) {
  5118. case 16: model.type = e_model::MODEL_1B; break; // Llama 3.2 1B
  5119. case 22: model.type = e_model::MODEL_1B; break;
  5120. case 26: model.type = e_model::MODEL_3B; break;
  5121. case 28: model.type = e_model::MODEL_3B; break; // Llama 3.2 3B
  5122. // granite uses a vocab with len 49152
  5123. 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;
  5124. case 36: model.type = e_model::MODEL_8B; break; // granite
  5125. case 40: model.type = e_model::MODEL_13B; break;
  5126. case 48: model.type = e_model::MODEL_34B; break;
  5127. case 60: model.type = e_model::MODEL_30B; break;
  5128. case 80: model.type = hparams.n_head() == hparams.n_head_kv() ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  5129. default: model.type = e_model::MODEL_UNKNOWN;
  5130. }
  5131. }
  5132. } break;
  5133. case LLM_ARCH_MLLAMA:
  5134. {
  5135. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5136. switch (hparams.n_layer) {
  5137. case 40: model.type = e_model::MODEL_11B; break;
  5138. case 100: model.type = e_model::MODEL_90B; break;
  5139. default: model.type = e_model::MODEL_UNKNOWN;
  5140. }
  5141. } break;
  5142. case LLM_ARCH_MINICPM:
  5143. {
  5144. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5145. ml.get_key(LLM_KV_EMBEDDING_SCALE, hparams.f_embedding_scale);
  5146. ml.get_key(LLM_KV_RESIDUAL_SCALE, hparams.f_residual_scale);
  5147. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  5148. switch (hparams.n_layer) {
  5149. case 52: model.type = e_model::MODEL_1B; break;
  5150. case 40: model.type = e_model::MODEL_2B; break;
  5151. default: model.type = e_model::MODEL_UNKNOWN;
  5152. }
  5153. } break;
  5154. case LLM_ARCH_MINICPM3:
  5155. {
  5156. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5157. ml.get_key(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q);
  5158. ml.get_key(LLM_KV_ATTENTION_KV_LORA_RANK, hparams.n_lora_kv);
  5159. switch (hparams.n_layer) {
  5160. case 62: model.type = e_model::MODEL_4B; break;
  5161. default: model.type = e_model::MODEL_UNKNOWN;
  5162. }
  5163. } break;
  5164. case LLM_ARCH_GROK:
  5165. {
  5166. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5167. switch (hparams.n_layer) {
  5168. case 64: model.type = e_model::MODEL_314B; break;
  5169. default: model.type = e_model::MODEL_UNKNOWN;
  5170. }
  5171. } break;
  5172. case LLM_ARCH_FALCON:
  5173. {
  5174. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5175. switch (hparams.n_layer) {
  5176. case 32: model.type = e_model::MODEL_7B; break;
  5177. case 60: model.type = e_model::MODEL_40B; break;
  5178. default: model.type = e_model::MODEL_UNKNOWN;
  5179. }
  5180. } break;
  5181. case LLM_ARCH_BAICHUAN:
  5182. {
  5183. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5184. switch (hparams.n_layer) {
  5185. case 32: model.type = e_model::MODEL_7B; break;
  5186. case 40: model.type = e_model::MODEL_13B; break;
  5187. default: model.type = e_model::MODEL_UNKNOWN;
  5188. }
  5189. if (model.type == e_model::MODEL_13B) {
  5190. // TODO: become GGUF KV parameter
  5191. hparams.f_max_alibi_bias = 8.0f;
  5192. }
  5193. } break;
  5194. case LLM_ARCH_STARCODER:
  5195. {
  5196. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5197. switch (hparams.n_layer) {
  5198. case 24: model.type = e_model::MODEL_1B; break;
  5199. case 36: model.type = e_model::MODEL_3B; break;
  5200. case 42: model.type = e_model::MODEL_7B; break;
  5201. case 40: model.type = e_model::MODEL_15B; break;
  5202. default: model.type = e_model::MODEL_UNKNOWN;
  5203. }
  5204. } break;
  5205. case LLM_ARCH_REFACT:
  5206. {
  5207. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5208. switch (hparams.n_layer) {
  5209. case 32: model.type = e_model::MODEL_1B; break;
  5210. default: model.type = e_model::MODEL_UNKNOWN;
  5211. }
  5212. // TODO: become GGUF KV parameter
  5213. hparams.f_max_alibi_bias = 8.0f;
  5214. } break;
  5215. case LLM_ARCH_BERT:
  5216. {
  5217. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5218. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  5219. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  5220. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  5221. switch (hparams.n_layer) {
  5222. case 3:
  5223. model.type = e_model::MODEL_17M; break; // bge-micro
  5224. case 6:
  5225. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  5226. case 12:
  5227. switch (hparams.n_embd) {
  5228. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  5229. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  5230. } break;
  5231. case 24:
  5232. model.type = e_model::MODEL_335M; break; // bge-large
  5233. }
  5234. } break;
  5235. case LLM_ARCH_JINA_BERT_V2:
  5236. {
  5237. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5238. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  5239. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  5240. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  5241. hparams.f_max_alibi_bias = 8.0f;
  5242. switch (hparams.n_layer) {
  5243. case 4: model.type = e_model::MODEL_33M; break; // jina-embeddings-small
  5244. case 12: model.type = e_model::MODEL_137M; break; // jina-embeddings-base
  5245. }
  5246. } break;
  5247. case LLM_ARCH_NOMIC_BERT:
  5248. {
  5249. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5250. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  5251. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  5252. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  5253. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  5254. model.type = e_model::MODEL_137M;
  5255. }
  5256. } break;
  5257. case LLM_ARCH_BLOOM:
  5258. {
  5259. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5260. switch (hparams.n_layer) {
  5261. case 24: model.type = e_model::MODEL_1B; break;
  5262. case 30:
  5263. switch (hparams.n_embd) {
  5264. case 2560: model.type = e_model::MODEL_3B; break;
  5265. case 4096: model.type = e_model::MODEL_7B; break;
  5266. } break;
  5267. }
  5268. // TODO: become GGUF KV parameter
  5269. hparams.f_max_alibi_bias = 8.0f;
  5270. } break;
  5271. case LLM_ARCH_MPT:
  5272. {
  5273. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5274. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  5275. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  5276. switch (hparams.n_layer) {
  5277. case 32: model.type = e_model::MODEL_7B; break;
  5278. case 48: model.type = e_model::MODEL_30B; break;
  5279. default: model.type = e_model::MODEL_UNKNOWN;
  5280. }
  5281. } break;
  5282. case LLM_ARCH_STABLELM:
  5283. {
  5284. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5285. switch (hparams.n_layer) {
  5286. case 24: model.type = e_model::MODEL_1B; break;
  5287. case 32: model.type = e_model::MODEL_3B; break;
  5288. case 40: model.type = e_model::MODEL_12B; break;
  5289. default: model.type = e_model::MODEL_UNKNOWN;
  5290. }
  5291. } break;
  5292. case LLM_ARCH_QWEN:
  5293. {
  5294. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5295. switch (hparams.n_layer) {
  5296. case 32: model.type = e_model::MODEL_7B; break;
  5297. case 40: model.type = e_model::MODEL_13B; break;
  5298. default: model.type = e_model::MODEL_UNKNOWN;
  5299. }
  5300. } break;
  5301. case LLM_ARCH_QWEN2VL:
  5302. {
  5303. std::array<int, 4> section_dims;
  5304. ml.get_key_or_arr(LLM_KV_ROPE_DIMENSION_SECTIONS, section_dims, 4, true);
  5305. std::copy(section_dims.begin(), section_dims.begin() + 4, std::begin(hparams.rope_sections));
  5306. }
  5307. // fall through
  5308. case LLM_ARCH_QWEN2:
  5309. {
  5310. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5311. switch (hparams.n_layer) {
  5312. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  5313. case 28: model.type = hparams.n_embd == 1536 ? e_model::MODEL_1_5B : e_model::MODEL_7B; break;
  5314. case 32: model.type = e_model::MODEL_7B; break;
  5315. case 36: model.type = e_model::MODEL_3B; break;
  5316. case 40: model.type = hparams.n_head() == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  5317. case 48: model.type = e_model::MODEL_14B; break;
  5318. case 64: model.type = e_model::MODEL_32B; break;
  5319. case 80: model.type = e_model::MODEL_70B; break;
  5320. default: model.type = e_model::MODEL_UNKNOWN;
  5321. }
  5322. } break;
  5323. case LLM_ARCH_QWEN2MOE:
  5324. {
  5325. ml.get_key(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp, false);
  5326. ml.get_key(LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, hparams.n_ff_shexp, false);
  5327. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5328. switch (hparams.n_layer) {
  5329. case 24: model.type = e_model::MODEL_A2_7B; break;
  5330. case 28: model.type = e_model::MODEL_57B_A14B; break;
  5331. default: model.type = e_model::MODEL_UNKNOWN;
  5332. }
  5333. } break;
  5334. case LLM_ARCH_PHI2:
  5335. {
  5336. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5337. switch (hparams.n_layer) {
  5338. case 24: model.type = e_model::MODEL_1B; break;
  5339. case 32: model.type = e_model::MODEL_3B; break;
  5340. default: model.type = e_model::MODEL_UNKNOWN;
  5341. }
  5342. } break;
  5343. case LLM_ARCH_PHI3:
  5344. {
  5345. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5346. switch (hparams.n_layer) {
  5347. case 24: model.type = e_model::MODEL_1B; break;
  5348. case 32: model.type = e_model::MODEL_3B; break;
  5349. case 40: model.type = e_model::MODEL_14B; break;
  5350. default: model.type = e_model::MODEL_UNKNOWN;
  5351. }
  5352. // for backward compatibility ; see: https://github.com/ggerganov/llama.cpp/pull/8931
  5353. if ((hparams.n_layer == 32 || hparams.n_layer == 40) && hparams.n_ctx_train == 4096) {
  5354. // default value for Phi-3-mini-4k-instruct and Phi-3-medium-4k-instruct
  5355. hparams.n_swa = 2047;
  5356. } else if (hparams.n_layer == 32 && hparams.n_head_kv(0) == 32 && hparams.n_ctx_train == 131072) {
  5357. // default value for Phi-3-mini-128k-instruct
  5358. hparams.n_swa = 262144;
  5359. } else if (hparams.n_layer == 40 && hparams.n_ctx_train == 131072) {
  5360. // default value for Phi-3-medium-128k-instruct
  5361. hparams.n_swa = 131072;
  5362. }
  5363. bool found_swa = ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa, false);
  5364. if (!found_swa && hparams.n_swa == 0) {
  5365. throw std::runtime_error("invalid value for sliding_window");
  5366. }
  5367. } break;
  5368. case LLM_ARCH_PLAMO:
  5369. {
  5370. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5371. switch (hparams.n_layer) {
  5372. case 40: model.type = e_model::MODEL_13B; break;
  5373. default: model.type = e_model::MODEL_UNKNOWN;
  5374. }
  5375. } break;
  5376. case LLM_ARCH_GPT2:
  5377. {
  5378. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5379. switch (hparams.n_layer) {
  5380. case 12: model.type = e_model::MODEL_SMALL; break;
  5381. case 24: model.type = e_model::MODEL_MEDIUM; break;
  5382. case 36: model.type = e_model::MODEL_LARGE; break;
  5383. case 48: model.type = e_model::MODEL_XL; break;
  5384. default: model.type = e_model::MODEL_UNKNOWN;
  5385. }
  5386. } break;
  5387. case LLM_ARCH_CODESHELL:
  5388. {
  5389. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5390. switch (hparams.n_layer) {
  5391. case 42: model.type = e_model::MODEL_7B; break;
  5392. default: model.type = e_model::MODEL_UNKNOWN;
  5393. }
  5394. } break;
  5395. case LLM_ARCH_ORION:
  5396. {
  5397. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5398. switch (hparams.n_layer) {
  5399. case 40: model.type = e_model::MODEL_14B; break;
  5400. default: model.type = e_model::MODEL_UNKNOWN;
  5401. }
  5402. } break;
  5403. case LLM_ARCH_INTERNLM2:
  5404. {
  5405. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5406. switch (hparams.n_layer) {
  5407. case 32: model.type = e_model::MODEL_7B; break;
  5408. case 48: model.type = e_model::MODEL_20B; break;
  5409. default: model.type = e_model::MODEL_UNKNOWN;
  5410. }
  5411. } break;
  5412. case LLM_ARCH_GEMMA:
  5413. {
  5414. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5415. switch (hparams.n_layer) {
  5416. case 18: model.type = e_model::MODEL_2B; break;
  5417. case 28: model.type = e_model::MODEL_7B; break;
  5418. default: model.type = e_model::MODEL_UNKNOWN;
  5419. }
  5420. } break;
  5421. case LLM_ARCH_GEMMA2:
  5422. {
  5423. hparams.n_swa = 4096; // default value of gemma 2
  5424. ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa, false);
  5425. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5426. ml.get_key(LLM_KV_ATTN_LOGIT_SOFTCAPPING, hparams.f_attn_logit_softcapping, false);
  5427. ml.get_key(LLM_KV_FINAL_LOGIT_SOFTCAPPING, hparams.f_final_logit_softcapping, false);
  5428. hparams.attn_soft_cap = true;
  5429. switch (hparams.n_layer) {
  5430. case 26: model.type = e_model::MODEL_2B; break;
  5431. case 42: model.type = e_model::MODEL_9B; break;
  5432. case 46: model.type = e_model::MODEL_27B; break;
  5433. default: model.type = e_model::MODEL_UNKNOWN;
  5434. }
  5435. } break;
  5436. case LLM_ARCH_STARCODER2:
  5437. {
  5438. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5439. switch (hparams.n_layer) {
  5440. case 30: model.type = e_model::MODEL_3B; break;
  5441. case 32: model.type = e_model::MODEL_7B; break;
  5442. case 40: model.type = e_model::MODEL_15B; break;
  5443. case 52: model.type = e_model::MODEL_20B; break; // granite
  5444. case 88: model.type = e_model::MODEL_34B; break; // granite
  5445. default: model.type = e_model::MODEL_UNKNOWN;
  5446. }
  5447. } break;
  5448. case LLM_ARCH_MAMBA:
  5449. {
  5450. ml.get_key(LLM_KV_SSM_CONV_KERNEL, hparams.ssm_d_conv);
  5451. ml.get_key(LLM_KV_SSM_INNER_SIZE, hparams.ssm_d_inner);
  5452. ml.get_key(LLM_KV_SSM_STATE_SIZE, hparams.ssm_d_state);
  5453. ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
  5454. ml.get_key(LLM_KV_SSM_DT_B_C_RMS, hparams.ssm_dt_b_c_rms, false);
  5455. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5456. switch (hparams.n_layer) {
  5457. case 24:
  5458. switch (hparams.n_embd) {
  5459. case 768: model.type = e_model::MODEL_SMALL; break;
  5460. default: model.type = e_model::MODEL_UNKNOWN;
  5461. } break;
  5462. case 48:
  5463. switch (hparams.n_embd) {
  5464. case 1024: model.type = e_model::MODEL_MEDIUM; break;
  5465. case 1536: model.type = e_model::MODEL_LARGE; break;
  5466. case 2048: model.type = e_model::MODEL_XL; break;
  5467. default: model.type = e_model::MODEL_UNKNOWN;
  5468. } break;
  5469. case 64:
  5470. switch (hparams.n_embd) {
  5471. case 2560: model.type = e_model::MODEL_3B; break;
  5472. default: model.type = e_model::MODEL_UNKNOWN;
  5473. } break;
  5474. default: model.type = e_model::MODEL_UNKNOWN;
  5475. }
  5476. } break;
  5477. case LLM_ARCH_XVERSE:
  5478. {
  5479. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5480. switch (hparams.n_layer) {
  5481. case 32: model.type = e_model::MODEL_7B; break;
  5482. case 40: model.type = e_model::MODEL_13B; break;
  5483. case 80: model.type = e_model::MODEL_65B; break;
  5484. default: model.type = e_model::MODEL_UNKNOWN;
  5485. }
  5486. } break;
  5487. case LLM_ARCH_COMMAND_R:
  5488. {
  5489. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  5490. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5491. switch (hparams.n_layer) {
  5492. case 40: model.type = e_model::MODEL_35B; break;
  5493. default: model.type = e_model::MODEL_UNKNOWN;
  5494. }
  5495. } break;
  5496. case LLM_ARCH_DBRX:
  5497. {
  5498. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5499. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv);
  5500. switch (hparams.n_layer) {
  5501. case 40: model.type = e_model::MODEL_16x12B; break;
  5502. default: model.type = e_model::MODEL_UNKNOWN;
  5503. }
  5504. } break;
  5505. case LLM_ARCH_OLMO:
  5506. {
  5507. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5508. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  5509. switch (hparams.n_layer) {
  5510. case 22: model.type = e_model::MODEL_1B; break;
  5511. case 32: model.type = e_model::MODEL_7B; break;
  5512. case 80: model.type = e_model::MODEL_70B; break;
  5513. default: model.type = e_model::MODEL_UNKNOWN;
  5514. }
  5515. } break;
  5516. case LLM_ARCH_OLMO2:
  5517. {
  5518. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5519. switch (hparams.n_layer) {
  5520. case 16: model.type = e_model::MODEL_1B; break;
  5521. case 32: model.type = e_model::MODEL_7B; break;
  5522. case 40: model.type = e_model::MODEL_13B; break;
  5523. default: model.type = e_model::MODEL_UNKNOWN;
  5524. }
  5525. } break;
  5526. case LLM_ARCH_OLMOE:
  5527. {
  5528. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5529. switch (hparams.n_layer) {
  5530. case 16: model.type = e_model::MODEL_A1_7B; break;
  5531. default: model.type = e_model::MODEL_UNKNOWN;
  5532. }
  5533. } break;
  5534. case LLM_ARCH_OPENELM:
  5535. {
  5536. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5537. switch (hparams.n_layer) {
  5538. case 16: model.type = e_model::MODEL_270M; break;
  5539. case 20: model.type = e_model::MODEL_450M; break;
  5540. case 28: model.type = e_model::MODEL_1B; break;
  5541. case 36: model.type = e_model::MODEL_3B; break;
  5542. default: model.type = e_model::MODEL_UNKNOWN;
  5543. }
  5544. } break;
  5545. case LLM_ARCH_GPTNEOX:
  5546. {
  5547. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5548. ml.get_key(LLM_KV_USE_PARALLEL_RESIDUAL, hparams.use_par_res);
  5549. switch (hparams.n_layer) {
  5550. case 6:
  5551. switch (hparams.n_ff()) {
  5552. case 512: model.type = e_model::MODEL_14M; break;
  5553. case 2048: model.type = e_model::MODEL_70M; break;
  5554. default: model.type = e_model::MODEL_UNKNOWN;
  5555. } break;
  5556. case 12:
  5557. switch (hparams.n_ff()) {
  5558. case 3072: model.type = e_model::MODEL_160M; break;
  5559. default: model.type = e_model::MODEL_UNKNOWN;
  5560. } break;
  5561. case 16:
  5562. switch (hparams.n_ff()) {
  5563. case 8192: model.type = e_model::MODEL_1B; break;
  5564. default: model.type = e_model::MODEL_UNKNOWN;
  5565. } break;
  5566. case 24:
  5567. switch (hparams.n_ff()) {
  5568. case 4096: model.type = e_model::MODEL_410M; break;
  5569. case 8192: model.type = e_model::MODEL_1_4B; break;
  5570. default: model.type = e_model::MODEL_UNKNOWN;
  5571. } break;
  5572. case 32:
  5573. switch (hparams.n_ff()) {
  5574. case 10240: model.type = e_model::MODEL_2_8B; break;
  5575. case 16384: model.type = e_model::MODEL_6_9B; break;
  5576. default: model.type = e_model::MODEL_UNKNOWN;
  5577. } break;
  5578. case 36:
  5579. switch (hparams.n_ff()) {
  5580. case 20480: model.type = e_model::MODEL_12B; break;
  5581. default: model.type = e_model::MODEL_UNKNOWN;
  5582. } break;
  5583. case 44:
  5584. switch (hparams.n_ff()) {
  5585. case 24576: model.type = e_model::MODEL_20B; break;
  5586. default: model.type = e_model::MODEL_UNKNOWN;
  5587. } break;
  5588. default: model.type = e_model::MODEL_UNKNOWN;
  5589. }
  5590. } break;
  5591. case LLM_ARCH_ARCTIC:
  5592. {
  5593. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5594. if (hparams.n_expert == 128) {
  5595. switch (hparams.n_layer) {
  5596. case 35: model.type = e_model::MODEL_10B_128x3_66B; break;
  5597. default: model.type = e_model::MODEL_UNKNOWN;
  5598. }
  5599. } else {
  5600. model.type = e_model::MODEL_UNKNOWN;
  5601. }
  5602. } break;
  5603. case LLM_ARCH_DEEPSEEK2:
  5604. {
  5605. bool is_lite = (hparams.n_layer == 27);
  5606. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5607. ml.get_key(LLM_KV_LEADING_DENSE_BLOCK_COUNT, hparams.n_layer_dense_lead);
  5608. if (!is_lite) {
  5609. ml.get_key(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q);
  5610. }
  5611. ml.get_key(LLM_KV_ATTENTION_KV_LORA_RANK, hparams.n_lora_kv);
  5612. ml.get_key(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp);
  5613. ml.get_key(LLM_KV_EXPERT_SHARED_COUNT, hparams.n_expert_shared);
  5614. ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale);
  5615. ml.get_key(LLM_KV_ROPE_SCALING_YARN_LOG_MUL, hparams.rope_yarn_log_mul);
  5616. switch (hparams.n_layer) {
  5617. case 27: model.type = e_model::MODEL_16B; break;
  5618. case 60: model.type = e_model::MODEL_236B; break;
  5619. default: model.type = e_model::MODEL_UNKNOWN;
  5620. }
  5621. } break;
  5622. case LLM_ARCH_CHATGLM:
  5623. {
  5624. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5625. switch (hparams.n_layer) {
  5626. case 28: model.type = e_model::MODEL_6B; break;
  5627. case 40: model.type = e_model::MODEL_9B; break;
  5628. default: model.type = e_model::MODEL_UNKNOWN;
  5629. }
  5630. } break;
  5631. case LLM_ARCH_BITNET:
  5632. {
  5633. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5634. switch (hparams.n_layer) {
  5635. case 26: model.type = e_model::MODEL_3B; break;
  5636. default: model.type = e_model::MODEL_UNKNOWN;
  5637. }
  5638. } break;
  5639. case LLM_ARCH_T5:
  5640. {
  5641. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5642. ml.get_key(LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, hparams.n_rel_attn_bkts);
  5643. uint32_t dec_start_token_id;
  5644. if (ml.get_key(LLM_KV_DECODER_START_TOKEN_ID, dec_start_token_id, false)) {
  5645. hparams.dec_start_token_id = dec_start_token_id;
  5646. }
  5647. switch (hparams.n_layer) {
  5648. case 6: model.type = e_model::MODEL_60M; break; // t5-small
  5649. case 8: model.type = e_model::MODEL_80M; break; // flan-t5-small
  5650. case 12:
  5651. switch (hparams.n_ff()) {
  5652. case 3072: model.type = e_model::MODEL_220M; break; // t5-base
  5653. case 2048: model.type = e_model::MODEL_250M; break; // flan-t5-base
  5654. default: model.type = e_model::MODEL_UNKNOWN;
  5655. } break;
  5656. case 24:
  5657. switch (hparams.n_ff()) {
  5658. case 4096: model.type = e_model::MODEL_770M; break; // t5-large
  5659. case 2816: model.type = e_model::MODEL_780M; break; // flan-t5-large
  5660. case 16384: model.type = e_model::MODEL_3B; break; // t5-3b
  5661. case 5120: model.type = e_model::MODEL_3B; break; // flan-t5-xl
  5662. case 65536: model.type = e_model::MODEL_11B; break; // t5-11b
  5663. case 10240: model.type = e_model::MODEL_11B; break; // flan-t5-xxl
  5664. default: model.type = e_model::MODEL_UNKNOWN;
  5665. } break;
  5666. default: model.type = e_model::MODEL_UNKNOWN;
  5667. }
  5668. } break;
  5669. case LLM_ARCH_T5ENCODER:
  5670. {
  5671. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5672. ml.get_key(LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, hparams.n_rel_attn_bkts);
  5673. model.type = e_model::MODEL_UNKNOWN;
  5674. } break;
  5675. case LLM_ARCH_JAIS:
  5676. {
  5677. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5678. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  5679. switch (hparams.n_layer) {
  5680. case 24: model.type = e_model::MODEL_1_3B; break;
  5681. case 40: model.type = e_model::MODEL_13B; break;
  5682. /* TODO: add variants */
  5683. default: model.type = e_model::MODEL_UNKNOWN;
  5684. }
  5685. } break;
  5686. case LLM_ARCH_NEMOTRON:
  5687. {
  5688. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5689. switch (hparams.n_layer) {
  5690. case 32: model.type = e_model::MODEL_4B; break;
  5691. default: model.type = e_model::MODEL_UNKNOWN;
  5692. }
  5693. } break;
  5694. case LLM_ARCH_EXAONE:
  5695. {
  5696. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5697. switch (hparams.n_layer) {
  5698. case 32: model.type = e_model::MODEL_8B; break;
  5699. default: model.type = e_model::MODEL_UNKNOWN;
  5700. }
  5701. } break;
  5702. case LLM_ARCH_RWKV6:
  5703. {
  5704. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5705. ml.get_key(LLM_KV_WKV_HEAD_SIZE, hparams.wkv_head_size);
  5706. ml.get_key(LLM_KV_TIME_MIX_EXTRA_DIM, hparams.time_mix_extra_dim);
  5707. ml.get_key(LLM_KV_TIME_DECAY_EXTRA_DIM, hparams.time_decay_extra_dim);
  5708. ml.get_key(LLM_KV_RESCALE_EVERY_N_LAYERS, hparams.rescale_every_n_layers, false);
  5709. switch (hparams.n_layer) {
  5710. case 24: model.type = e_model::MODEL_1_6B; break;
  5711. case 32:
  5712. switch (hparams.n_embd) {
  5713. case 2560: model.type = e_model::MODEL_3B; break;
  5714. case 4096: model.type = e_model::MODEL_7B; break;
  5715. default: model.type = e_model::MODEL_UNKNOWN;
  5716. } break;
  5717. case 61: model.type = e_model::MODEL_14B; break;
  5718. default: model.type = e_model::MODEL_UNKNOWN;
  5719. }
  5720. } break;
  5721. case LLM_ARCH_GRANITE:
  5722. case LLM_ARCH_GRANITE_MOE:
  5723. {
  5724. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5725. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  5726. ml.get_key(LLM_KV_RESIDUAL_SCALE, hparams.f_residual_scale);
  5727. ml.get_key(LLM_KV_EMBEDDING_SCALE, hparams.f_embedding_scale);
  5728. ml.get_key(LLM_KV_ATTENTION_SCALE, hparams.f_attention_scale);
  5729. switch (hparams.n_layer) {
  5730. case 32: model.type = e_model::MODEL_3B; break;
  5731. case 40: model.type = e_model::MODEL_3B; break;
  5732. // Add additional layer/vocab/etc checks here for other model sizes
  5733. default: model.type = e_model::MODEL_UNKNOWN;
  5734. }
  5735. } break;
  5736. case LLM_ARCH_CHAMELEON:
  5737. {
  5738. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5739. hparams.f_norm_eps = 1e-5; // eps for qk-norm, torch default
  5740. ml.get_key(LLM_KV_SWIN_NORM, hparams.swin_norm);
  5741. switch (hparams.n_layer) {
  5742. case 32: model.type = e_model::MODEL_7B; break;
  5743. case 48: model.type = e_model::MODEL_34B; break;
  5744. default: model.type = e_model::MODEL_UNKNOWN;
  5745. }
  5746. } break;
  5747. case LLM_ARCH_SOLAR:
  5748. {
  5749. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5750. for (int i = 0; i < hparams.n_bskcn_arr.max_size(); ++i) {
  5751. auto & bskcn = hparams.n_bskcn_arr.at(i);
  5752. bskcn.fill(0);
  5753. 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);
  5754. }
  5755. switch (hparams.n_layer) {
  5756. case 64: model.type = e_model::MODEL_22B; break;
  5757. default: model.type = e_model::MODEL_UNKNOWN;
  5758. }
  5759. }
  5760. default: (void)0;
  5761. }
  5762. model.ftype = ml.ftype;
  5763. if (hparams.f_max_alibi_bias > 0.0f) {
  5764. hparams.use_alibi = true;
  5765. }
  5766. hparams.rope_type = llama_rope_type(&model);
  5767. }
  5768. static void llm_load_vocab(
  5769. llama_model_loader & ml,
  5770. llama_model & model) {
  5771. auto & vocab = model.vocab;
  5772. struct gguf_context * ctx = ml.meta.get();
  5773. const auto kv = LLM_KV(model.arch);
  5774. // determine vocab type
  5775. {
  5776. std::string tokenizer_model;
  5777. std::string tokenizer_pre;
  5778. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_model);
  5779. ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false);
  5780. if (tokenizer_model == "no_vocab") {
  5781. vocab.type = LLAMA_VOCAB_TYPE_NONE;
  5782. // default special tokens
  5783. vocab.special_bos_id = LLAMA_TOKEN_NULL;
  5784. vocab.special_eos_id = LLAMA_TOKEN_NULL;
  5785. vocab.special_unk_id = LLAMA_TOKEN_NULL;
  5786. vocab.special_sep_id = LLAMA_TOKEN_NULL;
  5787. vocab.special_pad_id = LLAMA_TOKEN_NULL;
  5788. vocab.special_cls_id = LLAMA_TOKEN_NULL;
  5789. vocab.special_mask_id = LLAMA_TOKEN_NULL;
  5790. vocab.linefeed_id = LLAMA_TOKEN_NULL;
  5791. // read vocab size from metadata
  5792. if (!ml.get_key(LLM_KV_VOCAB_SIZE, vocab.n_vocab, false)) {
  5793. vocab.n_vocab = 0;
  5794. LLAMA_LOG_WARN("%s: there is no vocab_size in metadata, vocab.n_vocab will be set to %u\n", __func__, vocab.n_vocab);
  5795. }
  5796. return;
  5797. }
  5798. if (tokenizer_model == "llama") {
  5799. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  5800. // default special tokens
  5801. vocab.special_bos_id = 1;
  5802. vocab.special_eos_id = 2;
  5803. vocab.special_unk_id = 0;
  5804. vocab.special_sep_id = LLAMA_TOKEN_NULL;
  5805. vocab.special_pad_id = LLAMA_TOKEN_NULL;
  5806. vocab.special_cls_id = LLAMA_TOKEN_NULL;
  5807. vocab.special_mask_id = LLAMA_TOKEN_NULL;
  5808. } else if (tokenizer_model == "bert") {
  5809. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  5810. // default special tokens
  5811. vocab.special_bos_id = LLAMA_TOKEN_NULL;
  5812. vocab.special_eos_id = LLAMA_TOKEN_NULL;
  5813. vocab.special_unk_id = 100;
  5814. vocab.special_sep_id = 102;
  5815. vocab.special_pad_id = 0;
  5816. vocab.special_cls_id = 101;
  5817. vocab.special_mask_id = 103;
  5818. } else if (tokenizer_model == "gpt2") {
  5819. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  5820. // read bpe merges and populate bpe ranks
  5821. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  5822. if (merges_keyidx == -1) {
  5823. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  5824. }
  5825. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  5826. for (int i = 0; i < n_merges; i++) {
  5827. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  5828. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  5829. std::string first;
  5830. std::string second;
  5831. const size_t pos = word.find(' ', 1);
  5832. if (pos != std::string::npos) {
  5833. first = word.substr(0, pos);
  5834. second = word.substr(pos + 1);
  5835. }
  5836. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  5837. }
  5838. // default special tokens
  5839. vocab.special_bos_id = 11;
  5840. vocab.special_eos_id = 11;
  5841. vocab.special_unk_id = LLAMA_TOKEN_NULL;
  5842. vocab.special_sep_id = LLAMA_TOKEN_NULL;
  5843. vocab.special_pad_id = LLAMA_TOKEN_NULL;
  5844. vocab.special_cls_id = LLAMA_TOKEN_NULL;
  5845. vocab.special_mask_id = LLAMA_TOKEN_NULL;
  5846. } else if (tokenizer_model == "t5") {
  5847. vocab.type = LLAMA_VOCAB_TYPE_UGM;
  5848. // default special tokens
  5849. vocab.special_bos_id = LLAMA_TOKEN_NULL;
  5850. vocab.special_eos_id = 1;
  5851. vocab.special_unk_id = 2;
  5852. vocab.special_sep_id = LLAMA_TOKEN_NULL;
  5853. vocab.special_pad_id = 0;
  5854. vocab.special_cls_id = LLAMA_TOKEN_NULL;
  5855. vocab.special_mask_id = LLAMA_TOKEN_NULL;
  5856. const int precompiled_charsmap_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP).c_str());
  5857. if (precompiled_charsmap_keyidx != -1) {
  5858. size_t n_precompiled_charsmap = gguf_get_arr_n(ctx, precompiled_charsmap_keyidx);
  5859. const char * precompiled_charsmap = (const char *) gguf_get_arr_data(ctx, precompiled_charsmap_keyidx);
  5860. vocab.precompiled_charsmap.assign(precompiled_charsmap, precompiled_charsmap + n_precompiled_charsmap);
  5861. #ifdef IS_BIG_ENDIAN
  5862. // correct endiannes of data in precompiled_charsmap binary blob
  5863. uint32_t * xcda_blob_size = (uint32_t *) &vocab.precompiled_charsmap[0];
  5864. *xcda_blob_size = __builtin_bswap32(*xcda_blob_size);
  5865. assert(*xcda_blob_size + sizeof(uint32_t) < n_precompiled_charsmap);
  5866. size_t xcda_array_size = *xcda_blob_size / sizeof(uint32_t);
  5867. uint32_t * xcda_array = (uint32_t *) &vocab.precompiled_charsmap[sizeof(uint32_t)];
  5868. for (size_t i = 0; i < xcda_array_size; ++i) {
  5869. xcda_array[i] = __builtin_bswap32(xcda_array[i]);
  5870. }
  5871. #endif
  5872. }
  5873. } else if (tokenizer_model == "rwkv") {
  5874. vocab.type = LLAMA_VOCAB_TYPE_RWKV;
  5875. // default special tokens
  5876. vocab.special_bos_id = LLAMA_TOKEN_NULL;
  5877. vocab.special_eos_id = LLAMA_TOKEN_NULL;
  5878. vocab.special_unk_id = LLAMA_TOKEN_NULL;
  5879. vocab.special_sep_id = LLAMA_TOKEN_NULL;
  5880. vocab.special_pad_id = LLAMA_TOKEN_NULL;
  5881. } else {
  5882. throw std::runtime_error(format("unknown tokenizer: '%s'", tokenizer_model.c_str()));
  5883. }
  5884. // for now, only BPE models have pre-tokenizers
  5885. if (vocab.type == LLAMA_VOCAB_TYPE_BPE) {
  5886. vocab.tokenizer_add_space_prefix = false;
  5887. vocab.tokenizer_clean_spaces = true;
  5888. if (tokenizer_pre == "default") {
  5889. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5890. } else if (
  5891. tokenizer_pre == "llama3" ||
  5892. tokenizer_pre == "llama-v3" ||
  5893. tokenizer_pre == "llama-bpe") {
  5894. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_LLAMA3;
  5895. vocab.tokenizer_ignore_merges = true;
  5896. vocab.tokenizer_add_bos = true;
  5897. } else if (
  5898. tokenizer_pre == "deepseek-llm") {
  5899. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM;
  5900. vocab.tokenizer_clean_spaces = false;
  5901. } else if (
  5902. tokenizer_pre == "deepseek-coder") {
  5903. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER;
  5904. vocab.tokenizer_clean_spaces = false;
  5905. } else if (
  5906. tokenizer_pre == "falcon") {
  5907. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_FALCON;
  5908. } else if (
  5909. tokenizer_pre == "mpt") {
  5910. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_MPT;
  5911. } else if (
  5912. tokenizer_pre == "starcoder") {
  5913. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_STARCODER;
  5914. } else if (
  5915. tokenizer_pre == "gpt-2" ||
  5916. tokenizer_pre == "phi-2" ||
  5917. tokenizer_pre == "jina-es" ||
  5918. tokenizer_pre == "jina-de" ||
  5919. tokenizer_pre == "jina-v1-en" ||
  5920. tokenizer_pre == "jina-v2-es" ||
  5921. tokenizer_pre == "jina-v2-de" ||
  5922. tokenizer_pre == "jina-v2-code") {
  5923. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_GPT2;
  5924. } else if (
  5925. tokenizer_pre == "refact") {
  5926. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_REFACT;
  5927. } else if (
  5928. tokenizer_pre == "command-r") {
  5929. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_COMMAND_R;
  5930. vocab.tokenizer_clean_spaces = false;
  5931. } else if (
  5932. tokenizer_pre == "qwen2") {
  5933. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_QWEN2;
  5934. vocab.tokenizer_clean_spaces = false;
  5935. } else if (
  5936. tokenizer_pre == "stablelm2") {
  5937. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_STABLELM2;
  5938. } else if (
  5939. tokenizer_pre == "olmo") {
  5940. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_OLMO;
  5941. } else if (
  5942. tokenizer_pre == "dbrx") {
  5943. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DBRX;
  5944. } else if (
  5945. tokenizer_pre == "smaug-bpe") {
  5946. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_SMAUG;
  5947. } else if (
  5948. tokenizer_pre == "poro-chat") {
  5949. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_PORO;
  5950. vocab.tokenizer_clean_spaces = false;
  5951. } else if (
  5952. tokenizer_pre == "chatglm-bpe") {
  5953. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_CHATGLM4;
  5954. vocab.special_bos_id = LLAMA_TOKEN_NULL;
  5955. } else if (
  5956. tokenizer_pre == "viking") {
  5957. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_VIKING;
  5958. vocab.tokenizer_clean_spaces = false;
  5959. } else if (
  5960. tokenizer_pre == "jais") {
  5961. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_JAIS;
  5962. } else if (
  5963. tokenizer_pre == "tekken") {
  5964. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_TEKKEN;
  5965. vocab.tokenizer_clean_spaces = false;
  5966. vocab.tokenizer_ignore_merges = true;
  5967. vocab.tokenizer_add_bos = true;
  5968. } else if (
  5969. tokenizer_pre == "smollm") {
  5970. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_SMOLLM;
  5971. vocab.tokenizer_clean_spaces = false;
  5972. } else if (
  5973. tokenizer_pre == "codeshell") {
  5974. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_CODESHELL;
  5975. } else if (
  5976. tokenizer_pre == "bloom") {
  5977. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_BLOOM;
  5978. } else if (
  5979. tokenizer_pre == "gpt3-finnish") {
  5980. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_GPT3_FINNISH;
  5981. } else if (
  5982. tokenizer_pre == "exaone") {
  5983. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_EXAONE;
  5984. } else if (
  5985. tokenizer_pre == "chameleon") {
  5986. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_CHAMELEON;
  5987. vocab.tokenizer_add_bos = true;
  5988. vocab.tokenizer_clean_spaces = false;
  5989. } else if (
  5990. tokenizer_pre == "minerva-7b") {
  5991. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_MINERVA;
  5992. } else {
  5993. LLAMA_LOG_WARN("%s: missing or unrecognized pre-tokenizer type, using: 'default'\n", __func__);
  5994. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5995. }
  5996. } else if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  5997. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5998. vocab.tokenizer_add_space_prefix = true;
  5999. vocab.tokenizer_clean_spaces = false;
  6000. vocab.tokenizer_add_bos = true;
  6001. vocab.tokenizer_add_eos = false;
  6002. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  6003. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  6004. vocab.tokenizer_add_space_prefix = false;
  6005. vocab.tokenizer_clean_spaces = true;
  6006. vocab.tokenizer_add_bos = true;
  6007. vocab.tokenizer_add_eos = false;
  6008. } else if (vocab.type == LLAMA_VOCAB_TYPE_UGM) {
  6009. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  6010. vocab.tokenizer_add_bos = false;
  6011. vocab.tokenizer_add_eos = true;
  6012. } else if (vocab.type == LLAMA_VOCAB_TYPE_RWKV) {
  6013. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  6014. vocab.tokenizer_add_space_prefix = false;
  6015. vocab.tokenizer_clean_spaces = false;
  6016. vocab.tokenizer_add_bos = false;
  6017. vocab.tokenizer_add_eos = false;
  6018. } else {
  6019. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  6020. }
  6021. ml.get_key(LLM_KV_TOKENIZER_ADD_PREFIX, vocab.tokenizer_add_space_prefix, false);
  6022. ml.get_key(LLM_KV_TOKENIZER_REMOVE_EXTRA_WS, vocab.tokenizer_remove_extra_whitespaces, false);
  6023. }
  6024. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  6025. if (token_idx == -1) {
  6026. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  6027. }
  6028. const float * scores = nullptr;
  6029. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  6030. if (score_idx != -1) {
  6031. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  6032. }
  6033. const int * toktypes = nullptr;
  6034. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  6035. if (toktype_idx != -1) {
  6036. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  6037. }
  6038. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  6039. vocab.n_vocab = n_vocab;
  6040. vocab.id_to_token.resize(n_vocab);
  6041. for (uint32_t i = 0; i < n_vocab; i++) {
  6042. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  6043. //GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  6044. if (word.empty()) {
  6045. LLAMA_LOG_WARN("%s: empty token at index %u\n", __func__, i);
  6046. word = "[EMPTY_" + std::to_string(i) + "]";
  6047. }
  6048. vocab.token_to_id[word] = i;
  6049. vocab.max_token_len = std::max(vocab.max_token_len, (int) word.size());
  6050. auto & token_data = vocab.id_to_token[i];
  6051. token_data.text = std::move(word);
  6052. token_data.score = scores ? scores[i] : 0.0f;
  6053. token_data.attr = LLAMA_TOKEN_ATTR_NORMAL;
  6054. if (toktypes) { //TODO: remove, required until per token attributes are available from GGUF file
  6055. switch(toktypes[i]) {
  6056. case LLAMA_TOKEN_TYPE_UNKNOWN: token_data.attr = LLAMA_TOKEN_ATTR_UNKNOWN; break;
  6057. case LLAMA_TOKEN_TYPE_UNUSED: token_data.attr = LLAMA_TOKEN_ATTR_UNUSED; break;
  6058. case LLAMA_TOKEN_TYPE_NORMAL: token_data.attr = LLAMA_TOKEN_ATTR_NORMAL; break;
  6059. case LLAMA_TOKEN_TYPE_CONTROL: token_data.attr = LLAMA_TOKEN_ATTR_CONTROL; break;
  6060. case LLAMA_TOKEN_TYPE_USER_DEFINED: token_data.attr = LLAMA_TOKEN_ATTR_USER_DEFINED; break;
  6061. case LLAMA_TOKEN_TYPE_BYTE: token_data.attr = LLAMA_TOKEN_ATTR_BYTE; break;
  6062. case LLAMA_TOKEN_TYPE_UNDEFINED: token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED; break;
  6063. default: token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED; break;
  6064. }
  6065. }
  6066. }
  6067. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  6068. vocab.init_tokenizer();
  6069. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  6070. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  6071. try {
  6072. vocab.linefeed_id = llama_byte_to_token_impl(vocab, '\n');
  6073. } catch (const std::exception & e) {
  6074. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  6075. vocab.linefeed_id = vocab.special_pad_id;
  6076. }
  6077. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  6078. vocab.linefeed_id = vocab.special_pad_id;
  6079. } else if (vocab.type == LLAMA_VOCAB_TYPE_RWKV) {
  6080. const std::vector<int> ids = llama_tokenize_internal(vocab, "\n", false);
  6081. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  6082. vocab.linefeed_id = ids[0];
  6083. } else {
  6084. const std::vector<int> ids = llama_tokenize_internal(vocab, "\xC4\x8A", false); // U+010A
  6085. //GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  6086. if (ids.empty()) {
  6087. LLAMA_LOG_WARN("%s: model vocab missing newline token, using special_pad_id instead\n", __func__);
  6088. vocab.linefeed_id = vocab.special_pad_id;
  6089. } else {
  6090. vocab.linefeed_id = ids[0];
  6091. }
  6092. }
  6093. // special tokens
  6094. {
  6095. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  6096. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  6097. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  6098. { LLM_KV_TOKENIZER_EOT_ID, vocab.special_eot_id },
  6099. { LLM_KV_TOKENIZER_EOM_ID, vocab.special_eom_id },
  6100. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  6101. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  6102. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  6103. { LLM_KV_TOKENIZER_CLS_ID, vocab.special_cls_id },
  6104. { LLM_KV_TOKENIZER_MASK_ID, vocab.special_mask_id },
  6105. { LLM_KV_TOKENIZER_FIM_PRE_ID, vocab.special_fim_pre_id },
  6106. { LLM_KV_TOKENIZER_FIM_SUF_ID, vocab.special_fim_suf_id },
  6107. { LLM_KV_TOKENIZER_FIM_MID_ID, vocab.special_fim_mid_id },
  6108. { LLM_KV_TOKENIZER_FIM_PAD_ID, vocab.special_fim_pad_id },
  6109. { LLM_KV_TOKENIZER_FIM_REP_ID, vocab.special_fim_rep_id },
  6110. { LLM_KV_TOKENIZER_FIM_SEP_ID, vocab.special_fim_sep_id },
  6111. // deprecated
  6112. { LLM_KV_TOKENIZER_PREFIX_ID, vocab.special_fim_pre_id },
  6113. { LLM_KV_TOKENIZER_SUFFIX_ID, vocab.special_fim_suf_id },
  6114. { LLM_KV_TOKENIZER_MIDDLE_ID, vocab.special_fim_mid_id },
  6115. };
  6116. for (const auto & it : special_token_types) {
  6117. const std::string & key = kv(std::get<0>(it));
  6118. int32_t & id = std::get<1>(it);
  6119. uint32_t new_id;
  6120. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  6121. continue;
  6122. }
  6123. if (new_id >= vocab.id_to_token.size()) {
  6124. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  6125. __func__, key.c_str(), new_id, id);
  6126. } else {
  6127. id = new_id;
  6128. }
  6129. }
  6130. // Handle add_bos_token and add_eos_token
  6131. {
  6132. bool temp = true;
  6133. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  6134. vocab.tokenizer_add_bos = temp;
  6135. }
  6136. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  6137. vocab.tokenizer_add_eos = temp;
  6138. }
  6139. }
  6140. // auto-detect special tokens by text
  6141. // TODO: convert scripts should provide these tokens through the KV metadata LLM_KV_TOKENIZER_...
  6142. // for now, we apply this workaround to find the tokens based on their text
  6143. for (const auto & t : vocab.token_to_id) {
  6144. // find EOT token: "<|eot_id|>", "<|im_end|>", "<end_of_turn>", etc.
  6145. if (vocab.special_eot_id == LLAMA_TOKEN_NULL) {
  6146. if (false
  6147. || t.first == "<|eot_id|>"
  6148. || t.first == "<|im_end|>"
  6149. || t.first == "<|end|>"
  6150. || t.first == "<end_of_turn>"
  6151. || t.first == "<|endoftext|>"
  6152. || t.first == "<EOT>"
  6153. || t.first == "<|end▁of▁sentence|>" // DeepSeek
  6154. ) {
  6155. vocab.special_eot_id = t.second;
  6156. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6157. 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",
  6158. __func__, t.second, t.first.c_str());
  6159. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6160. }
  6161. }
  6162. }
  6163. // find EOM token: "<|eom_id|>"
  6164. if (vocab.special_eom_id == LLAMA_TOKEN_NULL) {
  6165. if (false
  6166. || t.first == "<|eom_id|>"
  6167. ) {
  6168. vocab.special_eom_id = t.second;
  6169. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6170. 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",
  6171. __func__, t.second, t.first.c_str());
  6172. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6173. }
  6174. }
  6175. }
  6176. // find FIM_PRE token: "<|fim_prefix|>", "<fim-prefix>", "<PRE>", etc.
  6177. if (vocab.special_fim_pre_id == LLAMA_TOKEN_NULL) {
  6178. if (false
  6179. || t.first == "<|fim_prefix|>" // Qwen
  6180. || t.first == "<fim-prefix>"
  6181. || t.first == "<|fim▁begin|>" // DeepSeek
  6182. || t.first == "<PRE>"
  6183. ) {
  6184. vocab.special_fim_pre_id = t.second;
  6185. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6186. 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",
  6187. __func__, t.second, t.first.c_str());
  6188. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6189. }
  6190. }
  6191. }
  6192. // find FIM_SUF token: "<|fim_suffix|>", "<fim-suffix>", "<SUF>", etc.
  6193. if (vocab.special_fim_suf_id == LLAMA_TOKEN_NULL) {
  6194. if (false
  6195. || t.first == "<|fim_suffix|>" // Qwen
  6196. || t.first == "<fim-suffix>"
  6197. || t.first == "<|fim▁hole|>" // DeepSeek
  6198. || t.first == "<SUF>"
  6199. ) {
  6200. vocab.special_fim_suf_id = t.second;
  6201. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6202. 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",
  6203. __func__, t.second, t.first.c_str());
  6204. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6205. }
  6206. }
  6207. }
  6208. // find FIM_MID token: "<|fim_middle|>", "<fim-middle>", "<MID>", etc.
  6209. if (vocab.special_fim_mid_id == LLAMA_TOKEN_NULL) {
  6210. if (false
  6211. || t.first == "<|fim_middle|>" // Qwen
  6212. || t.first == "<fim-middle>"
  6213. || t.first == "<|fim▁end|>" // DeepSeek
  6214. || t.first == "<MID>"
  6215. ) {
  6216. vocab.special_fim_mid_id = t.second;
  6217. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6218. 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",
  6219. __func__, t.second, t.first.c_str());
  6220. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6221. }
  6222. }
  6223. }
  6224. // find FIM_PAD token: "<|fim_pad|>", "<fim-pad>", "<PAD>", etc.
  6225. if (vocab.special_fim_pad_id == LLAMA_TOKEN_NULL) {
  6226. if (false
  6227. || t.first == "<|fim_pad|>" // Qwen
  6228. || t.first == "<fim-pad>"
  6229. || t.first == "<PAD>"
  6230. ) {
  6231. vocab.special_fim_pad_id = t.second;
  6232. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6233. 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",
  6234. __func__, t.second, t.first.c_str());
  6235. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6236. }
  6237. }
  6238. }
  6239. // find FIM_REP token: "<|fim_repo|>", "<fim-repo>", "<REP>", etc.
  6240. if (vocab.special_fim_rep_id == LLAMA_TOKEN_NULL) {
  6241. if (false
  6242. || t.first == "<|fim_repo|>" // Qwen
  6243. || t.first == "<|repo_name|>"
  6244. || t.first == "<fim-repo>"
  6245. || t.first == "<REPO>"
  6246. ) {
  6247. vocab.special_fim_rep_id = t.second;
  6248. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6249. 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",
  6250. __func__, t.second, t.first.c_str());
  6251. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6252. }
  6253. }
  6254. }
  6255. // find FIM_SEP token: "<|file_sep|>"
  6256. if (vocab.special_fim_sep_id == LLAMA_TOKEN_NULL) {
  6257. if (false
  6258. || t.first == "<|file_sep|>" // Qwen
  6259. ) {
  6260. vocab.special_fim_sep_id = t.second;
  6261. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6262. 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",
  6263. __func__, t.second, t.first.c_str());
  6264. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6265. }
  6266. }
  6267. }
  6268. }
  6269. // maintain a list of tokens that cause end-of-generation
  6270. // this is currently determined based on the token text, which is obviously not ideal
  6271. // ref: https://github.com/ggerganov/llama.cpp/issues/9606
  6272. vocab.special_eog_ids.clear();
  6273. if (vocab.special_fim_pad_id != LLAMA_TOKEN_NULL && vocab.special_eog_ids.count(vocab.special_fim_pad_id) == 0) {
  6274. vocab.special_eog_ids.insert(vocab.special_fim_pad_id);
  6275. }
  6276. if (vocab.special_fim_rep_id != LLAMA_TOKEN_NULL && vocab.special_eog_ids.count(vocab.special_fim_rep_id) == 0) {
  6277. vocab.special_eog_ids.insert(vocab.special_fim_rep_id);
  6278. }
  6279. if (vocab.special_fim_sep_id != LLAMA_TOKEN_NULL && vocab.special_eog_ids.count(vocab.special_fim_sep_id) == 0) {
  6280. vocab.special_eog_ids.insert(vocab.special_fim_sep_id);
  6281. }
  6282. for (const auto & t : vocab.token_to_id) {
  6283. if (false
  6284. || t.first == "<|eot_id|>"
  6285. || t.first == "<|im_end|>"
  6286. || t.first == "<|end|>"
  6287. || t.first == "<end_of_turn>"
  6288. || t.first == "<|endoftext|>"
  6289. || t.first == "<|eom_id|>"
  6290. || t.first == "<EOT>"
  6291. ) {
  6292. vocab.special_eog_ids.insert(t.second);
  6293. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6294. 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",
  6295. __func__, t.second, t.first.c_str());
  6296. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6297. }
  6298. } else {
  6299. // token is control, but not marked as EOG -> print a debug log
  6300. if (vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL && vocab.special_eog_ids.count(t.second) == 0) {
  6301. LLAMA_LOG_DEBUG("%s: control token: %6d '%s' is not marked as EOG\n",
  6302. __func__, t.second, t.first.c_str());
  6303. }
  6304. }
  6305. }
  6306. // sanity checks
  6307. if (vocab.special_eos_id != LLAMA_TOKEN_NULL && vocab.special_eog_ids.count(vocab.special_eos_id) == 0) {
  6308. vocab.special_eog_ids.insert(vocab.special_eos_id);
  6309. LLAMA_LOG_WARN("%s: special_eos_id is not in special_eog_ids - the tokenizer config may be incorrect\n", __func__);
  6310. }
  6311. if (vocab.special_eot_id != LLAMA_TOKEN_NULL && vocab.special_eog_ids.count(vocab.special_eot_id) == 0) {
  6312. vocab.special_eog_ids.insert(vocab.special_eot_id);
  6313. LLAMA_LOG_WARN("%s: special_eot_id is not in special_eog_ids - the tokenizer config may be incorrect\n", __func__);
  6314. }
  6315. if (vocab.special_eom_id != LLAMA_TOKEN_NULL && vocab.special_eog_ids.count(vocab.special_eom_id) == 0) {
  6316. vocab.special_eog_ids.insert(vocab.special_eom_id);
  6317. LLAMA_LOG_WARN("%s: special_eom_id is not in special_eog_ids - the tokenizer config may be incorrect\n", __func__);
  6318. }
  6319. }
  6320. // build special tokens cache
  6321. {
  6322. for (llama_vocab::id id = 0; id < (llama_vocab::id)n_vocab; ++id) {
  6323. if (vocab.id_to_token[id].attr & (LLAMA_TOKEN_ATTR_CONTROL | LLAMA_TOKEN_ATTR_USER_DEFINED | LLAMA_TOKEN_ATTR_UNKNOWN)) {
  6324. vocab.cache_special_tokens.push_back(id);
  6325. }
  6326. }
  6327. std::sort(vocab.cache_special_tokens.begin(), vocab.cache_special_tokens.end(),
  6328. [&] (const llama_vocab::id a, const llama_vocab::id b) {
  6329. return vocab.id_to_token[a].text.size() > vocab.id_to_token[b].text.size();
  6330. }
  6331. );
  6332. LLAMA_LOG_INFO("%s: special tokens cache size = %u\n", __func__, (uint32_t)vocab.cache_special_tokens.size());
  6333. }
  6334. // build token to piece cache
  6335. {
  6336. size_t size_cache = 0;
  6337. std::vector<llama_vocab::token> cache_token_to_piece(n_vocab);
  6338. for (uint32_t id = 0; id < n_vocab; ++id) {
  6339. cache_token_to_piece[id] = llama_token_to_piece(&model, id, true);
  6340. size_cache += cache_token_to_piece[id].size();
  6341. }
  6342. std::swap(vocab.cache_token_to_piece, cache_token_to_piece);
  6343. LLAMA_LOG_INFO("%s: token to piece cache size = %.4f MB\n", __func__, size_cache / 1024.0 / 1024.0);
  6344. }
  6345. // Handle per token attributes
  6346. //NOTE: Each model customizes per token attributes.
  6347. //NOTE: Per token attributes are missing from the GGUF file.
  6348. //TODO: Extract attributes from GGUF file.
  6349. {
  6350. auto _contains_any = [] (const std::string &str, const std::vector<std::string> &substrs) -> bool {
  6351. for (auto substr : substrs) {
  6352. if (str.find(substr) < std::string::npos) {
  6353. return true;
  6354. }
  6355. }
  6356. return false;
  6357. };
  6358. auto _set_tokenid_attr = [&] (const llama_vocab::id id, llama_token_attr attr, bool value) {
  6359. uint32_t current = vocab.id_to_token.at(id).attr;
  6360. current = value ? (current | attr) : (current & ~attr);
  6361. vocab.id_to_token[id].attr = (llama_token_attr) current;
  6362. };
  6363. auto _set_token_attr = [&] (const std::string & token, llama_token_attr attr, bool value) {
  6364. _set_tokenid_attr(vocab.token_to_id.at(token), attr, value);
  6365. };
  6366. std::string model_name;
  6367. std::string tokenizer_pre;
  6368. ml.get_key(LLM_KV_GENERAL_NAME, model_name, false);
  6369. ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false);
  6370. // model name to lowercase
  6371. std::transform(model_name.begin(), model_name.end(), model_name.begin(),
  6372. [] (const std::string::value_type x) {
  6373. return std::tolower(x);
  6374. }
  6375. );
  6376. // set attributes by model/tokenizer name
  6377. if (_contains_any(tokenizer_pre, {"jina-v2-de", "jina-v2-es", "jina-v2-code"})) {
  6378. _set_token_attr("<mask>", LLAMA_TOKEN_ATTR_LSTRIP, true);
  6379. } else if (_contains_any(model_name, {"phi-3", "phi3"})) {
  6380. for (auto id : vocab.cache_special_tokens) {
  6381. _set_tokenid_attr(id, LLAMA_TOKEN_ATTR_RSTRIP, true);
  6382. }
  6383. for (auto token : {"</s>"}) {
  6384. _set_token_attr(token, LLAMA_TOKEN_ATTR_RSTRIP, true);
  6385. }
  6386. for (auto token : {"<unk>", "<s>", "<|endoftext|>"}) {
  6387. _set_token_attr(token, LLAMA_TOKEN_ATTR_RSTRIP, false);
  6388. }
  6389. }
  6390. }
  6391. }
  6392. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  6393. const auto & hparams = model.hparams;
  6394. const auto & vocab = model.vocab;
  6395. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  6396. auto print_f = [](const std::function<uint32_t(uint32_t)> & f, uint32_t n) {
  6397. bool is_var = false;
  6398. std::vector<uint32_t> v;
  6399. for (uint32_t i = 0; i < n; ++i) {
  6400. v.push_back(f(i));
  6401. if (v[i] != v[0]) {
  6402. is_var = true;
  6403. }
  6404. }
  6405. std::stringstream ss;
  6406. if (is_var) {
  6407. ss << "[";
  6408. for (uint32_t i = 0; i < n; ++i) {
  6409. ss << v[i];
  6410. if (i < n - 1) {
  6411. ss << ", ";
  6412. }
  6413. }
  6414. ss << "]";
  6415. } else {
  6416. ss << v[0];
  6417. }
  6418. return ss.str();
  6419. };
  6420. // hparams
  6421. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  6422. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  6423. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  6424. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  6425. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  6426. LLAMA_LOG_INFO("%s: vocab_only = %d\n", __func__, hparams.vocab_only);
  6427. if (!hparams.vocab_only) {
  6428. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  6429. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  6430. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  6431. LLAMA_LOG_INFO("%s: n_head = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_head(il); }, hparams.n_layer).c_str());
  6432. 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());
  6433. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  6434. LLAMA_LOG_INFO("%s: n_swa = %u\n", __func__, hparams.n_swa);
  6435. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  6436. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  6437. LLAMA_LOG_INFO("%s: n_gqa = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_gqa(il); }, hparams.n_layer).c_str());
  6438. 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());
  6439. 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());
  6440. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  6441. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  6442. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  6443. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  6444. LLAMA_LOG_INFO("%s: f_logit_scale = %.1e\n", __func__, hparams.f_logit_scale);
  6445. LLAMA_LOG_INFO("%s: n_ff = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_ff(il); }, hparams.n_layer).c_str());
  6446. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  6447. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  6448. LLAMA_LOG_INFO("%s: causal attn = %d\n", __func__, hparams.causal_attn);
  6449. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  6450. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  6451. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  6452. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  6453. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  6454. LLAMA_LOG_INFO("%s: n_ctx_orig_yarn = %u\n", __func__, hparams.n_ctx_orig_yarn);
  6455. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  6456. LLAMA_LOG_INFO("%s: ssm_d_conv = %u\n", __func__, hparams.ssm_d_conv);
  6457. LLAMA_LOG_INFO("%s: ssm_d_inner = %u\n", __func__, hparams.ssm_d_inner);
  6458. LLAMA_LOG_INFO("%s: ssm_d_state = %u\n", __func__, hparams.ssm_d_state);
  6459. LLAMA_LOG_INFO("%s: ssm_dt_rank = %u\n", __func__, hparams.ssm_dt_rank);
  6460. LLAMA_LOG_INFO("%s: ssm_dt_b_c_rms = %d\n", __func__, hparams.ssm_dt_b_c_rms);
  6461. }
  6462. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  6463. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  6464. if (ml.n_elements >= 1e12) {
  6465. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  6466. } else if (ml.n_elements >= 1e9) {
  6467. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  6468. } else if (ml.n_elements >= 1e6) {
  6469. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  6470. } else {
  6471. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  6472. }
  6473. if (ml.n_bytes < GiB) {
  6474. 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);
  6475. } else {
  6476. 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);
  6477. }
  6478. // general kv
  6479. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  6480. // special tokens
  6481. 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() ); }
  6482. 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() ); }
  6483. 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() ); }
  6484. 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() ); }
  6485. 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() ); }
  6486. 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() ); }
  6487. 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() ); }
  6488. 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() ); }
  6489. 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() ); }
  6490. 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() ); }
  6491. 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() ); }
  6492. 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() ); }
  6493. 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() ); }
  6494. 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() ); }
  6495. 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() ); }
  6496. 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() ); }
  6497. for (const auto & id : vocab.special_eog_ids) {
  6498. LLAMA_LOG_INFO( "%s: EOG token = %d '%s'\n", __func__, id, vocab.id_to_token[id].text.c_str() );
  6499. }
  6500. LLAMA_LOG_INFO("%s: max token length = %d\n", __func__, vocab.max_token_len);
  6501. if (model.arch == LLM_ARCH_DEEPSEEK2) {
  6502. LLAMA_LOG_INFO("%s: n_layer_dense_lead = %d\n", __func__, hparams.n_layer_dense_lead);
  6503. LLAMA_LOG_INFO("%s: n_lora_q = %d\n", __func__, hparams.n_lora_q);
  6504. LLAMA_LOG_INFO("%s: n_lora_kv = %d\n", __func__, hparams.n_lora_kv);
  6505. LLAMA_LOG_INFO("%s: n_ff_exp = %d\n", __func__, hparams.n_ff_exp);
  6506. LLAMA_LOG_INFO("%s: n_expert_shared = %d\n", __func__, hparams.n_expert_shared);
  6507. LLAMA_LOG_INFO("%s: expert_weights_scale = %.1f\n", __func__, hparams.expert_weights_scale);
  6508. LLAMA_LOG_INFO("%s: rope_yarn_log_mul = %.4f\n", __func__, hparams.rope_yarn_log_mul);
  6509. }
  6510. if (model.arch == LLM_ARCH_QWEN2MOE) {
  6511. LLAMA_LOG_INFO("%s: n_ff_exp = %d\n", __func__, hparams.n_ff_exp);
  6512. LLAMA_LOG_INFO("%s: n_ff_shexp = %d\n", __func__, hparams.n_ff_shexp);
  6513. }
  6514. if (model.arch == LLM_ARCH_MINICPM || model.arch == LLM_ARCH_GRANITE || model.arch == LLM_ARCH_GRANITE_MOE) {
  6515. LLAMA_LOG_INFO("%s: f_embedding_scale = %f\n", __func__, hparams.f_embedding_scale);
  6516. LLAMA_LOG_INFO("%s: f_residual_scale = %f\n", __func__, hparams.f_residual_scale);
  6517. LLAMA_LOG_INFO("%s: f_attention_scale = %f\n", __func__, hparams.f_attention_scale);
  6518. }
  6519. }
  6520. enum llm_tensor_layer {
  6521. LLM_TENSOR_LAYER_INPUT,
  6522. LLM_TENSOR_LAYER_REPEATING,
  6523. LLM_TENSOR_LAYER_OUTPUT,
  6524. };
  6525. struct llm_tensor_info {
  6526. llm_tensor_layer layer;
  6527. ggml_op op;
  6528. };
  6529. static const std::map<llm_tensor, llm_tensor_info> llm_tensor_info_mapping = {
  6530. {LLM_TENSOR_TOKEN_EMBD, {LLM_TENSOR_LAYER_INPUT, GGML_OP_GET_ROWS}},
  6531. {LLM_TENSOR_POS_EMBD, {LLM_TENSOR_LAYER_INPUT, GGML_OP_GET_ROWS}},
  6532. {LLM_TENSOR_TOKEN_EMBD_NORM, {LLM_TENSOR_LAYER_INPUT, GGML_OP_GET_ROWS}},
  6533. {LLM_TENSOR_TOKEN_TYPES, {LLM_TENSOR_LAYER_INPUT, GGML_OP_GET_ROWS}},
  6534. {LLM_TENSOR_OUTPUT, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}},
  6535. {LLM_TENSOR_CLS, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}},
  6536. {LLM_TENSOR_CLS_OUT, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}},
  6537. {LLM_TENSOR_OUTPUT_NORM, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL}},
  6538. {LLM_TENSOR_DEC_OUTPUT_NORM, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL}},
  6539. {LLM_TENSOR_ENC_OUTPUT_NORM, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL}},
  6540. {LLM_TENSOR_ROPE_FREQS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ROPE}},
  6541. {LLM_TENSOR_ROPE_FACTORS_LONG, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ROPE}},
  6542. {LLM_TENSOR_ROPE_FACTORS_SHORT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ROPE}},
  6543. {LLM_TENSOR_ATTN_Q, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6544. {LLM_TENSOR_ATTN_K, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6545. {LLM_TENSOR_ATTN_V, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6546. {LLM_TENSOR_ATTN_QKV, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6547. {LLM_TENSOR_ATTN_OUT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6548. {LLM_TENSOR_FFN_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6549. {LLM_TENSOR_FFN_DOWN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6550. {LLM_TENSOR_FFN_UP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6551. {LLM_TENSOR_FFN_DOWN_SHEXP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6552. {LLM_TENSOR_FFN_GATE_SHEXP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6553. {LLM_TENSOR_FFN_UP_SHEXP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6554. {LLM_TENSOR_ATTN_Q_A, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6555. {LLM_TENSOR_ATTN_Q_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6556. {LLM_TENSOR_ATTN_KV_A_MQA, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6557. {LLM_TENSOR_ATTN_KV_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6558. {LLM_TENSOR_DEC_ATTN_Q, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6559. {LLM_TENSOR_DEC_ATTN_K, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6560. {LLM_TENSOR_ATTN_Q, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6561. {LLM_TENSOR_ATTN_K, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6562. {LLM_TENSOR_ATTN_V, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6563. {LLM_TENSOR_ATTN_QKV, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6564. {LLM_TENSOR_ATTN_OUT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6565. {LLM_TENSOR_FFN_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6566. {LLM_TENSOR_FFN_DOWN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6567. {LLM_TENSOR_FFN_UP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6568. {LLM_TENSOR_FFN_DOWN_SHEXP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6569. {LLM_TENSOR_FFN_GATE_SHEXP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6570. {LLM_TENSOR_FFN_UP_SHEXP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6571. {LLM_TENSOR_ATTN_Q_A, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6572. {LLM_TENSOR_ATTN_Q_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6573. {LLM_TENSOR_ATTN_KV_A_MQA, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6574. {LLM_TENSOR_ATTN_KV_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6575. {LLM_TENSOR_DEC_ATTN_Q, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6576. {LLM_TENSOR_DEC_ATTN_K, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6577. {LLM_TENSOR_DEC_ATTN_V, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6578. {LLM_TENSOR_DEC_ATTN_OUT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6579. {LLM_TENSOR_DEC_CROSS_ATTN_Q, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6580. {LLM_TENSOR_DEC_CROSS_ATTN_K, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6581. {LLM_TENSOR_DEC_CROSS_ATTN_V, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6582. {LLM_TENSOR_DEC_CROSS_ATTN_OUT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6583. {LLM_TENSOR_DEC_FFN_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6584. {LLM_TENSOR_DEC_FFN_DOWN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6585. {LLM_TENSOR_DEC_FFN_UP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6586. {LLM_TENSOR_ENC_ATTN_Q, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6587. {LLM_TENSOR_ENC_ATTN_K, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6588. {LLM_TENSOR_ENC_ATTN_V, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6589. {LLM_TENSOR_ENC_ATTN_OUT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6590. {LLM_TENSOR_ENC_FFN_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6591. {LLM_TENSOR_ENC_FFN_DOWN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6592. {LLM_TENSOR_ENC_FFN_UP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6593. {LLM_TENSOR_FFN_GATE_INP_SHEXP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6594. {LLM_TENSOR_FFN_GATE_INP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6595. {LLM_TENSOR_SSM_IN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6596. {LLM_TENSOR_SSM_X, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6597. {LLM_TENSOR_SSM_DT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6598. {LLM_TENSOR_SSM_OUT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6599. {LLM_TENSOR_TIME_MIX_W1, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6600. {LLM_TENSOR_TIME_MIX_W2, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6601. {LLM_TENSOR_TIME_MIX_DECAY_W1, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6602. {LLM_TENSOR_TIME_MIX_DECAY_W2, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6603. {LLM_TENSOR_TIME_MIX_KEY, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6604. {LLM_TENSOR_TIME_MIX_VALUE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6605. {LLM_TENSOR_TIME_MIX_RECEPTANCE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6606. {LLM_TENSOR_TIME_MIX_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6607. {LLM_TENSOR_TIME_MIX_OUTPUT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6608. {LLM_TENSOR_CHANNEL_MIX_KEY, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6609. {LLM_TENSOR_CHANNEL_MIX_RECEPTANCE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6610. {LLM_TENSOR_CHANNEL_MIX_VALUE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6611. {LLM_TENSOR_FFN_ACT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_DIV}},
  6612. {LLM_TENSOR_SSM_CONV1D, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_SSM_CONV}},
  6613. {LLM_TENSOR_SSM_A, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_SSM_SCAN}},
  6614. {LLM_TENSOR_SSM_D, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6615. {LLM_TENSOR_TIME_MIX_LERP_X, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6616. {LLM_TENSOR_TIME_MIX_LN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6617. {LLM_TENSOR_CHANNEL_MIX_LERP_K, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6618. {LLM_TENSOR_CHANNEL_MIX_LERP_R, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6619. {LLM_TENSOR_TIME_MIX_LERP_W, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}},
  6620. {LLM_TENSOR_TIME_MIX_LERP_K, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}},
  6621. {LLM_TENSOR_TIME_MIX_LERP_V, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}},
  6622. {LLM_TENSOR_TIME_MIX_LERP_R, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}},
  6623. {LLM_TENSOR_TIME_MIX_LERP_G, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}},
  6624. {LLM_TENSOR_TIME_MIX_DECAY, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}},
  6625. {LLM_TENSOR_TIME_MIX_FIRST, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_RWKV_WKV6}},
  6626. {LLM_TENSOR_ATTN_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6627. {LLM_TENSOR_ATTN_NORM_2, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6628. {LLM_TENSOR_ATTN_OUT_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6629. {LLM_TENSOR_ATTN_POST_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6630. {LLM_TENSOR_FFN_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6631. {LLM_TENSOR_FFN_POST_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6632. {LLM_TENSOR_FFN_NORM_EXPS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6633. {LLM_TENSOR_ATTN_Q_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6634. {LLM_TENSOR_ATTN_K_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6635. {LLM_TENSOR_LAYER_OUT_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6636. {LLM_TENSOR_ATTN_Q_A_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6637. {LLM_TENSOR_ATTN_KV_A_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6638. {LLM_TENSOR_ATTN_SUB_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6639. {LLM_TENSOR_FFN_SUB_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6640. {LLM_TENSOR_DEC_ATTN_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6641. {LLM_TENSOR_DEC_CROSS_ATTN_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6642. {LLM_TENSOR_DEC_FFN_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6643. {LLM_TENSOR_ENC_ATTN_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6644. {LLM_TENSOR_ENC_FFN_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6645. {LLM_TENSOR_DEC_ATTN_REL_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_GET_ROWS}},
  6646. {LLM_TENSOR_ENC_ATTN_REL_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_GET_ROWS}},
  6647. {LLM_TENSOR_FFN_DOWN_EXPS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT_ID}},
  6648. {LLM_TENSOR_FFN_GATE_EXPS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT_ID}},
  6649. {LLM_TENSOR_FFN_UP_EXPS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT_ID}},
  6650. // this tensor is loaded for T5, but never used
  6651. {LLM_TENSOR_DEC_CROSS_ATTN_REL_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_NONE}},
  6652. {LLM_TENSOR_BSKCN_TV, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6653. {LLM_TENSOR_CROSS_ATTN_K_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6654. {LLM_TENSOR_CROSS_ATTN_K_PROJ, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6655. {LLM_TENSOR_CROSS_ATTN_O_PROJ, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6656. {LLM_TENSOR_CROSS_ATTN_Q_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6657. {LLM_TENSOR_CROSS_ATTN_Q_PROJ, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6658. {LLM_TENSOR_CROSS_ATTN_V_PROJ, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  6659. {LLM_TENSOR_CROSS_ATTN_ATTN_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6660. {LLM_TENSOR_CROSS_ATTN_MLP_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  6661. };
  6662. // checks if the weight tensor can be used with the specified buffer type and device
  6663. 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) {
  6664. GGML_ASSERT(w != nullptr);
  6665. if (op == GGML_OP_NONE) {
  6666. return true;
  6667. }
  6668. ggml_init_params params = {
  6669. /*.mem_size =*/ ggml_tensor_overhead()*8,
  6670. /*.mem_buffer =*/ NULL,
  6671. /*.no_alloc =*/ true,
  6672. };
  6673. ggml_context_ptr ctx_ptr { ggml_init(params) };
  6674. if (!ctx_ptr) {
  6675. throw std::runtime_error(format("failed to create ggml context"));
  6676. }
  6677. ggml_context * ctx = ctx_ptr.get();
  6678. ggml_tensor * op_tensor = nullptr;
  6679. switch (op) {
  6680. case GGML_OP_GET_ROWS:
  6681. {
  6682. ggml_tensor * b = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 512);
  6683. op_tensor = ggml_get_rows(ctx, w, b);
  6684. } break;
  6685. case GGML_OP_MUL_MAT:
  6686. {
  6687. ggml_tensor * b = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, w->ne[0], 512, w->ne[2], w->ne[3]);
  6688. op_tensor = ggml_mul_mat(ctx, w, b);
  6689. } break;
  6690. case GGML_OP_MUL_MAT_ID:
  6691. {
  6692. int n_expert_used = hparams.n_expert_used;
  6693. ggml_tensor * b = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, w->ne[0], n_expert_used, 512);
  6694. ggml_tensor * ids = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, n_expert_used, 512);
  6695. op_tensor = ggml_mul_mat_id(ctx, w, b, ids);
  6696. } break;
  6697. case GGML_OP_ADD:
  6698. {
  6699. ggml_tensor * a = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, w->ne[0], w->ne[1], w->ne[2], w->ne[3]);
  6700. op_tensor = ggml_add(ctx, a, w);
  6701. } break;
  6702. case GGML_OP_MUL:
  6703. {
  6704. ggml_tensor * a = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, w->ne[0], w->ne[1], w->ne[2], w->ne[3]);
  6705. op_tensor = ggml_mul(ctx, a, w);
  6706. } break;
  6707. case GGML_OP_DIV:
  6708. {
  6709. ggml_tensor * a = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, w->ne[0]);
  6710. op_tensor = ggml_div(ctx, a, w);
  6711. } break;
  6712. case GGML_OP_ROPE:
  6713. {
  6714. int n_embd_head = hparams.n_embd_head_v;
  6715. int n_head = hparams.n_head();
  6716. ggml_tensor * a = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n_embd_head, n_head, 512);
  6717. ggml_tensor * b = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 512);
  6718. op_tensor = ggml_rope_ext(
  6719. ctx, a, b, w,
  6720. 0, 0, 0, 0, 0,
  6721. 0, 0, 0, 0
  6722. );
  6723. } break;
  6724. case GGML_OP_SSM_CONV:
  6725. {
  6726. // FIXME
  6727. ggml_tensor * conv_x = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, 12345, w->ne[1], 6789);
  6728. op_tensor = ggml_ssm_conv(ctx, conv_x, w);
  6729. } break;
  6730. case GGML_OP_SSM_SCAN:
  6731. {
  6732. // FIXME
  6733. const int64_t d_state = w->ne[0];
  6734. const int64_t d_inner = w->ne[1];
  6735. const int64_t n_seq_tokens = 512;
  6736. const int64_t n_seqs = 1;
  6737. ggml_tensor * s = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, d_state, d_inner, n_seqs);
  6738. ggml_tensor * x = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, d_inner, n_seq_tokens, n_seqs);
  6739. ggml_tensor * dt = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, d_inner, n_seq_tokens, n_seqs);
  6740. ggml_tensor * B = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, d_state, n_seq_tokens, n_seqs);
  6741. ggml_tensor * C = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, d_state, n_seq_tokens, n_seqs);
  6742. op_tensor = ggml_ssm_scan(ctx, s, x, dt, w, B, C);
  6743. } break;
  6744. case GGML_OP_RWKV_WKV6:
  6745. {
  6746. // FIXME
  6747. const int64_t S = 123;
  6748. const int64_t H = 123;
  6749. const int64_t n_tokens = 123;
  6750. const int64_t n_seqs = 123;
  6751. ggml_tensor * k = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, 1, H, n_tokens);
  6752. ggml_tensor * v = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 1, S, H, n_tokens);
  6753. ggml_tensor * r = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 1, S, H, n_tokens);
  6754. ggml_tensor * tf = w;
  6755. ggml_tensor * td = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 1, S, H, n_tokens);
  6756. ggml_tensor * state = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, n_seqs, S, H);
  6757. op_tensor = ggml_rwkv_wkv6(ctx, k, v, r, tf, td, state);
  6758. } break;
  6759. default:
  6760. GGML_ABORT("%s: missing test for op %s for tensor %s", __func__, ggml_op_name(op), w->name);
  6761. }
  6762. // create a temporary dummy buffer for the weight so that supports_op can check the buffer type
  6763. GGML_ASSERT(w->buffer == nullptr);
  6764. w->buffer = ggml_backend_buft_alloc_buffer(buft, 0);
  6765. bool op_supported = ggml_backend_dev_supports_op(dev, op_tensor);
  6766. ggml_backend_buffer_free(w->buffer);
  6767. w->buffer = nullptr;
  6768. return op_supported;
  6769. }
  6770. // find the first buffer type in the list that can use the tensor
  6771. 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) {
  6772. GGML_ASSERT(!buft_list.empty());
  6773. for (const auto & cur : buft_list) {
  6774. ggml_backend_dev_t cur_dev = cur.first;
  6775. ggml_backend_buffer_type_t cur_buft = cur.second;
  6776. if (weight_buft_supported(model.hparams, tensor, op, cur_buft, cur_dev)) {
  6777. return cur_buft;
  6778. }
  6779. }
  6780. return nullptr;
  6781. }
  6782. // CPU: ACCEL -> CPU extra -> GPU host -> CPU
  6783. static llama_model::buft_list_t make_cpu_buft_list(llama_model & model) {
  6784. llama_model::buft_list_t buft_list;
  6785. // add ACCEL buffer types
  6786. for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
  6787. ggml_backend_dev_t dev = ggml_backend_dev_get(i);
  6788. if (ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_ACCEL) {
  6789. auto * buft = ggml_backend_dev_buffer_type(dev);
  6790. // skip
  6791. if (buft != ggml_backend_cpu_buffer_type()) {
  6792. buft_list.emplace_back(dev, buft);
  6793. }
  6794. }
  6795. }
  6796. // add extra buffer types
  6797. auto * cpu_dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
  6798. auto * cpu_reg = ggml_backend_dev_backend_reg(cpu_dev);
  6799. auto ggml_backend_dev_get_extra_bufts_fn = (ggml_backend_dev_get_extra_bufts_t)
  6800. ggml_backend_reg_get_proc_address(cpu_reg, "ggml_backend_dev_get_extra_bufts");
  6801. if (ggml_backend_dev_get_extra_bufts_fn) {
  6802. ggml_backend_buffer_type_t * extra_bufts = ggml_backend_dev_get_extra_bufts_fn(cpu_dev);
  6803. while (extra_bufts && *extra_bufts) {
  6804. buft_list.emplace_back(cpu_dev, *extra_bufts);
  6805. ++extra_bufts;
  6806. }
  6807. }
  6808. // add a host buffer type
  6809. // storing the tensors in a host buffer is useful when the processing of large batches
  6810. // is offloaded to a GPU device, since it reduces the time spent on data transfers
  6811. // generally, this will be done using the first device in the list
  6812. // a better approach would be to handle this on a weight-by-weight basis using the offload_op
  6813. // function of the device to determine if it would benefit from being stored in a host buffer
  6814. for (auto * dev : model.devices) {
  6815. ggml_backend_buffer_type_t buft = ggml_backend_dev_host_buffer_type(dev);
  6816. if (buft) {
  6817. buft_list.emplace_back(dev, buft);
  6818. break;
  6819. }
  6820. }
  6821. // add the CPU buffer type
  6822. for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
  6823. ggml_backend_dev_t dev = ggml_backend_dev_get(i);
  6824. if (ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_CPU) {
  6825. buft_list.emplace_back(dev, ggml_backend_dev_buffer_type(dev));
  6826. }
  6827. }
  6828. return buft_list;
  6829. }
  6830. // GPU: split if LLAMA_SPLIT_MODE_ROW -> GPU
  6831. 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) {
  6832. llama_model::buft_list_t buft_list;
  6833. // add the device split buffer type if requested and available
  6834. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  6835. ggml_backend_reg_t reg = ggml_backend_dev_backend_reg(dev);
  6836. auto ggml_backend_split_buffer_type_fn = (ggml_backend_split_buffer_type_t)
  6837. ggml_backend_reg_get_proc_address(reg, "ggml_backend_split_buffer_type");
  6838. if (ggml_backend_split_buffer_type_fn) {
  6839. size_t dev_index = [&]() {
  6840. auto * reg = ggml_backend_dev_backend_reg(dev);
  6841. for (size_t i = 0; i < ggml_backend_reg_dev_count(reg); ++i) {
  6842. if (ggml_backend_reg_dev_get(reg, i) == dev) {
  6843. return i;
  6844. }
  6845. }
  6846. throw std::runtime_error(format("device %s not found in its backend reg", ggml_backend_dev_name(dev)));
  6847. }();
  6848. auto * buft = ggml_backend_split_buffer_type_fn(dev_index, tensor_split);
  6849. if (buft != nullptr) {
  6850. buft_list.emplace_back(dev, buft);
  6851. }
  6852. }
  6853. }
  6854. // add the device default buffer type
  6855. buft_list.emplace_back(dev, ggml_backend_dev_buffer_type(dev));
  6856. return buft_list;
  6857. }
  6858. // Returns false if cancelled by progress_callback
  6859. static bool llm_load_tensors(
  6860. llama_model_loader & ml,
  6861. llama_model & model,
  6862. int n_gpu_layers,
  6863. enum llama_split_mode split_mode,
  6864. int main_gpu,
  6865. const float * tensor_split,
  6866. bool use_mlock,
  6867. llama_progress_callback progress_callback,
  6868. void * progress_callback_user_data) {
  6869. auto & hparams = model.hparams;
  6870. model.split_mode = split_mode;
  6871. model.main_gpu = main_gpu;
  6872. model.n_gpu_layers = n_gpu_layers;
  6873. const int n_layer = hparams.n_layer;
  6874. bool use_mmap_buffer = true;
  6875. // build a list of buffer types for the CPU and GPU devices
  6876. model.cpu_buft_list = make_cpu_buft_list(model);
  6877. for (auto * dev : model.devices) {
  6878. llama_model::buft_list_t buft_list = make_gpu_buft_list(dev, split_mode, tensor_split);
  6879. // add CPU buffer types as a fallback
  6880. buft_list.insert(buft_list.end(), model.cpu_buft_list.begin(), model.cpu_buft_list.end());
  6881. model.gpu_buft_list.emplace(dev, std::move(buft_list));
  6882. }
  6883. // calculate the split points
  6884. int device_count = llama_get_device_count(model);
  6885. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  6886. std::vector<float> splits(device_count);
  6887. if (all_zero) {
  6888. // default split, by free memory
  6889. for (int i = 0; i < device_count; ++i) {
  6890. ggml_backend_dev_t dev = model.devices[i];
  6891. size_t total;
  6892. size_t free;
  6893. ggml_backend_dev_memory(dev, &free, &total);
  6894. splits[i] = free;
  6895. }
  6896. } else {
  6897. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  6898. }
  6899. // sum and normalize the splits to get the split points
  6900. float split_sum = 0.0f;
  6901. for (int i = 0; i < device_count; ++i) {
  6902. split_sum += splits[i];
  6903. splits[i] = split_sum;
  6904. }
  6905. for (int i = 0; i < device_count; ++i) {
  6906. splits[i] /= split_sum;
  6907. }
  6908. ggml_backend_dev_t cpu_dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
  6909. const int i_gpu_start = std::max((int) hparams.n_layer - n_gpu_layers, (int) 0);
  6910. const int act_gpu_layers = model.devices.empty() ? 0 : std::min(n_gpu_layers, (int)n_layer + 1);
  6911. auto get_layer_buft_list = [&](int il) -> llama_model::layer_dev {
  6912. if (il < i_gpu_start || (il - i_gpu_start) >= act_gpu_layers) {
  6913. return {cpu_dev, &model.cpu_buft_list};
  6914. }
  6915. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(il - i_gpu_start)/act_gpu_layers) - splits.begin();
  6916. auto * dev = model.devices.at(layer_gpu);
  6917. return {dev, &model.gpu_buft_list.at(dev)};
  6918. };
  6919. // assign the input layer
  6920. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  6921. model.dev_input = { cpu_dev, &model.cpu_buft_list };
  6922. // assign the repeating layers to the devices according to the splits
  6923. model.dev_layer.resize(n_layer);
  6924. for (int il = 0; il < n_layer; ++il) {
  6925. model.dev_layer[il] = get_layer_buft_list(il);
  6926. }
  6927. // assign the output layer
  6928. model.dev_output = get_layer_buft_list(n_layer);
  6929. // one ggml context per buffer type
  6930. int max_n_tensors = ml.n_tensors;
  6931. max_n_tensors += 1; // duplicated output tensor
  6932. max_n_tensors += n_layer*2; // duplicated rope freq tensors
  6933. const size_t ctx_size = ggml_tensor_overhead()*max_n_tensors;
  6934. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  6935. auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
  6936. auto it = ctx_map.find(buft);
  6937. if (it == ctx_map.end()) {
  6938. ggml_init_params params = {
  6939. /*.mem_size =*/ ctx_size,
  6940. /*.mem_buffer =*/ NULL,
  6941. /*.no_alloc =*/ true,
  6942. };
  6943. ggml_context * ctx = ggml_init(params);
  6944. if (!ctx) {
  6945. throw std::runtime_error(format("failed to create ggml context"));
  6946. }
  6947. ctx_map[buft] = ctx;
  6948. model.ctxs.emplace_back(ctx);
  6949. return ctx;
  6950. }
  6951. return it->second;
  6952. };
  6953. // create tensors for the weights
  6954. {
  6955. // note: cast to int64_t since we will use these for the tensor dimensions
  6956. const int64_t n_head = hparams.n_head();
  6957. const int64_t n_head_kv = hparams.n_head_kv();
  6958. const int64_t n_embd = hparams.n_embd;
  6959. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  6960. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  6961. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  6962. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  6963. const int64_t n_ff = hparams.n_ff();
  6964. const int64_t n_embd_gqa = n_embd_v_gqa;
  6965. const int64_t n_vocab = hparams.n_vocab;
  6966. const int64_t n_vocab_type = hparams.n_vocab_type;
  6967. const int64_t n_rot = hparams.n_rot;
  6968. const int64_t n_expert = hparams.n_expert;
  6969. const int64_t n_expert_used = hparams.n_expert_used;
  6970. const int64_t n_ctx_train = hparams.n_ctx_train;
  6971. if (n_expert > 0 && hparams.n_expert_used == 0) {
  6972. throw std::runtime_error("model has expert layers but no expert layers are used");
  6973. }
  6974. int n_moved_tensors = 0;
  6975. ggml_tensor * first_moved_tensor = nullptr;
  6976. ggml_backend_buffer_type_t first_moved_from_buft = nullptr;
  6977. ggml_backend_buffer_type_t first_moved_to_buft = nullptr;
  6978. auto create_tensor = [&](const LLM_TN_IMPL & tn, const std::initializer_list<int64_t> & ne, int flags) -> ggml_tensor * {
  6979. ggml_tensor * t_meta = ml.get_tensor_meta(tn.str().c_str());
  6980. if (!t_meta) {
  6981. if (flags & llama_model_loader::TENSOR_NOT_REQUIRED) {
  6982. return nullptr;
  6983. }
  6984. throw std::runtime_error(format("missing tensor '%s'", tn.str().c_str()));
  6985. }
  6986. // some models use the token embedding tensor as the output, but since these are used in different layers and with different ops
  6987. // the tensor is duplicated
  6988. // to handle this, we check if the tensor is duplicated, and if so, we assume that it is being loaded as the output tensor
  6989. llm_tensor tn_tensor = tn.tensor;
  6990. if (tn.tensor == LLM_TENSOR_TOKEN_EMBD && flags & llama_model_loader::TENSOR_DUPLICATED) {
  6991. tn_tensor = LLM_TENSOR_OUTPUT;
  6992. }
  6993. auto it = llm_tensor_info_mapping.find(tn_tensor);
  6994. if (it == llm_tensor_info_mapping.end()) {
  6995. throw std::runtime_error(format("missing tensor info mapping for %s", tn.str().c_str()));
  6996. }
  6997. const auto & info = it->second;
  6998. // tensors with "bias" suffix are always used with GGML_OP_ADD
  6999. ggml_op op;
  7000. bool bias = tn.suffix != nullptr && strcmp(tn.suffix, "bias") == 0;
  7001. if (bias) {
  7002. op = GGML_OP_ADD;
  7003. } else {
  7004. op = info.op;
  7005. }
  7006. // sanity checks
  7007. if (info.layer == LLM_TENSOR_LAYER_INPUT || info.layer == LLM_TENSOR_LAYER_OUTPUT) {
  7008. if (tn.bid != -1) {
  7009. GGML_ABORT("input/output layer tensor %s used with a layer number", tn.str().c_str());
  7010. }
  7011. } else {
  7012. if (tn.bid == -1) {
  7013. GGML_ABORT("repeating layer tensor %s used without a layer number", tn.str().c_str());
  7014. }
  7015. }
  7016. // select the buffer type for this tensor
  7017. llama_model::buft_list_t * buft_list;
  7018. switch (info.layer) {
  7019. case LLM_TENSOR_LAYER_INPUT:
  7020. buft_list = model.dev_input.buft_list;
  7021. break;
  7022. case LLM_TENSOR_LAYER_OUTPUT:
  7023. buft_list = model.dev_output.buft_list;
  7024. break;
  7025. case LLM_TENSOR_LAYER_REPEATING:
  7026. buft_list = model.dev_layer.at(tn.bid).buft_list;
  7027. break;
  7028. default:
  7029. GGML_ABORT("invalid layer %d for tensor %s", info.layer, tn.str().c_str());
  7030. }
  7031. ggml_backend_buffer_type_t buft = select_weight_buft(model, t_meta, op, *buft_list);
  7032. if (!buft) {
  7033. throw std::runtime_error(format("failed to find a compatible buffer type for tensor %s", tn.str().c_str()));
  7034. }
  7035. // avoid using a host buffer when using mmap
  7036. auto * buft_dev = ggml_backend_buft_get_device(buft);
  7037. if (ml.use_mmap && buft_dev && buft == ggml_backend_dev_host_buffer_type(buft_dev)) {
  7038. auto * cpu_dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
  7039. buft = ggml_backend_dev_buffer_type(cpu_dev);
  7040. }
  7041. if (buft != buft_list->front().second) {
  7042. n_moved_tensors++;
  7043. if (!first_moved_tensor) {
  7044. first_moved_tensor = t_meta;
  7045. first_moved_from_buft = buft_list->front().second;
  7046. first_moved_to_buft = buft;
  7047. }
  7048. }
  7049. ggml_context * ctx = ctx_for_buft(buft);
  7050. // if duplicated, check if the original tensor was allocated in the same buffer type context and avoid creating a new one
  7051. if (flags & llama_model_loader::TENSOR_DUPLICATED) {
  7052. ggml_tensor * t = ggml_get_tensor(ctx, tn.str().c_str());
  7053. if (t) {
  7054. return t;
  7055. }
  7056. }
  7057. return ml.create_tensor(ctx, tn, ne, flags);
  7058. };
  7059. model.layers.resize(n_layer);
  7060. // TODO: move to a separate function
  7061. const auto tn = LLM_TN(model.arch);
  7062. switch (model.arch) {
  7063. case LLM_ARCH_LLAMA:
  7064. case LLM_ARCH_REFACT:
  7065. case LLM_ARCH_MINICPM:
  7066. case LLM_ARCH_GRANITE:
  7067. case LLM_ARCH_GRANITE_MOE:
  7068. {
  7069. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7070. // output
  7071. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7072. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7073. // if output is NULL, init from the input tok embed
  7074. if (model.output == NULL) {
  7075. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7076. }
  7077. for (int i = 0; i < n_layer; ++i) {
  7078. auto & layer = model.layers[i];
  7079. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7080. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head}, 0);
  7081. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  7082. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  7083. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd}, 0);
  7084. // optional bias tensors
  7085. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7086. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7087. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7088. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7089. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7090. if (hparams.rope_scaling_type_train == LLAMA_ROPE_SCALING_TYPE_LONGROPE) {
  7091. 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));
  7092. 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));
  7093. }
  7094. else {
  7095. 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));
  7096. }
  7097. if (n_expert == 0) {
  7098. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7099. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7100. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7101. // optional MLP bias
  7102. layer.ffn_gate_b = create_tensor(tn(LLM_TENSOR_FFN_GATE, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7103. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7104. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7105. } else {
  7106. layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0);
  7107. 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);
  7108. layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert}, 0);
  7109. layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert}, 0);
  7110. }
  7111. }
  7112. } break;
  7113. case LLM_ARCH_MLLAMA:
  7114. {
  7115. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab+8}, 0);
  7116. // output
  7117. {
  7118. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7119. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7120. // if output is NULL, init from the input tok embed
  7121. if (model.output == NULL) {
  7122. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7123. }
  7124. }
  7125. for (int i = 0; i < n_layer; ++i) {
  7126. auto & layer = model.layers[i];
  7127. if (hparams.cross_attention_layers(i)) {
  7128. layer.cross_attn_k_norm = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_K_NORM, "weight", i), {128}, 0);
  7129. layer.cross_attn_k_proj = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_K_PROJ, "weight", i), {n_embd, 1024}, 0);
  7130. layer.cross_attn_o_proj = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_O_PROJ, "weight", i), {n_embd, n_embd}, 0);
  7131. layer.cross_attn_q_norm = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_Q_NORM, "weight", i), {128}, 0);
  7132. layer.cross_attn_q_proj = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_Q_PROJ, "weight", i), {n_embd, n_embd}, 0);
  7133. layer.cross_attn_v_proj = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_V_PROJ, "weight", i), {n_embd, 1024}, 0);
  7134. layer.cross_attn_attn_gate = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_ATTN_GATE, i), {1}, 0);
  7135. layer.cross_attn_mlp_gate = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_MLP_GATE, i), {1}, 0);
  7136. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7137. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7138. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7139. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7140. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7141. } else {
  7142. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7143. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head}, 0);
  7144. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  7145. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  7146. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd}, 0);
  7147. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7148. 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));
  7149. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7150. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7151. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7152. }
  7153. }
  7154. } break;
  7155. case LLM_ARCH_MINICPM3:
  7156. {
  7157. const int64_t n_embd_head_qk_rope = hparams.n_rot;
  7158. const int64_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  7159. const int64_t q_lora_rank = hparams.n_lora_q;
  7160. const int64_t kv_lora_rank = hparams.n_lora_kv;
  7161. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7162. // output
  7163. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7164. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7165. // if output is NULL, init from the input tok embed
  7166. if (model.output == NULL) {
  7167. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7168. }
  7169. for (int i = 0; i < n_layer; ++i) {
  7170. auto & layer = model.layers[i];
  7171. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7172. layer.attn_q_a_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_A_NORM, "weight", i), {q_lora_rank}, 0);
  7173. layer.attn_kv_a_norm = create_tensor(tn(LLM_TENSOR_ATTN_KV_A_NORM, "weight", i), {kv_lora_rank}, 0);
  7174. layer.wq_a = create_tensor(tn(LLM_TENSOR_ATTN_Q_A, "weight", i), {n_embd, q_lora_rank}, 0);
  7175. layer.wq_b = create_tensor(tn(LLM_TENSOR_ATTN_Q_B, "weight", i), {q_lora_rank, n_head * n_embd_head_k}, 0);
  7176. 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);
  7177. 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);
  7178. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_head * ( n_embd_head_v), n_embd}, 0);
  7179. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7180. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7181. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7182. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7183. 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));
  7184. 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));
  7185. }
  7186. } break;
  7187. case LLM_ARCH_GROK:
  7188. {
  7189. if (n_expert == 0) {
  7190. throw std::runtime_error("Grok model cannot have zero experts");
  7191. }
  7192. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7193. // output
  7194. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7195. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7196. // if output is NULL, init from the input tok embed
  7197. if (model.output == NULL) {
  7198. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7199. }
  7200. for (int i = 0; i < n_layer; ++i) {
  7201. auto & layer = model.layers[i];
  7202. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7203. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7204. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7205. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7206. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7207. layer.attn_out_norm = create_tensor(tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd}, 0);
  7208. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7209. layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0);
  7210. 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);
  7211. layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert}, 0);
  7212. layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert}, 0);
  7213. layer.layer_out_norm = create_tensor(tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd}, 0);
  7214. }
  7215. } break;
  7216. case LLM_ARCH_DBRX:
  7217. {
  7218. if (n_expert == 0) {
  7219. throw std::runtime_error("DBRX model cannot have zero experts");
  7220. }
  7221. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7222. // output
  7223. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7224. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7225. for (int i = 0; i < n_layer; ++i) {
  7226. auto & layer = model.layers[i];
  7227. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7228. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7229. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7230. layer.attn_out_norm = create_tensor(tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd}, 0);
  7231. layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0);
  7232. layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, 0);
  7233. layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff, n_embd, n_expert}, 0);
  7234. layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert}, 0);
  7235. }
  7236. } break;
  7237. case LLM_ARCH_BAICHUAN:
  7238. {
  7239. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7240. {
  7241. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7242. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7243. }
  7244. for (int i = 0; i < n_layer; ++i) {
  7245. auto & layer = model.layers[i];
  7246. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7247. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7248. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7249. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7250. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7251. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7252. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7253. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7254. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7255. }
  7256. } break;
  7257. case LLM_ARCH_FALCON:
  7258. {
  7259. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7260. // output
  7261. {
  7262. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7263. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7264. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7265. if (!model.output) {
  7266. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED); // needs to be on GPU
  7267. }
  7268. }
  7269. for (int i = 0; i < n_layer; ++i) {
  7270. auto & layer = model.layers[i];
  7271. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7272. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7273. layer.attn_norm_2 = create_tensor(tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7274. layer.attn_norm_2_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7275. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7276. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7277. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7278. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7279. }
  7280. } break;
  7281. case LLM_ARCH_STARCODER:
  7282. {
  7283. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7284. model.pos_embd = create_tensor(tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train}, 0);
  7285. // output
  7286. {
  7287. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7288. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7289. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7290. if (!model.output) {
  7291. // needs to be on GPU
  7292. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7293. }
  7294. }
  7295. for (int i = 0; i < n_layer; ++i) {
  7296. auto & layer = model.layers[i];
  7297. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7298. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7299. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7300. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, 0);
  7301. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7302. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  7303. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7304. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  7305. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7306. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  7307. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7308. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0);
  7309. }
  7310. } break;
  7311. case LLM_ARCH_BERT:
  7312. case LLM_ARCH_NOMIC_BERT:
  7313. {
  7314. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7315. model.type_embd = create_tensor(tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type}, 0);
  7316. if (model.arch == LLM_ARCH_BERT) {
  7317. model.pos_embd = create_tensor(tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train}, 0);
  7318. model.cls = create_tensor(tn(LLM_TENSOR_CLS, "weight"), {n_embd, n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7319. model.cls_b = create_tensor(tn(LLM_TENSOR_CLS, "bias"), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7320. model.cls_out = create_tensor(tn(LLM_TENSOR_CLS_OUT, "weight"), {n_embd, 1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7321. model.cls_out_b = create_tensor(tn(LLM_TENSOR_CLS_OUT, "bias"), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7322. }
  7323. model.tok_norm = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd}, 0);
  7324. model.tok_norm_b = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd}, 0);
  7325. for (int i = 0; i < n_layer; ++i) {
  7326. auto & layer = model.layers[i];
  7327. if (model.arch == LLM_ARCH_BERT) {
  7328. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7329. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, 0);
  7330. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7331. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, 0);
  7332. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7333. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, 0);
  7334. } else {
  7335. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7336. }
  7337. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7338. layer.attn_out_norm = create_tensor(tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd}, 0);
  7339. layer.attn_out_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd}, 0);
  7340. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7341. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7342. if (model.arch == LLM_ARCH_BERT) {
  7343. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  7344. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0);
  7345. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  7346. } else {
  7347. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7348. }
  7349. layer.layer_out_norm = create_tensor(tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd}, 0);
  7350. layer.layer_out_norm_b = create_tensor(tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd}, 0);
  7351. }
  7352. } break;
  7353. case LLM_ARCH_JINA_BERT_V2:
  7354. {
  7355. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0); // word_embeddings
  7356. model.type_embd = create_tensor(tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type}, 0); // token_type_embeddings
  7357. model.tok_norm = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd}, 0); // LayerNorm
  7358. model.tok_norm_b = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd}, 0); //LayerNorm bias
  7359. model.cls = create_tensor(tn(LLM_TENSOR_CLS, "weight"), {n_embd, 1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7360. model.cls_b = create_tensor(tn(LLM_TENSOR_CLS, "bias"), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7361. for (int i = 0; i < n_layer; ++i) {
  7362. auto & layer = model.layers[i]; // JinaBertLayer
  7363. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7364. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, 0);
  7365. layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7366. layer.attn_q_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7367. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7368. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, 0);
  7369. layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7370. layer.attn_k_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7371. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7372. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, 0);
  7373. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0); //output_dens
  7374. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0); //output_dens
  7375. layer.attn_out_norm = create_tensor(tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd}, 0); //output_norm
  7376. layer.attn_out_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd}, 0);
  7377. layer.attn_norm_2 = create_tensor(tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7378. layer.attn_norm_2_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7379. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7380. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7381. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7382. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  7383. layer.layer_out_norm = create_tensor(tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd}, 0);
  7384. layer.layer_out_norm_b = create_tensor(tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd}, 0);
  7385. }
  7386. } break;
  7387. case LLM_ARCH_BLOOM:
  7388. {
  7389. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7390. model.tok_norm = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd}, 0);
  7391. model.tok_norm_b = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd}, 0);
  7392. // output
  7393. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7394. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7395. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7396. for (int i = 0; i < n_layer; ++i) {
  7397. auto & layer = model.layers[i];
  7398. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7399. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7400. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7401. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, 0);
  7402. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7403. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  7404. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7405. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  7406. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7407. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  7408. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7409. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0);
  7410. }
  7411. } break;
  7412. case LLM_ARCH_MPT:
  7413. {
  7414. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7415. model.pos_embd = create_tensor(tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7416. // output
  7417. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7418. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7419. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7420. if (!model.output) {
  7421. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED); // needs to be on GPU
  7422. }
  7423. for (int i = 0; i < n_layer; ++i) {
  7424. auto & layer = model.layers[i];
  7425. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7426. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7427. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7428. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7429. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7430. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7431. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7432. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7433. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7434. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7435. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7436. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7437. layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7438. layer.attn_q_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7439. layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7440. layer.attn_k_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7441. // AWQ ScaleActivation layer
  7442. layer.ffn_act = create_tensor(tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7443. }
  7444. } break;
  7445. case LLM_ARCH_STABLELM:
  7446. {
  7447. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7448. // output
  7449. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7450. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7451. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7452. for (int i = 0; i < n_layer; ++i) {
  7453. auto & layer = model.layers[i];
  7454. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7455. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7456. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7457. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7458. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7459. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7460. // optional bias tensors, present in Stable LM 2 1.6B
  7461. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7462. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7463. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7464. // optional q and k layernorms, present in StableLM 2 12B
  7465. 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);
  7466. 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);
  7467. // optional FFN norm, not present in StableLM 2 12B which uses parallel residual
  7468. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7469. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7470. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7471. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7472. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7473. }
  7474. } break;
  7475. case LLM_ARCH_QWEN:
  7476. {
  7477. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7478. // output
  7479. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7480. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7481. for (int i = 0; i < n_layer; ++i) {
  7482. auto & layer = model.layers[i];
  7483. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7484. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3}, 0);
  7485. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3}, 0);
  7486. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7487. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7488. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2}, 0);
  7489. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd}, 0);
  7490. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2}, 0);
  7491. }
  7492. } break;
  7493. case LLM_ARCH_QWEN2:
  7494. case LLM_ARCH_QWEN2VL:
  7495. {
  7496. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7497. // output
  7498. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7499. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7500. // if output is NULL, init from the input tok embed
  7501. if (model.output == NULL) {
  7502. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7503. }
  7504. for (int i = 0; i < n_layer; ++i) {
  7505. auto & layer = model.layers[i];
  7506. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7507. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7508. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7509. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7510. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7511. // optional bias tensors
  7512. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, 0);
  7513. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, 0);
  7514. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, 0);
  7515. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7516. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7517. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7518. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7519. }
  7520. } break;
  7521. case LLM_ARCH_QWEN2MOE:
  7522. {
  7523. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7524. // output
  7525. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7526. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7527. for (int i = 0; i < n_layer; ++i) {
  7528. auto & layer = model.layers[i];
  7529. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7530. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7531. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7532. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7533. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7534. // optional bias tensors
  7535. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, 0);
  7536. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, 0);
  7537. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, 0);
  7538. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7539. layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0);
  7540. if (n_expert == 0) {
  7541. throw std::runtime_error("n_expert must be > 0 for QWEN2MOE");
  7542. }
  7543. if (n_expert_used == 0) {
  7544. throw std::runtime_error("n_expert_used must be > 0 for QWEN2MOE");
  7545. }
  7546. // MoE branch
  7547. const int64_t n_ff_exp = hparams.n_ff_exp ? hparams.n_ff_exp : n_ff / n_expert_used;
  7548. layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert}, 0);
  7549. layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert}, 0);
  7550. layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert}, 0);
  7551. // Shared expert branch
  7552. const int64_t n_ff_shexp = hparams.n_ff_shexp ? hparams.n_ff_shexp : n_ff;
  7553. layer.ffn_gate_inp_shexp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP_SHEXP, "weight", i), {n_embd}, 0);
  7554. layer.ffn_gate_shexp = create_tensor(tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), { n_embd, n_ff_shexp}, 0);
  7555. layer.ffn_down_shexp = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), {n_ff_shexp, n_embd}, 0);
  7556. layer.ffn_up_shexp = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), { n_embd, n_ff_shexp}, 0);
  7557. }
  7558. } break;
  7559. case LLM_ARCH_PHI2:
  7560. {
  7561. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7562. // output
  7563. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7564. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7565. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7566. model.output_b = create_tensor(tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab}, 0);
  7567. for (int i = 0; i < n_layer; ++i) {
  7568. auto & layer = model.layers[i];
  7569. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7570. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7571. 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);
  7572. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7573. if (layer.wqkv == nullptr) {
  7574. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7575. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, 0);
  7576. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7577. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, 0);
  7578. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7579. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, 0);
  7580. }
  7581. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7582. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  7583. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7584. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  7585. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7586. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0);
  7587. }
  7588. } break;
  7589. case LLM_ARCH_PHI3:
  7590. {
  7591. const int64_t n_embd_head = n_embd / n_head;
  7592. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), { n_embd, n_vocab }, 0);
  7593. // output
  7594. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), { n_embd }, 0);
  7595. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), { n_embd, n_vocab }, 0);
  7596. for (int i = 0; i < n_layer; ++i) {
  7597. auto & layer = model.layers[i];
  7598. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), { n_embd }, 0);
  7599. 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);
  7600. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_embd, n_embd }, 0);
  7601. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), { n_embd }, 0);
  7602. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd }, 0);
  7603. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), { n_embd, 2 * n_ff }, 0);
  7604. 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));
  7605. 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));
  7606. }
  7607. } break;
  7608. case LLM_ARCH_PLAMO:
  7609. {
  7610. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7611. // output
  7612. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7613. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7614. for (int i = 0; i < n_layer; ++i) {
  7615. auto & layer = model.layers[i];
  7616. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7617. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7618. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7619. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7620. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7621. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7622. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7623. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7624. }
  7625. } break;
  7626. case LLM_ARCH_GPT2:
  7627. {
  7628. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7629. model.pos_embd = create_tensor(tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train}, 0);
  7630. // output
  7631. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7632. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7633. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7634. for (int i = 0; i < n_layer; ++i) {
  7635. auto & layer = model.layers[i];
  7636. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7637. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7638. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7639. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, 0);
  7640. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7641. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  7642. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7643. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  7644. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7645. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  7646. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7647. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0);
  7648. }
  7649. } break;
  7650. case LLM_ARCH_CODESHELL:
  7651. {
  7652. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7653. // output
  7654. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7655. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7656. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7657. for (int i = 0; i < n_layer; ++i) {
  7658. auto & layer = model.layers[i];
  7659. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7660. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7661. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7662. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, 0);
  7663. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7664. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  7665. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7666. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  7667. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7668. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  7669. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7670. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0);
  7671. }
  7672. } break;
  7673. case LLM_ARCH_ORION:
  7674. {
  7675. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7676. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7677. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7678. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7679. for (int i = 0; i < n_layer; ++i) {
  7680. auto & layer = model.layers[i];
  7681. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7682. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7683. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7684. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7685. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7686. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7687. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7688. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  7689. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7690. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7691. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7692. }
  7693. } break;
  7694. case LLM_ARCH_INTERNLM2:
  7695. {
  7696. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7697. // output
  7698. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7699. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7700. for (int i = 0; i < n_layer; ++i) {
  7701. auto & layer = model.layers[i];
  7702. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7703. // layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7704. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7705. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7706. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7707. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7708. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7709. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7710. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7711. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7712. }
  7713. } break;
  7714. case LLM_ARCH_GEMMA:
  7715. {
  7716. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7717. // output
  7718. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7719. 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
  7720. for (int i = 0; i < n_layer; ++i) {
  7721. auto & layer = model.layers[i];
  7722. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7723. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head}, 0);
  7724. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  7725. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  7726. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd}, 0);
  7727. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7728. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7729. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7730. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7731. }
  7732. } break;
  7733. case LLM_ARCH_GEMMA2:
  7734. {
  7735. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7736. // output
  7737. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7738. 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
  7739. for (int i = 0; i < n_layer; ++i) {
  7740. auto & layer = model.layers[i];
  7741. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7742. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head}, 0);
  7743. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  7744. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  7745. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd}, 0);
  7746. layer.attn_post_norm = create_tensor(tn(LLM_TENSOR_ATTN_POST_NORM, "weight", i), {n_embd}, 0);
  7747. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7748. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7749. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7750. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7751. layer.ffn_post_norm = create_tensor(tn(LLM_TENSOR_FFN_POST_NORM, "weight", i), {n_embd}, 0);
  7752. }
  7753. } break;
  7754. case LLM_ARCH_STARCODER2:
  7755. {
  7756. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7757. // output
  7758. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7759. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7760. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7761. // if output is NULL, init from the input tok embed
  7762. if (model.output == NULL) {
  7763. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7764. }
  7765. for (int i = 0; i < n_layer; ++i) {
  7766. auto & layer = model.layers[i];
  7767. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7768. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7769. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7770. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7771. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7772. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7773. // optional bias tensors
  7774. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, 0);
  7775. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, 0);
  7776. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, 0);
  7777. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  7778. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7779. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  7780. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7781. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7782. // optional bias tensors
  7783. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  7784. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP , "bias", i), { n_ff}, 0);
  7785. }
  7786. } break;
  7787. case LLM_ARCH_MAMBA:
  7788. {
  7789. const int64_t d_conv = hparams.ssm_d_conv;
  7790. const int64_t d_inner = hparams.ssm_d_inner;
  7791. const int64_t d_state = hparams.ssm_d_state;
  7792. const int64_t dt_rank = hparams.ssm_dt_rank;
  7793. // only an expansion factor of 2 is supported for now
  7794. if (2 * n_embd != d_inner) {
  7795. throw std::runtime_error("only an expansion factor of 2 is supported for now");
  7796. }
  7797. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7798. // output
  7799. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7800. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7801. // if output is NULL, init from the input tok embed, duplicated to allow offloading
  7802. if (model.output == NULL) {
  7803. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7804. }
  7805. for (int i = 0; i < n_layer; ++i) {
  7806. auto & layer = model.layers[i];
  7807. // norm
  7808. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7809. layer.ssm_in = create_tensor(tn(LLM_TENSOR_SSM_IN, "weight", i), {n_embd, 2*d_inner}, 0);
  7810. layer.ssm_conv1d = create_tensor(tn(LLM_TENSOR_SSM_CONV1D, "weight", i), {d_conv, d_inner}, 0);
  7811. layer.ssm_conv1d_b = create_tensor(tn(LLM_TENSOR_SSM_CONV1D, "bias", i), {d_inner}, 0);
  7812. layer.ssm_x = create_tensor(tn(LLM_TENSOR_SSM_X, "weight", i), {d_inner, dt_rank + 2*d_state}, 0);
  7813. layer.ssm_dt = create_tensor(tn(LLM_TENSOR_SSM_DT, "weight", i), {dt_rank, d_inner}, 0);
  7814. layer.ssm_dt_b = create_tensor(tn(LLM_TENSOR_SSM_DT, "bias", i), {d_inner}, 0);
  7815. // no "weight" suffix for these
  7816. layer.ssm_a = create_tensor(tn(LLM_TENSOR_SSM_A, i), {d_state, d_inner}, 0);
  7817. layer.ssm_d = create_tensor(tn(LLM_TENSOR_SSM_D, i), {d_inner}, 0);
  7818. // out_proj
  7819. layer.ssm_out = create_tensor(tn(LLM_TENSOR_SSM_OUT, "weight", i), {d_inner, n_embd}, 0);
  7820. }
  7821. } break;
  7822. case LLM_ARCH_XVERSE:
  7823. {
  7824. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7825. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7826. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7827. for (int i = 0; i < n_layer; ++i) {
  7828. auto & layer = model.layers[i];
  7829. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7830. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7831. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7832. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7833. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7834. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7835. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7836. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7837. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7838. }
  7839. } break;
  7840. case LLM_ARCH_COMMAND_R:
  7841. {
  7842. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7843. // output
  7844. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7845. // init output from the input tok embed
  7846. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7847. for (int i = 0; i < n_layer; ++i) {
  7848. auto & layer = model.layers[i];
  7849. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7850. if (n_layer >= 64){
  7851. layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k, n_head}, 0);
  7852. layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k, n_head_kv}, 0);
  7853. }
  7854. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7855. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7856. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7857. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7858. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7859. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7860. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7861. }
  7862. } break;
  7863. case LLM_ARCH_OLMO: // adapted from LLM_ARCH_LLAMA with norm params removed
  7864. {
  7865. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7866. // output
  7867. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7868. // if output is NULL, init from the input tok embed
  7869. if (model.output == NULL) {
  7870. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7871. }
  7872. for (int i = 0; i < n_layer; ++i) {
  7873. auto & layer = model.layers[i];
  7874. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7875. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7876. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7877. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7878. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7879. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7880. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7881. }
  7882. } break;
  7883. case LLM_ARCH_OLMO2:
  7884. {
  7885. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7886. // output
  7887. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7888. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7889. for (int i = 0; i < n_layer; ++i) {
  7890. auto & layer = model.layers[i];
  7891. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7892. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7893. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7894. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7895. layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd}, 0);
  7896. layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd}, 0);
  7897. layer.attn_post_norm = create_tensor(tn(LLM_TENSOR_ATTN_POST_NORM, "weight", i), {n_embd}, 0);
  7898. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7899. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7900. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  7901. layer.ffn_post_norm = create_tensor(tn(LLM_TENSOR_FFN_POST_NORM, "weight", i), {n_embd}, 0);
  7902. }
  7903. } break;
  7904. case LLM_ARCH_OLMOE:
  7905. {
  7906. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7907. // output
  7908. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7909. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7910. for (int i = 0; i < n_layer; ++i) {
  7911. auto & layer = model.layers[i];
  7912. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7913. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7914. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7915. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7916. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7917. layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd}, 0);
  7918. layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd}, 0);
  7919. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7920. layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0);
  7921. if (n_expert == 0) {
  7922. throw std::runtime_error("n_expert must be > 0");
  7923. }
  7924. if (n_expert_used == 0) {
  7925. throw std::runtime_error("n_expert_used must be > 0");
  7926. }
  7927. // MoE branch
  7928. layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, 0);
  7929. layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff, n_embd, n_expert}, 0);
  7930. layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert}, 0);
  7931. }
  7932. } break;
  7933. case LLM_ARCH_OPENELM:
  7934. {
  7935. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7936. // output
  7937. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7938. // init output from the input tok embed
  7939. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7940. for (int i = 0; i < n_layer; ++i) {
  7941. const int64_t n_head = hparams.n_head(i);
  7942. const int64_t n_head_qkv = 2*hparams.n_head_kv(i) + n_head;
  7943. const int64_t n_ff = hparams.n_ff(i);
  7944. auto & layer = model.layers[i];
  7945. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7946. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_head_qkv*n_embd_head_k}, 0);
  7947. layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k}, 0);
  7948. layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k}, 0);
  7949. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_head*n_embd_head_k, n_embd}, 0);
  7950. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7951. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  7952. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7953. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7954. }
  7955. } break;
  7956. case LLM_ARCH_GPTNEOX:
  7957. {
  7958. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7959. // output
  7960. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7961. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  7962. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  7963. for (int i = 0; i < n_layer; ++i) {
  7964. auto & layer = model.layers[i];
  7965. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7966. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  7967. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  7968. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, 0);
  7969. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7970. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  7971. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7972. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  7973. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  7974. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  7975. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  7976. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0);
  7977. }
  7978. } break;
  7979. case LLM_ARCH_ARCTIC:
  7980. {
  7981. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  7982. // output
  7983. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  7984. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7985. // if output is NULL, init from the input tok embed
  7986. if (model.output == NULL) {
  7987. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7988. }
  7989. for (int i = 0; i < n_layer; ++i) {
  7990. auto & layer = model.layers[i];
  7991. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  7992. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  7993. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  7994. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  7995. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  7996. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  7997. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_embd}, 0);
  7998. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_embd, n_embd}, 0);
  7999. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_embd}, 0);
  8000. layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0);
  8001. layer.ffn_norm_exps = create_tensor(tn(LLM_TENSOR_FFN_NORM_EXPS, "weight", i), {n_embd}, 0);
  8002. layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, false);
  8003. layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert}, 0);
  8004. layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert}, 0);
  8005. }
  8006. } break;
  8007. case LLM_ARCH_DEEPSEEK2:
  8008. {
  8009. const bool is_lite = (hparams.n_layer == 27);
  8010. const int64_t n_embd_head_qk_rope = hparams.n_rot;
  8011. const int64_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  8012. const int64_t q_lora_rank = hparams.n_lora_q;
  8013. const int64_t kv_lora_rank = hparams.n_lora_kv;
  8014. const int64_t n_ff_exp = hparams.n_ff_exp;
  8015. const int64_t n_expert_shared = hparams.n_expert_shared;
  8016. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8017. // output
  8018. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8019. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  8020. for (int i = 0; i < n_layer; ++i) {
  8021. auto & layer = model.layers[i];
  8022. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  8023. if (!is_lite) {
  8024. layer.attn_q_a_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_A_NORM, "weight", i), {q_lora_rank}, 0);
  8025. }
  8026. layer.attn_kv_a_norm = create_tensor(tn(LLM_TENSOR_ATTN_KV_A_NORM, "weight", i), {kv_lora_rank}, 0);
  8027. if (!is_lite) {
  8028. layer.wq_a = create_tensor(tn(LLM_TENSOR_ATTN_Q_A, "weight", i), {n_embd, q_lora_rank}, 0);
  8029. layer.wq_b = create_tensor(tn(LLM_TENSOR_ATTN_Q_B, "weight", i), {q_lora_rank, n_head * n_embd_head_k}, 0);
  8030. } else {
  8031. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8032. }
  8033. 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);
  8034. 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);
  8035. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_head * ( n_embd_head_v), n_embd}, 0);
  8036. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  8037. if (i < (int) hparams.n_layer_dense_lead) {
  8038. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  8039. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  8040. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8041. } else {
  8042. layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0);
  8043. if (n_expert == 0) {
  8044. throw std::runtime_error("n_expert must be > 0");
  8045. }
  8046. if (n_expert_used == 0) {
  8047. throw std::runtime_error("n_expert_used must be > 0");
  8048. }
  8049. // MoE branch
  8050. layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert}, 0);
  8051. layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert}, 0);
  8052. layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert}, 0);
  8053. // Shared expert branch
  8054. layer.ffn_gate_shexp = create_tensor(tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), {n_embd, n_ff_exp * n_expert_shared}, 0);
  8055. layer.ffn_down_shexp = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), { n_ff_exp * n_expert_shared, n_embd}, 0);
  8056. layer.ffn_up_shexp = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), {n_embd, n_ff_exp * n_expert_shared}, 0);
  8057. }
  8058. }
  8059. } break;
  8060. case LLM_ARCH_BITNET:
  8061. {
  8062. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8063. // output
  8064. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8065. for (int i = 0; i < n_layer; ++i) {
  8066. auto & layer = model.layers[i];
  8067. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  8068. layer.attn_sub_norm = create_tensor(tn(LLM_TENSOR_ATTN_SUB_NORM, "weight", i), {n_embd}, 0);
  8069. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  8070. layer.wq_scale = create_tensor(tn(LLM_TENSOR_ATTN_Q, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8071. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  8072. layer.wk_scale = create_tensor(tn(LLM_TENSOR_ATTN_K, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8073. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  8074. layer.wv_scale = create_tensor(tn(LLM_TENSOR_ATTN_V, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8075. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  8076. layer.wo_scale = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8077. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  8078. layer.ffn_sub_norm = create_tensor(tn(LLM_TENSOR_FFN_SUB_NORM, "weight", i), {n_ff}, 0);
  8079. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  8080. layer.ffn_gate_scale = create_tensor(tn(LLM_TENSOR_FFN_GATE, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8081. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  8082. layer.ffn_down_scale = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8083. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8084. layer.ffn_up_scale = create_tensor(tn(LLM_TENSOR_FFN_UP, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8085. }
  8086. } break;
  8087. case LLM_ARCH_T5:
  8088. {
  8089. const auto n_rel_attn_bkts = hparams.n_rel_attn_bkts;
  8090. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8091. // output
  8092. model.output_norm_enc = create_tensor(tn(LLM_TENSOR_ENC_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8093. model.output_norm = create_tensor(tn(LLM_TENSOR_DEC_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8094. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8095. // if output is NULL, init from the input tok embed
  8096. if (model.output == NULL) {
  8097. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  8098. }
  8099. for (int i = 0; i < n_layer; ++i) {
  8100. auto & layer = model.layers[i];
  8101. layer.attn_norm_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_NORM, "weight", i), {n_embd}, 0);
  8102. 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);
  8103. layer.wq_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8104. layer.wk_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8105. layer.wv_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  8106. layer.wo_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd}, 0);
  8107. layer.ffn_norm_enc = create_tensor(tn(LLM_TENSOR_ENC_FFN_NORM, "weight", i), {n_embd}, 0);
  8108. layer.ffn_gate_enc = create_tensor(tn(LLM_TENSOR_ENC_FFN_GATE, "weight", i), {n_embd, n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8109. layer.ffn_down_enc = create_tensor(tn(LLM_TENSOR_ENC_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  8110. layer.ffn_up_enc = create_tensor(tn(LLM_TENSOR_ENC_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8111. layer.attn_norm = create_tensor(tn(LLM_TENSOR_DEC_ATTN_NORM, "weight", i), {n_embd}, 0);
  8112. 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);
  8113. layer.wq = create_tensor(tn(LLM_TENSOR_DEC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8114. layer.wk = create_tensor(tn(LLM_TENSOR_DEC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8115. layer.wv = create_tensor(tn(LLM_TENSOR_DEC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  8116. layer.wo = create_tensor(tn(LLM_TENSOR_DEC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd}, 0);
  8117. layer.attn_norm_cross = create_tensor(tn(LLM_TENSOR_DEC_CROSS_ATTN_NORM, "weight", i), {n_embd}, 0);
  8118. // this tensor seems to be unused in HF transformers implementation
  8119. 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);
  8120. layer.wq_cross = create_tensor(tn(LLM_TENSOR_DEC_CROSS_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8121. layer.wk_cross = create_tensor(tn(LLM_TENSOR_DEC_CROSS_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8122. layer.wv_cross = create_tensor(tn(LLM_TENSOR_DEC_CROSS_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  8123. layer.wo_cross = create_tensor(tn(LLM_TENSOR_DEC_CROSS_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd}, 0);
  8124. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_DEC_FFN_NORM, "weight", i), {n_embd}, 0);
  8125. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_DEC_FFN_GATE, "weight", i), {n_embd, n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8126. layer.ffn_down = create_tensor(tn(LLM_TENSOR_DEC_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  8127. layer.ffn_up = create_tensor(tn(LLM_TENSOR_DEC_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8128. }
  8129. } break;
  8130. case LLM_ARCH_T5ENCODER:
  8131. {
  8132. const auto n_rel_attn_bkts = hparams.n_rel_attn_bkts;
  8133. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8134. // output
  8135. model.output_norm_enc = create_tensor(tn(LLM_TENSOR_ENC_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8136. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8137. // if output is NULL, init from the input tok embed
  8138. if (model.output == NULL) {
  8139. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  8140. }
  8141. for (int i = 0; i < n_layer; ++i) {
  8142. auto & layer = model.layers[i];
  8143. layer.attn_norm_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_NORM, "weight", i), {n_embd}, 0);
  8144. 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);
  8145. layer.wq_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8146. layer.wk_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8147. layer.wv_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  8148. layer.wo_enc = create_tensor(tn(LLM_TENSOR_ENC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd}, 0);
  8149. layer.ffn_norm_enc = create_tensor(tn(LLM_TENSOR_ENC_FFN_NORM, "weight", i), {n_embd}, 0);
  8150. layer.ffn_gate_enc = create_tensor(tn(LLM_TENSOR_ENC_FFN_GATE, "weight", i), {n_embd, n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8151. layer.ffn_down_enc = create_tensor(tn(LLM_TENSOR_ENC_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  8152. layer.ffn_up_enc = create_tensor(tn(LLM_TENSOR_ENC_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8153. }
  8154. } break;
  8155. case LLM_ARCH_JAIS:
  8156. {
  8157. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8158. // output
  8159. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8160. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  8161. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  8162. for (int i = 0; i < n_layer; ++i) {
  8163. auto & layer = model.layers[i];
  8164. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  8165. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  8166. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  8167. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, 0);
  8168. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  8169. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
  8170. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  8171. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  8172. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  8173. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
  8174. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  8175. layer.ffn_gate_b = create_tensor(tn(LLM_TENSOR_FFN_GATE, "bias", i), {n_ff}, 0);
  8176. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8177. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0);
  8178. }
  8179. } break;
  8180. case LLM_ARCH_CHATGLM:
  8181. {
  8182. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8183. // output
  8184. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8185. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  8186. for (int i = 0; i < n_layer; ++i) {
  8187. auto & layer = model.layers[i];
  8188. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  8189. layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, 0);
  8190. layer.bqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, 0);
  8191. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  8192. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  8193. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff * 2}, 0);
  8194. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  8195. }
  8196. } break;
  8197. case LLM_ARCH_NEMOTRON:
  8198. {
  8199. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8200. // output
  8201. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8202. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  8203. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  8204. for (int i = 0; i < n_layer; ++i) {
  8205. auto & layer = model.layers[i];
  8206. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  8207. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  8208. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  8209. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  8210. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  8211. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  8212. // optional bias tensors
  8213. layer.bq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8214. layer.bk = create_tensor(tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8215. layer.bv = create_tensor(tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8216. layer.bo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8217. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  8218. layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
  8219. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  8220. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8221. // optional MLP bias
  8222. layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8223. layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8224. }
  8225. } break;
  8226. case LLM_ARCH_EXAONE:
  8227. {
  8228. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8229. // output
  8230. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8231. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  8232. for (int i = 0; i < n_layer; ++i) {
  8233. auto & layer = model.layers[i];
  8234. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  8235. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head}, 0);
  8236. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8237. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  8238. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd}, 0);
  8239. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  8240. 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));
  8241. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  8242. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  8243. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8244. }
  8245. } break;
  8246. case LLM_ARCH_RWKV6:
  8247. {
  8248. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8249. // Block 0, LN0
  8250. model.tok_norm = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd}, 0);
  8251. model.tok_norm_b = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd}, 0);
  8252. // output
  8253. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8254. model.output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
  8255. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
  8256. const int time_mix_extra_dim = hparams.time_mix_extra_dim;
  8257. const int time_decay_extra_dim = hparams.time_decay_extra_dim;
  8258. const int head_size = hparams.wkv_head_size;
  8259. const int attn_hidden_size = n_embd;
  8260. const int ffn_size = hparams.n_ff_arr[0];
  8261. for (int i = 0; i < n_layer; ++i) {
  8262. auto & layer = model.layers[i];
  8263. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  8264. layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
  8265. layer.attn_norm_2 = create_tensor(tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd}, 0);
  8266. layer.attn_norm_2_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd}, 0);
  8267. layer.time_mix_w1 = create_tensor(tn(LLM_TENSOR_TIME_MIX_W1, "weight", i), {n_embd, time_mix_extra_dim * 5}, 0);
  8268. layer.time_mix_w2 = create_tensor(tn(LLM_TENSOR_TIME_MIX_W2, "weight", i), {time_mix_extra_dim, n_embd, 5}, 0);
  8269. layer.time_mix_lerp_x = create_tensor(tn(LLM_TENSOR_TIME_MIX_LERP_X, "weight", i), {n_embd, 1, 1}, 0);
  8270. layer.time_mix_lerp_w = create_tensor(tn(LLM_TENSOR_TIME_MIX_LERP_W, "weight", i), {n_embd, 1, 1}, 0);
  8271. layer.time_mix_lerp_k = create_tensor(tn(LLM_TENSOR_TIME_MIX_LERP_K, "weight", i), {n_embd, 1, 1}, 0);
  8272. layer.time_mix_lerp_v = create_tensor(tn(LLM_TENSOR_TIME_MIX_LERP_V, "weight", i), {n_embd, 1, 1}, 0);
  8273. layer.time_mix_lerp_r = create_tensor(tn(LLM_TENSOR_TIME_MIX_LERP_R, "weight", i), {n_embd, 1, 1}, 0);
  8274. layer.time_mix_lerp_g = create_tensor(tn(LLM_TENSOR_TIME_MIX_LERP_G, "weight", i), {n_embd, 1, 1}, 0);
  8275. layer.time_mix_first = create_tensor(tn(LLM_TENSOR_TIME_MIX_FIRST, "weight", i), {head_size, n_embd / head_size}, 0);
  8276. layer.time_mix_decay = create_tensor(tn(LLM_TENSOR_TIME_MIX_DECAY, "weight", i), {n_embd}, 0);
  8277. layer.time_mix_decay_w1 = create_tensor(tn(LLM_TENSOR_TIME_MIX_DECAY_W1, "weight", i), {n_embd, time_decay_extra_dim}, 0);
  8278. layer.time_mix_decay_w2 = create_tensor(tn(LLM_TENSOR_TIME_MIX_DECAY_W2, "weight", i), {time_decay_extra_dim, attn_hidden_size}, 0);
  8279. layer.time_mix_key = create_tensor(tn(LLM_TENSOR_TIME_MIX_KEY, "weight", i), {attn_hidden_size, n_embd}, 0);
  8280. layer.time_mix_value = create_tensor(tn(LLM_TENSOR_TIME_MIX_VALUE, "weight", i), {attn_hidden_size, n_embd}, 0);
  8281. layer.time_mix_receptance = create_tensor(tn(LLM_TENSOR_TIME_MIX_RECEPTANCE, "weight", i), {attn_hidden_size, n_embd}, 0);
  8282. layer.time_mix_gate = create_tensor(tn(LLM_TENSOR_TIME_MIX_GATE, "weight", i), {attn_hidden_size, n_embd}, 0);
  8283. layer.time_mix_ln = create_tensor(tn(LLM_TENSOR_TIME_MIX_LN, "weight", i), {n_embd}, 0);
  8284. layer.time_mix_ln_b = create_tensor(tn(LLM_TENSOR_TIME_MIX_LN, "bias", i), {n_embd}, 0);
  8285. layer.time_mix_output = create_tensor(tn(LLM_TENSOR_TIME_MIX_OUTPUT, "weight", i), {n_embd, attn_hidden_size}, 0);
  8286. layer.channel_mix_lerp_k = create_tensor(tn(LLM_TENSOR_CHANNEL_MIX_LERP_K, "weight", i), {n_embd, 1, 1}, 0);
  8287. layer.channel_mix_lerp_r = create_tensor(tn(LLM_TENSOR_CHANNEL_MIX_LERP_R, "weight", i), {n_embd, 1, 1}, 0);
  8288. layer.channel_mix_key = create_tensor(tn(LLM_TENSOR_CHANNEL_MIX_KEY, "weight", i), {n_embd, ffn_size}, 0);
  8289. layer.channel_mix_value = create_tensor(tn(LLM_TENSOR_CHANNEL_MIX_VALUE, "weight", i), {ffn_size, n_embd}, 0);
  8290. layer.channel_mix_receptance = create_tensor(tn(LLM_TENSOR_CHANNEL_MIX_RECEPTANCE, "weight", i), {n_embd, n_embd}, 0);
  8291. }
  8292. } break;
  8293. case LLM_ARCH_CHAMELEON:
  8294. {
  8295. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8296. // output
  8297. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8298. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8299. // if output is NULL, init from the input tok embed
  8300. if (model.output == NULL) {
  8301. model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  8302. }
  8303. for (int i = 0; i < n_layer; ++i) {
  8304. auto & layer = model.layers[i];
  8305. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  8306. layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k, n_head}, 0);
  8307. layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k, n_head_kv}, 0);
  8308. 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);
  8309. 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);
  8310. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
  8311. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
  8312. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
  8313. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
  8314. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  8315. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  8316. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  8317. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8318. }
  8319. } break;
  8320. case LLM_ARCH_SOLAR:
  8321. {
  8322. model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
  8323. // output
  8324. {
  8325. model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  8326. model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  8327. }
  8328. for (int i = 0; i < n_layer; ++i) {
  8329. auto & layer = model.layers[i];
  8330. layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  8331. layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head}, 0);
  8332. layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  8333. layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  8334. layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd}, 0);
  8335. layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  8336. 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));
  8337. layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  8338. layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  8339. layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  8340. }
  8341. } break;
  8342. default:
  8343. throw std::runtime_error("unknown architecture");
  8344. }
  8345. if (n_moved_tensors > 0) {
  8346. LLAMA_LOG_DEBUG("%s: tensor '%s' (%s) (and %d others) cannot be used with preferred buffer type %s, using %s instead\n",
  8347. __func__, first_moved_tensor->name, ggml_type_name(first_moved_tensor->type), n_moved_tensors - 1,
  8348. ggml_backend_buft_name(first_moved_from_buft), ggml_backend_buft_name(first_moved_to_buft));
  8349. }
  8350. }
  8351. ml.done_getting_tensors();
  8352. ml.init_mappings(true, use_mlock ? &model.mlock_mmaps : nullptr);
  8353. model.mappings.reserve(ml.mappings.size());
  8354. // create the backend buffers
  8355. std::vector<std::pair<ggml_context *, llama_buf_map>> ctx_bufs;
  8356. ctx_bufs.reserve(ctx_map.size());
  8357. // Ensure we have enough capacity for the maximum backend buffer we will potentially create
  8358. const size_t n_max_backend_buffer = ctx_map.size() * ml.files.size();
  8359. model.bufs.reserve(n_max_backend_buffer);
  8360. for (auto & it : ctx_map) {
  8361. ggml_backend_buffer_type_t buft = it.first;
  8362. ggml_context * ctx = it.second;
  8363. // skip contexts without tensors
  8364. if (ggml_get_first_tensor(ctx) == nullptr) {
  8365. continue;
  8366. }
  8367. llama_buf_map bufs;
  8368. bufs.reserve(n_max_backend_buffer);
  8369. // check if it is possible to use buffer_from_host_ptr with this buffer type
  8370. ggml_backend_dev_t dev = ggml_backend_buft_get_device(buft);
  8371. if (!dev) {
  8372. // FIXME: workaround for CPU backend buft having a NULL device
  8373. dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
  8374. }
  8375. ggml_backend_dev_props props;
  8376. ggml_backend_dev_get_props(dev, &props);
  8377. bool buffer_from_host_ptr_supported = props.caps.buffer_from_host_ptr;
  8378. bool is_default_buft = buft == ggml_backend_dev_buffer_type(dev);
  8379. if (ml.use_mmap && use_mmap_buffer && buffer_from_host_ptr_supported && is_default_buft) {
  8380. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  8381. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  8382. // 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
  8383. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  8384. void * addr = nullptr;
  8385. size_t first, last; // NOLINT
  8386. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  8387. if (first >= last) {
  8388. continue;
  8389. }
  8390. const size_t max_size = ggml_get_max_tensor_size(ctx);
  8391. ggml_backend_buffer_t buf = ggml_backend_dev_buffer_from_host_ptr(dev, (char *) addr + first, last - first, max_size);
  8392. if (buf == nullptr) {
  8393. throw std::runtime_error(format("unable to allocate %s buffer", ggml_backend_buft_name(buft)));
  8394. }
  8395. model.bufs.emplace_back(buf);
  8396. bufs.emplace(idx, buf);
  8397. }
  8398. }
  8399. else {
  8400. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  8401. if (buf == nullptr) {
  8402. throw std::runtime_error(format("unable to allocate %s buffer", ggml_backend_buft_name(buft)));
  8403. }
  8404. model.bufs.emplace_back(buf);
  8405. if (use_mlock && ggml_backend_buffer_is_host(buf)) {
  8406. model.mlock_bufs.emplace_back(new llama_mlock);
  8407. auto & mlock_buf = model.mlock_bufs.back();
  8408. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  8409. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  8410. }
  8411. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  8412. bufs.emplace(idx, buf);
  8413. }
  8414. }
  8415. if (bufs.empty()) {
  8416. throw std::runtime_error("failed to allocate buffer");
  8417. }
  8418. for (auto & buf : bufs) {
  8419. // indicate that this buffer contains weights
  8420. // 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
  8421. ggml_backend_buffer_set_usage(buf.second, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  8422. }
  8423. ctx_bufs.emplace_back(ctx, bufs);
  8424. }
  8425. if (llama_supports_gpu_offload()) {
  8426. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  8427. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  8428. if (n_gpu_layers > (int) hparams.n_layer) {
  8429. LLAMA_LOG_INFO("%s: offloading output layer to GPU\n", __func__);
  8430. }
  8431. const int max_backend_supported_layers = hparams.n_layer + 1;
  8432. const int max_offloadable_layers = hparams.n_layer + 1;
  8433. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  8434. }
  8435. // print memory requirements per buffer type
  8436. for (auto & buf : model.bufs) {
  8437. 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);
  8438. }
  8439. // populate tensors_by_name
  8440. for (auto & ctx : model.ctxs) {
  8441. for (auto * cur = ggml_get_first_tensor(ctx.get()); cur != NULL; cur = ggml_get_next_tensor(ctx.get(), cur)) {
  8442. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  8443. }
  8444. }
  8445. // load tensor data
  8446. for (auto & it : ctx_bufs) {
  8447. ggml_context * ctx = it.first;
  8448. auto & bufs = it.second;
  8449. if (!ml.load_all_data(ctx, bufs, use_mlock ? &model.mlock_mmaps : NULL, progress_callback, progress_callback_user_data)) {
  8450. return false;
  8451. }
  8452. }
  8453. if (use_mmap_buffer) {
  8454. for (auto & mapping : ml.mappings) {
  8455. model.mappings.emplace_back(std::move(mapping));
  8456. }
  8457. }
  8458. return true;
  8459. }
  8460. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  8461. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  8462. model.t_start_us = ggml_time_us();
  8463. try {
  8464. llama_model_loader ml(fname, params.use_mmap, params.check_tensors, params.kv_overrides);
  8465. model.hparams.vocab_only = params.vocab_only;
  8466. try {
  8467. llm_load_arch(ml, model);
  8468. } catch(const std::exception & e) {
  8469. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  8470. }
  8471. try {
  8472. llm_load_hparams(ml, model);
  8473. } catch(const std::exception & e) {
  8474. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  8475. }
  8476. try {
  8477. llm_load_vocab(ml, model);
  8478. } catch(const std::exception & e) {
  8479. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  8480. }
  8481. llm_load_stats(ml, model);
  8482. llm_load_print_meta(ml, model);
  8483. if (model.vocab.type != LLAMA_VOCAB_TYPE_NONE &&
  8484. model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  8485. LLAMA_LOG_WARN("%s: vocab mismatch %u !- %zu ...\n", __func__, model.hparams.n_vocab, model.vocab.id_to_token.size());
  8486. }
  8487. if (params.vocab_only) {
  8488. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  8489. return 0;
  8490. }
  8491. if (!llm_load_tensors(
  8492. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  8493. params.progress_callback, params.progress_callback_user_data
  8494. )) {
  8495. return -2;
  8496. }
  8497. } catch (const std::exception & err) {
  8498. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  8499. return -1;
  8500. }
  8501. // loading time will be recalculate after the first eval, so
  8502. // we take page faults deferred by mmap() into consideration
  8503. model.t_load_us = ggml_time_us() - model.t_start_us;
  8504. return 0;
  8505. }
  8506. //
  8507. // llm_build
  8508. //
  8509. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  8510. enum llm_ffn_op_type {
  8511. LLM_FFN_SILU,
  8512. LLM_FFN_GELU,
  8513. LLM_FFN_RELU,
  8514. LLM_FFN_RELU_SQR,
  8515. LLM_FFN_SWIGLU,
  8516. };
  8517. enum llm_ffn_gate_type {
  8518. LLM_FFN_SEQ,
  8519. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  8520. };
  8521. enum llm_norm_type {
  8522. LLM_NORM,
  8523. LLM_NORM_RMS,
  8524. };
  8525. static struct ggml_tensor * llm_build_inp_embd(
  8526. struct ggml_context * ctx,
  8527. struct llama_context & lctx,
  8528. const llama_hparams & hparams,
  8529. const llama_ubatch & batch,
  8530. struct ggml_tensor * tok_embd,
  8531. const llm_build_cb & cb) {
  8532. const int64_t n_embd = hparams.n_embd;
  8533. struct ggml_tensor * inpL;
  8534. if (batch.token) {
  8535. lctx.inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  8536. cb(lctx.inp_tokens, "inp_tokens", -1);
  8537. ggml_set_input(lctx.inp_tokens);
  8538. inpL = ggml_get_rows(ctx, tok_embd, lctx.inp_tokens);
  8539. } else {
  8540. lctx.inp_embd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  8541. inpL = lctx.inp_embd;
  8542. ggml_set_input(lctx.inp_embd);
  8543. }
  8544. // For Granite architecture
  8545. if (hparams.f_embedding_scale != 0.0f) {
  8546. inpL = ggml_scale(ctx, inpL, hparams.f_embedding_scale);
  8547. }
  8548. cb(inpL, "inp_embd", -1);
  8549. return inpL;
  8550. }
  8551. static struct ggml_tensor * llm_build_inp_cross_attn_state(
  8552. struct ggml_context * ctx,
  8553. struct llama_context & lctx,
  8554. const llama_hparams & hparams,
  8555. const llm_build_cb & cb) {
  8556. const int64_t n_embd = hparams.n_embd;
  8557. struct ggml_tensor * inpCAS = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n_embd, 1601, 4);
  8558. cb(inpCAS, "inp_cross_attn_state", -1);
  8559. ggml_set_input(inpCAS);
  8560. lctx.inp_cross_attn_state = inpCAS;
  8561. return inpCAS;
  8562. }
  8563. static void llm_build_kv_store(
  8564. struct ggml_context * ctx,
  8565. const llama_hparams & hparams,
  8566. const llama_cparams & cparams,
  8567. const llama_kv_cache & kv,
  8568. struct ggml_cgraph * graph,
  8569. struct ggml_tensor * k_cur,
  8570. struct ggml_tensor * v_cur,
  8571. int32_t n_tokens,
  8572. int32_t kv_head,
  8573. const llm_build_cb & cb,
  8574. int64_t il) {
  8575. const int64_t n_ctx = cparams.n_ctx;
  8576. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  8577. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  8578. GGML_ASSERT(kv.size == n_ctx);
  8579. 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);
  8580. cb(k_cache_view, "k_cache_view", il);
  8581. // note: storing RoPE-ed version of K in the KV cache
  8582. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  8583. assert(v_cur->ne[0] == n_embd_v_gqa && v_cur->ne[1] == n_tokens);
  8584. struct ggml_tensor * v_cache_view = nullptr;
  8585. if (cparams.flash_attn) {
  8586. 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);
  8587. } else {
  8588. // note: the V cache is transposed when not using flash attention
  8589. v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  8590. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  8591. (kv_head)*ggml_element_size(kv.v_l[il]));
  8592. v_cur = ggml_transpose(ctx, v_cur);
  8593. }
  8594. cb(v_cache_view, "v_cache_view", il);
  8595. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur, v_cache_view));
  8596. }
  8597. // do mat_mul, while optionally apply lora
  8598. static struct ggml_tensor * llm_build_lora_mm(
  8599. struct llama_context & lctx,
  8600. struct ggml_context * ctx0,
  8601. struct ggml_tensor * w,
  8602. struct ggml_tensor * cur) {
  8603. struct ggml_tensor * res = ggml_mul_mat(ctx0, w, cur);
  8604. for (auto & it : lctx.lora_adapters) {
  8605. struct llama_lora_weight * lora = it.first->get_weight(w);
  8606. if (lora == nullptr) {
  8607. continue;
  8608. }
  8609. const float alpha = it.first->alpha;
  8610. const float rank = (float) lora->b->ne[0];
  8611. const float scale = alpha ? it.second * alpha / rank : it.second;
  8612. struct ggml_tensor * ab_cur = ggml_mul_mat(
  8613. ctx0, lora->b,
  8614. ggml_mul_mat(ctx0, lora->a, cur)
  8615. );
  8616. ab_cur = ggml_scale(ctx0, ab_cur, scale);
  8617. res = ggml_add(ctx0, res, ab_cur);
  8618. }
  8619. return res;
  8620. }
  8621. // do mat_mul_id, while optionally apply lora
  8622. static struct ggml_tensor * llm_build_lora_mm_id(
  8623. struct llama_context & lctx,
  8624. struct ggml_context * ctx0,
  8625. struct ggml_tensor * w, // struct ggml_tensor * as
  8626. struct ggml_tensor * cur, // struct ggml_tensor * b
  8627. struct ggml_tensor * ids) {
  8628. struct ggml_tensor * res = ggml_mul_mat_id(ctx0, w, cur, ids);
  8629. for (auto & it : lctx.lora_adapters) {
  8630. struct llama_lora_weight * lora = it.first->get_weight(w);
  8631. if (lora == nullptr) {
  8632. continue;
  8633. }
  8634. const float alpha = it.first->alpha;
  8635. const float rank = (float) lora->b->ne[0];
  8636. const float scale = alpha ? it.second * alpha / rank : it.second;
  8637. struct ggml_tensor * ab_cur = ggml_mul_mat_id(
  8638. ctx0, lora->b,
  8639. ggml_mul_mat_id(ctx0, lora->a, cur, ids),
  8640. ids
  8641. );
  8642. ab_cur = ggml_scale(ctx0, ab_cur, scale);
  8643. res = ggml_add(ctx0, res, ab_cur);
  8644. }
  8645. return res;
  8646. }
  8647. static struct ggml_tensor * llm_build_norm(
  8648. struct ggml_context * ctx,
  8649. struct ggml_tensor * cur,
  8650. const llama_hparams & hparams,
  8651. struct ggml_tensor * mw,
  8652. struct ggml_tensor * mb,
  8653. llm_norm_type type,
  8654. const llm_build_cb & cb,
  8655. int il) {
  8656. switch (type) {
  8657. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  8658. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  8659. }
  8660. if (mw || mb) {
  8661. cb(cur, "norm", il);
  8662. }
  8663. if (mw) {
  8664. cur = ggml_mul(ctx, cur, mw);
  8665. if (mb) {
  8666. cb(cur, "norm_w", il);
  8667. }
  8668. }
  8669. if (mb) {
  8670. cur = ggml_add(ctx, cur, mb);
  8671. }
  8672. return cur;
  8673. }
  8674. static struct ggml_tensor * llm_build_ffn(
  8675. struct ggml_context * ctx,
  8676. struct llama_context & lctx,
  8677. struct ggml_tensor * cur,
  8678. struct ggml_tensor * up,
  8679. struct ggml_tensor * up_b,
  8680. struct ggml_tensor * up_s,
  8681. struct ggml_tensor * gate,
  8682. struct ggml_tensor * gate_b,
  8683. struct ggml_tensor * gate_s,
  8684. struct ggml_tensor * down,
  8685. struct ggml_tensor * down_b,
  8686. struct ggml_tensor * down_s,
  8687. struct ggml_tensor * act_scales,
  8688. llm_ffn_op_type type_op,
  8689. llm_ffn_gate_type type_gate,
  8690. const llm_build_cb & cb,
  8691. int il) {
  8692. struct ggml_tensor * tmp = up ? llm_build_lora_mm(lctx, ctx, up, cur) : cur;
  8693. cb(tmp, "ffn_up", il);
  8694. if (up_b) {
  8695. tmp = ggml_add(ctx, tmp, up_b);
  8696. cb(tmp, "ffn_up_b", il);
  8697. }
  8698. if (up_s) {
  8699. tmp = ggml_mul(ctx, tmp, up_s);
  8700. cb(tmp, "ffn_up_s", il);
  8701. }
  8702. if (gate) {
  8703. switch (type_gate) {
  8704. case LLM_FFN_SEQ:
  8705. {
  8706. cur = llm_build_lora_mm(lctx, ctx, gate, tmp);
  8707. cb(cur, "ffn_gate", il);
  8708. } break;
  8709. case LLM_FFN_PAR:
  8710. {
  8711. cur = llm_build_lora_mm(lctx, ctx, gate, cur);
  8712. cb(cur, "ffn_gate", il);
  8713. } break;
  8714. }
  8715. if (gate_b) {
  8716. cur = ggml_add(ctx, cur, gate_b);
  8717. cb(cur, "ffn_gate_b", il);
  8718. }
  8719. if (gate_s) {
  8720. cur = ggml_mul(ctx, cur, gate_s);
  8721. cb(cur, "ffn_gate_s", il);
  8722. }
  8723. } else {
  8724. cur = tmp;
  8725. }
  8726. switch (type_op) {
  8727. case LLM_FFN_SILU:
  8728. {
  8729. cur = ggml_silu(ctx, cur);
  8730. cb(cur, "ffn_silu", il);
  8731. } break;
  8732. case LLM_FFN_GELU:
  8733. {
  8734. cur = ggml_gelu(ctx, cur);
  8735. cb(cur, "ffn_gelu", il);
  8736. if (act_scales != NULL) {
  8737. cur = ggml_div(ctx, cur, act_scales);
  8738. cb(cur, "ffn_act", il);
  8739. }
  8740. } break;
  8741. case LLM_FFN_RELU:
  8742. {
  8743. cur = ggml_relu(ctx, cur);
  8744. cb(cur, "ffn_relu", il);
  8745. } break;
  8746. case LLM_FFN_RELU_SQR:
  8747. {
  8748. cur = ggml_relu(ctx, cur);
  8749. cb(cur, "ffn_relu", il);
  8750. cur = ggml_sqr(ctx, cur);
  8751. cb(cur, "ffn_sqr(relu)", il);
  8752. } break;
  8753. case LLM_FFN_SWIGLU:
  8754. {
  8755. // Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf
  8756. int64_t split_point = cur->ne[0] / 2;
  8757. struct ggml_tensor * x0 = ggml_cont(ctx, ggml_view_2d(ctx, cur, split_point, cur->ne[1], cur->nb[1], 0));
  8758. 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)));
  8759. x0 = ggml_silu(ctx, x0);
  8760. cb(cur, "ffn_silu", il);
  8761. cur = ggml_mul(ctx, x0, x1);
  8762. cb(cur, "ffn_mul", il);
  8763. } break;
  8764. }
  8765. if (type_gate == LLM_FFN_PAR) {
  8766. cur = ggml_mul(ctx, cur, tmp);
  8767. cb(cur, "ffn_gate_par", il);
  8768. }
  8769. if (down) {
  8770. cur = llm_build_lora_mm(lctx, ctx, down, cur);
  8771. }
  8772. if (down_b) {
  8773. cb(cur, "ffn_down", il);
  8774. }
  8775. if (down_b) {
  8776. cur = ggml_add(ctx, cur, down_b);
  8777. }
  8778. if (down_s) {
  8779. cur = ggml_mul(ctx, cur, down_s);
  8780. cb(cur, "ffn_down_s", il);
  8781. }
  8782. return cur;
  8783. }
  8784. static struct ggml_tensor * llm_build_moe_ffn(
  8785. struct ggml_context * ctx,
  8786. struct llama_context & lctx,
  8787. struct ggml_tensor * cur,
  8788. struct ggml_tensor * gate_inp,
  8789. struct ggml_tensor * up_exps,
  8790. struct ggml_tensor * gate_exps,
  8791. struct ggml_tensor * down_exps,
  8792. int64_t n_expert,
  8793. int64_t n_expert_used,
  8794. llm_ffn_op_type type_op,
  8795. bool norm_w,
  8796. bool scale_w,
  8797. float w_scale,
  8798. const llm_build_cb & cb,
  8799. int il) {
  8800. int64_t n_embd = cur->ne[0];
  8801. int64_t n_tokens = cur->ne[1];
  8802. ggml_tensor * logits = llm_build_lora_mm(lctx, ctx, gate_inp, cur); // [n_expert, n_tokens]
  8803. cb(logits, "ffn_moe_logits", il);
  8804. ggml_tensor * probs = ggml_soft_max(ctx, logits); // [n_expert, n_tokens]
  8805. cb(probs, "ffn_moe_probs", il);
  8806. // select experts
  8807. ggml_tensor * selected_experts = ggml_top_k(ctx, probs, n_expert_used); // [n_expert_used, n_tokens]
  8808. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  8809. cb(selected_experts, "ffn_moe_topk", il);
  8810. ggml_tensor * weights = ggml_get_rows(ctx,
  8811. ggml_reshape_3d(ctx, probs, 1, n_expert, n_tokens), selected_experts); // [1, n_expert_used, n_tokens]
  8812. cb(weights, "ffn_moe_weights", il);
  8813. if (norm_w) {
  8814. weights = ggml_reshape_2d(ctx, weights, n_expert_used, n_tokens);
  8815. ggml_tensor * weights_sum = ggml_sum_rows(ctx, weights); // [1, n_tokens]
  8816. cb(weights_sum, "ffn_moe_weights_sum", il);
  8817. weights = ggml_div(ctx, weights, weights_sum); // [n_expert_used, n_tokens]
  8818. cb(weights, "ffn_moe_weights_norm", il);
  8819. weights = ggml_reshape_3d(ctx, weights, 1, n_expert_used, n_tokens);
  8820. }
  8821. if (scale_w) {
  8822. weights = ggml_scale(ctx, weights, w_scale);
  8823. cb(weights, "ffn_moe_weights_scaled", il);
  8824. }
  8825. cur = ggml_reshape_3d(ctx, cur, n_embd, 1, n_tokens);
  8826. ggml_tensor * up = llm_build_lora_mm_id(lctx, ctx, up_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  8827. cb(up, "ffn_moe_up", il);
  8828. ggml_tensor * gate = llm_build_lora_mm_id(lctx, ctx, gate_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  8829. cb(gate, "ffn_moe_gate", il);
  8830. switch (type_op) {
  8831. case LLM_FFN_SILU:
  8832. {
  8833. gate = ggml_silu(ctx, gate);
  8834. cb(gate, "ffn_moe_silu", il);
  8835. } break;
  8836. case LLM_FFN_GELU:
  8837. {
  8838. gate = ggml_gelu(ctx, gate);
  8839. cb(gate, "ffn_moe_gelu", il);
  8840. } break;
  8841. default:
  8842. GGML_ABORT("fatal error");
  8843. }
  8844. ggml_tensor * par = ggml_mul(ctx, up, gate); // [n_ff, n_expert_used, n_tokens]
  8845. cb(par, "ffn_moe_gate_par", il);
  8846. ggml_tensor * experts = llm_build_lora_mm_id(lctx, ctx, down_exps, par, selected_experts); // [n_embd, n_expert_used, n_tokens]
  8847. cb(experts, "ffn_moe_down", il);
  8848. experts = ggml_mul(ctx, experts, weights);
  8849. // aggregate experts
  8850. ggml_tensor * moe_out = nullptr;
  8851. for (int i = 0; i < n_expert_used; ++i) {
  8852. ggml_tensor * cur_expert = ggml_view_2d(ctx, experts, n_embd, n_tokens,
  8853. experts->nb[2], i*experts->nb[1]);
  8854. if (i == 0) {
  8855. moe_out = cur_expert;
  8856. } else {
  8857. moe_out = ggml_add(ctx, moe_out, cur_expert);
  8858. }
  8859. }
  8860. if (n_expert_used == 1) {
  8861. // avoid returning a non-contiguous tensor
  8862. moe_out = ggml_cont(ctx, moe_out);
  8863. }
  8864. return moe_out;
  8865. }
  8866. static struct ggml_tensor * llm_build_kqv(
  8867. struct ggml_context * ctx,
  8868. struct llama_context & lctx,
  8869. const llama_kv_cache & kv,
  8870. struct ggml_cgraph * graph,
  8871. struct ggml_tensor * wo,
  8872. struct ggml_tensor * wo_b,
  8873. struct ggml_tensor * q_cur,
  8874. struct ggml_tensor * kq_mask,
  8875. int32_t n_tokens,
  8876. int32_t n_kv,
  8877. float kq_scale,
  8878. const llm_build_cb & cb,
  8879. int il) {
  8880. const llama_model & model = lctx.model;
  8881. const llama_hparams & hparams = lctx.model.hparams;
  8882. const llama_cparams & cparams = lctx.cparams;
  8883. const int64_t n_ctx = cparams.n_ctx;
  8884. const int64_t n_head = hparams.n_head(il);
  8885. const int64_t n_head_kv = hparams.n_head_kv(il);
  8886. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  8887. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  8888. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  8889. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  8890. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  8891. cb(q, "q", il);
  8892. struct ggml_tensor * k =
  8893. ggml_view_3d(ctx, kv.k_l[il],
  8894. n_embd_head_k, n_kv, n_head_kv,
  8895. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  8896. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  8897. 0);
  8898. cb(k, "k", il);
  8899. struct ggml_tensor * cur;
  8900. if (cparams.flash_attn) {
  8901. GGML_UNUSED(model);
  8902. GGML_UNUSED(n_ctx);
  8903. // split cached v into n_head heads (not transposed)
  8904. struct ggml_tensor * v =
  8905. ggml_view_3d(ctx, kv.v_l[il],
  8906. n_embd_head_v, n_kv, n_head_kv,
  8907. ggml_row_size(kv.v_l[il]->type, n_embd_v_gqa),
  8908. ggml_row_size(kv.v_l[il]->type, n_embd_head_v),
  8909. 0);
  8910. cb(v, "v", il);
  8911. cur = ggml_flash_attn_ext(ctx, q, k, v, kq_mask, kq_scale, hparams.f_max_alibi_bias,
  8912. hparams.attn_soft_cap ? hparams.f_attn_logit_softcapping : 0.0f);
  8913. ggml_flash_attn_ext_set_prec(cur, GGML_PREC_F32);
  8914. cur = ggml_reshape_2d(ctx, cur, n_embd_head_v*n_head, n_tokens);
  8915. } else {
  8916. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  8917. cb(kq, "kq", il);
  8918. // note: this op tends to require high floating point range
  8919. // while for some models F16 is enough, for others it is not, so we default to F32 here
  8920. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  8921. if (model.arch == LLM_ARCH_GROK) {
  8922. // need to do the following:
  8923. // multiply by attn_output_multiplyer of 0.08838834764831845
  8924. // and then :
  8925. // kq = 30 * tanh(kq / 30)
  8926. // before the softmax below
  8927. kq = ggml_tanh(ctx, ggml_scale(ctx, kq, 0.08838834764831845f/30.0f));
  8928. kq = ggml_scale(ctx, kq, 30);
  8929. }
  8930. if (hparams.attn_soft_cap) {
  8931. kq = ggml_scale(ctx, kq, 1.0f / hparams.f_attn_logit_softcapping);
  8932. kq = ggml_tanh(ctx, kq);
  8933. kq = ggml_scale(ctx, kq, hparams.f_attn_logit_softcapping);
  8934. }
  8935. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_scale, hparams.f_max_alibi_bias);
  8936. cb(kq, "kq_soft_max_ext", il);
  8937. GGML_ASSERT(kv.size == n_ctx);
  8938. // split cached v into n_head heads
  8939. struct ggml_tensor * v =
  8940. ggml_view_3d(ctx, kv.v_l[il],
  8941. n_kv, n_embd_head_v, n_head_kv,
  8942. ggml_element_size(kv.v_l[il])*n_ctx,
  8943. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  8944. 0);
  8945. cb(v, "v", il);
  8946. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  8947. cb(kqv, "kqv", il);
  8948. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  8949. cb(kqv_merged, "kqv_merged", il);
  8950. cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_v*n_head, n_tokens);
  8951. cb(cur, "kqv_merged_cont", il);
  8952. }
  8953. ggml_build_forward_expand(graph, cur);
  8954. if (wo) {
  8955. cur = llm_build_lora_mm(lctx, ctx, wo, cur);
  8956. }
  8957. if (wo_b) {
  8958. cb(cur, "kqv_wo", il);
  8959. }
  8960. if (wo_b) {
  8961. cur = ggml_add(ctx, cur, wo_b);
  8962. }
  8963. return cur;
  8964. }
  8965. static struct ggml_tensor * llm_build_kv(
  8966. struct ggml_context * ctx,
  8967. struct llama_context & lctx,
  8968. const llama_kv_cache & kv,
  8969. struct ggml_cgraph * graph,
  8970. struct ggml_tensor * wo,
  8971. struct ggml_tensor * wo_b,
  8972. struct ggml_tensor * k_cur,
  8973. struct ggml_tensor * v_cur,
  8974. struct ggml_tensor * q_cur,
  8975. struct ggml_tensor * kq_mask,
  8976. int32_t n_tokens,
  8977. int32_t kv_head,
  8978. int32_t n_kv,
  8979. float kq_scale,
  8980. const llm_build_cb & cb,
  8981. int il) {
  8982. const llama_hparams & hparams = lctx.model.hparams;
  8983. const llama_cparams & cparams = lctx.cparams;
  8984. // these nodes are added to the graph together so that they are not reordered
  8985. // by doing so, the number of splits in the graph is reduced
  8986. ggml_build_forward_expand(graph, q_cur);
  8987. ggml_build_forward_expand(graph, k_cur);
  8988. ggml_build_forward_expand(graph, v_cur);
  8989. llm_build_kv_store(ctx, hparams, cparams, kv, graph, k_cur, v_cur, n_tokens, kv_head, cb, il);
  8990. struct ggml_tensor * cur;
  8991. cur = llm_build_kqv(ctx, lctx, kv, graph, wo, wo_b, q_cur, kq_mask, n_tokens, n_kv, kq_scale, cb, il);
  8992. cb(cur, "kqv_out", il);
  8993. return cur;
  8994. }
  8995. static struct ggml_tensor * llm_build_copy_mask_state(
  8996. struct ggml_context * ctx,
  8997. struct ggml_cgraph * graph,
  8998. struct ggml_tensor * s,
  8999. struct ggml_tensor * state_copy,
  9000. struct ggml_tensor * state_mask,
  9001. int32_t n_state,
  9002. int32_t kv_size,
  9003. int32_t kv_head,
  9004. int32_t n_kv,
  9005. int32_t n_seqs) {
  9006. struct ggml_tensor * states = ggml_reshape_2d(ctx, s, n_state, kv_size);
  9007. // copy states
  9008. // NOTE: assuming the copy destinations are ALL contained between kv_head and kv_head + n_kv
  9009. // this shrinks the tensors's ne[1] to n_kv
  9010. states = ggml_get_rows(ctx, states, state_copy);
  9011. // clear states of sequences which are starting at the beginning of this batch
  9012. // FIXME: zero-out NANs?
  9013. states = ggml_mul(ctx, states, state_mask);
  9014. // copy states which won't be changed further (between n_seqs and n_kv)
  9015. ggml_build_forward_expand(graph,
  9016. ggml_cpy(ctx,
  9017. ggml_view_1d(ctx, states, n_state*(n_kv - n_seqs), n_seqs*n_state*ggml_element_size(states)),
  9018. ggml_view_1d(ctx, s, n_state*(n_kv - n_seqs), (kv_head + n_seqs)*n_state*ggml_element_size(s))));
  9019. // the part of the states that will be used and modified
  9020. return ggml_view_2d(ctx, states, n_state, n_seqs, states->nb[1], 0);
  9021. }
  9022. // TODO: split
  9023. static struct ggml_tensor * llm_build_mamba(
  9024. struct ggml_context * ctx,
  9025. struct llama_context & lctx,
  9026. const llama_ubatch & batch,
  9027. struct ggml_cgraph * graph,
  9028. struct ggml_tensor * cur,
  9029. struct ggml_tensor * state_copy,
  9030. struct ggml_tensor * state_mask,
  9031. int32_t kv_head,
  9032. int32_t n_kv,
  9033. const llm_build_cb & cb,
  9034. int il) {
  9035. const llama_model & model = lctx.model;
  9036. const llama_hparams & hparams = model.hparams;
  9037. const llama_kv_cache & kv = lctx.kv_self;
  9038. const int64_t d_conv = hparams.ssm_d_conv;
  9039. const int64_t d_inner = hparams.ssm_d_inner;
  9040. const int64_t d_state = hparams.ssm_d_state;
  9041. const int64_t dt_rank = hparams.ssm_dt_rank;
  9042. const int64_t n_seqs = batch.n_seqs;
  9043. // Some variants of Mamba arch (e.g. FalconMamba do apply layer norm on B and Dt layers)
  9044. const bool ssm_dt_b_c_rms = hparams.ssm_dt_b_c_rms;
  9045. // Use the same RMS norm as the final layer norm
  9046. const float norm_rms_eps = hparams.f_norm_rms_eps;
  9047. const int64_t n_seq_tokens = batch.n_seq_tokens;
  9048. GGML_ASSERT(n_seqs != 0);
  9049. GGML_ASSERT(batch.equal_seqs);
  9050. GGML_ASSERT(batch.n_tokens == n_seq_tokens * n_seqs);
  9051. struct ggml_tensor * conv_states_all = kv.k_l[il];
  9052. struct ggml_tensor * ssm_states_all = kv.v_l[il];
  9053. // (ab)using the KV cache to store the states
  9054. struct ggml_tensor * conv = llm_build_copy_mask_state(ctx,
  9055. graph, conv_states_all, state_copy, state_mask,
  9056. hparams.n_embd_k_s(), kv.size, kv_head, n_kv, n_seqs);
  9057. conv = ggml_reshape_3d(ctx, conv, d_conv - 1, d_inner, n_seqs);
  9058. struct ggml_tensor * ssm = llm_build_copy_mask_state(ctx,
  9059. graph, ssm_states_all, state_copy, state_mask,
  9060. hparams.n_embd_v_s(), kv.size, kv_head, n_kv, n_seqs);
  9061. ssm = ggml_reshape_3d(ctx, ssm, d_state, d_inner, n_seqs);
  9062. // {n_embd, n_tokens} => {n_embd, n_seq_tokens, n_seqs}
  9063. cur = ggml_reshape_3d(ctx, cur, cur->ne[0], n_seq_tokens, n_seqs);
  9064. // {n_embd, 2*d_inner} @ {n_embd, n_seq_tokens, n_seqs} => {2*d_inner, n_seq_tokens, n_seqs}
  9065. struct ggml_tensor * xz = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_in, cur);
  9066. // split the above in two
  9067. // => {d_inner, n_seq_tokens, n_seqs}
  9068. struct ggml_tensor * x = ggml_view_3d(ctx, xz, d_inner, xz->ne[1], xz->ne[2], xz->nb[1], xz->nb[2], 0);
  9069. 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));
  9070. // conv
  9071. {
  9072. // => {d_conv - 1 + n_seq_tokens, d_inner, n_seqs}
  9073. struct ggml_tensor * conv_x = ggml_concat(ctx, conv, ggml_transpose(ctx, x), 0);
  9074. // copy last (d_conv - 1) columns back into the state cache
  9075. 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]));
  9076. ggml_build_forward_expand(graph,
  9077. ggml_cpy(ctx, last_conv,
  9078. ggml_view_1d(ctx, conv_states_all,
  9079. (d_conv - 1)*(d_inner)*(n_seqs),
  9080. kv_head*(d_conv - 1)*(d_inner)*ggml_element_size(conv_states_all))));
  9081. // 1D convolution
  9082. // The equivalent is to make a self-overlapping view of conv_x
  9083. // over d_conv columns at each stride in the 3rd dimension,
  9084. // then element-wise multiply that with the conv1d weight,
  9085. // then sum the elements of each row,
  9086. // (the last two steps are a dot product over rows (also doable with mul_mat))
  9087. // then permute away the ne[0] dimension,
  9088. // and then you're left with the resulting x tensor.
  9089. // For simultaneous sequences, all sequences need to have the same length.
  9090. x = ggml_ssm_conv(ctx, conv_x, model.layers[il].ssm_conv1d);
  9091. // bias
  9092. x = ggml_add(ctx, x, model.layers[il].ssm_conv1d_b);
  9093. x = ggml_silu(ctx, x);
  9094. }
  9095. // ssm
  9096. {
  9097. // {d_inner, dt_rank + 2*d_state} @ {d_inner, n_seq_tokens, n_seqs} => {dt_rank + 2*d_state, n_seq_tokens, n_seqs}
  9098. struct ggml_tensor * x_db = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_x, x);
  9099. // split
  9100. 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);
  9101. 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);
  9102. 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));
  9103. // Some Mamba variants (e.g. FalconMamba) apply RMS norm in B, C & Dt layers
  9104. if (ssm_dt_b_c_rms) {
  9105. dt = ggml_rms_norm(ctx, dt, norm_rms_eps);
  9106. B = ggml_rms_norm(ctx, B, norm_rms_eps);
  9107. C = ggml_rms_norm(ctx, C, norm_rms_eps);
  9108. }
  9109. // {dt_rank, d_inner} @ {dt_rank, n_seq_tokens, n_seqs} => {d_inner, n_seq_tokens, n_seqs}
  9110. dt = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_dt, dt);
  9111. dt = ggml_add(ctx, dt, model.layers[il].ssm_dt_b);
  9112. // Custom operator to optimize the parallel associative scan
  9113. // as described in the Annex D of the Mamba paper.
  9114. // => {d_inner, n_seq_tokens, n_seqs} and {d_state, d_inner, n_seqs}
  9115. struct ggml_tensor * y_ssm = ggml_ssm_scan(ctx, ssm, x, dt, model.layers[il].ssm_a, B, C);
  9116. // store last states
  9117. ggml_build_forward_expand(graph,
  9118. ggml_cpy(ctx,
  9119. ggml_view_1d(ctx, y_ssm, d_state*d_inner*n_seqs, x->nb[3]),
  9120. 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))));
  9121. struct ggml_tensor * y = ggml_view_3d(ctx, y_ssm, d_inner, n_seq_tokens, n_seqs, x->nb[1], x->nb[2], 0);
  9122. // TODO: skip computing output earlier for unused tokens
  9123. // {d_inner, n_seq_tokens, n_seqs} * {d_inner} => {d_inner, n_seq_tokens, n_seqs}
  9124. y = ggml_add(ctx, y, ggml_mul(ctx, x, model.layers[il].ssm_d));
  9125. y = ggml_mul(ctx, y, ggml_silu(ctx, ggml_cont(ctx, z)));
  9126. // {d_inner, n_embd} @ {d_inner, n_seq_tokens, n_seqs} => {n_embd, n_seq_tokens, n_seqs}
  9127. cur = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_out, y);
  9128. }
  9129. // {n_embd, n_seq_tokens, n_seqs} => {n_embd, n_tokens}
  9130. cur = ggml_reshape_2d(ctx, cur, cur->ne[0], n_seq_tokens * n_seqs);
  9131. cb(cur, "mamba_out", il);
  9132. return cur;
  9133. }
  9134. static struct ggml_tensor * llm_build_rwkv6_time_mix(
  9135. struct llama_context & lctx,
  9136. struct ggml_context * ctx,
  9137. const struct llama_layer * layer,
  9138. struct ggml_tensor * cur,
  9139. struct ggml_tensor * x_prev,
  9140. struct ggml_tensor ** wkv_state) {
  9141. size_t n_embd = cur->ne[0];
  9142. size_t n_seq_tokens = cur->ne[1];
  9143. size_t n_seqs = cur->ne[2];
  9144. size_t head_size = layer->time_mix_first->ne[0];
  9145. size_t head_count = layer->time_mix_first->ne[1];
  9146. size_t n_tokens = n_seqs * n_seq_tokens;
  9147. struct ggml_tensor * sx = ggml_sub(ctx, x_prev, cur);
  9148. sx = ggml_reshape_2d(ctx, sx, n_embd, n_tokens);
  9149. cur = ggml_reshape_2d(ctx, cur, n_embd, n_tokens);
  9150. struct ggml_tensor * xxx = ggml_add(ctx, ggml_mul(ctx, sx, layer->time_mix_lerp_x), cur);
  9151. xxx = ggml_reshape_4d(
  9152. ctx,
  9153. ggml_tanh(
  9154. ctx,
  9155. ggml_mul_mat(ctx, layer->time_mix_w1, xxx)
  9156. ),
  9157. layer->time_mix_w1->ne[1] / 5, 1, 5, n_tokens
  9158. );
  9159. xxx = ggml_cont(ctx, ggml_permute(ctx, xxx, 0, 1, 3, 2));
  9160. xxx = ggml_mul_mat(
  9161. ctx,
  9162. ggml_reshape_4d(
  9163. ctx,
  9164. layer->time_mix_w2,
  9165. layer->time_mix_w2->ne[0], layer->time_mix_w2->ne[1], 1, 5
  9166. ),
  9167. xxx
  9168. );
  9169. struct ggml_tensor *mw = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], 0);
  9170. struct ggml_tensor *mk = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * sizeof(float));
  9171. struct ggml_tensor *mv = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * 2 * sizeof(float));
  9172. struct ggml_tensor *mr = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * 3 * sizeof(float));
  9173. struct ggml_tensor *mg = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * 4 * sizeof(float));
  9174. struct ggml_tensor * xw = ggml_add(
  9175. ctx,
  9176. ggml_mul(
  9177. ctx,
  9178. ggml_add(ctx, mw, layer->time_mix_lerp_w),
  9179. sx
  9180. ),
  9181. cur
  9182. );
  9183. struct ggml_tensor * xk = ggml_add(
  9184. ctx,
  9185. ggml_mul(
  9186. ctx,
  9187. ggml_add(ctx, mk, layer->time_mix_lerp_k),
  9188. sx
  9189. ),
  9190. cur
  9191. );
  9192. struct ggml_tensor * xv = ggml_add(
  9193. ctx,
  9194. ggml_mul(
  9195. ctx,
  9196. ggml_add(ctx, mv, layer->time_mix_lerp_v),
  9197. sx
  9198. ),
  9199. cur
  9200. );
  9201. struct ggml_tensor * xr = ggml_add(
  9202. ctx,
  9203. ggml_mul(
  9204. ctx,
  9205. ggml_add(ctx, mr, layer->time_mix_lerp_r),
  9206. sx
  9207. ),
  9208. cur
  9209. );
  9210. struct ggml_tensor * xg = ggml_add(
  9211. ctx,
  9212. ggml_mul(
  9213. ctx,
  9214. ggml_add(ctx, mg, layer->time_mix_lerp_g),
  9215. sx
  9216. ),
  9217. cur
  9218. );
  9219. 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);
  9220. 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);
  9221. 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);
  9222. struct ggml_tensor * g = ggml_silu(
  9223. ctx,
  9224. llm_build_lora_mm(lctx, ctx, layer->time_mix_gate, xg)
  9225. );
  9226. struct ggml_tensor * w = ggml_mul_mat(
  9227. ctx,
  9228. layer->time_mix_decay_w2,
  9229. ggml_tanh(
  9230. ctx,
  9231. ggml_mul_mat(ctx, layer->time_mix_decay_w1, xw)
  9232. )
  9233. );
  9234. w = ggml_add(ctx, w, ggml_reshape_1d(ctx, layer->time_mix_decay, n_embd));
  9235. w = ggml_exp(ctx, ggml_neg(ctx, ggml_exp(ctx, w)));
  9236. w = ggml_reshape_4d(ctx, w, 1, head_size, head_count, n_tokens);
  9237. k = ggml_transpose(ctx, k);
  9238. v = ggml_transpose(ctx, v);
  9239. r = ggml_transpose(ctx, r);
  9240. struct ggml_tensor * wkv_output = ggml_rwkv_wkv6(ctx, k, v, r, layer->time_mix_first, w, *wkv_state);
  9241. cur = ggml_view_1d(ctx, wkv_output, n_embd * n_tokens, 0);
  9242. *wkv_state = ggml_view_1d(ctx, wkv_output, n_embd * head_size * n_seqs, n_embd * n_tokens * sizeof(float));
  9243. // group norm with head_count groups
  9244. cur = ggml_reshape_3d(ctx, cur, n_embd / head_count, head_count, n_tokens);
  9245. cur = ggml_norm(ctx, cur, 64e-5f);
  9246. // Convert back to regular vectors.
  9247. cur = ggml_reshape_2d(ctx, cur, n_embd, n_tokens);
  9248. cur = ggml_add(ctx, ggml_mul(ctx, cur, layer->time_mix_ln), layer->time_mix_ln_b);
  9249. cur = ggml_mul(ctx, cur, g);
  9250. cur = llm_build_lora_mm(lctx, ctx, layer->time_mix_output, cur);
  9251. return ggml_reshape_3d(ctx, cur, n_embd, n_seq_tokens, n_seqs);
  9252. }
  9253. static struct ggml_tensor * llm_build_rwkv6_channel_mix(
  9254. struct llama_context & lctx,
  9255. struct ggml_context * ctx,
  9256. const struct llama_layer * layer,
  9257. struct ggml_tensor * cur,
  9258. struct ggml_tensor * x_prev) {
  9259. struct ggml_tensor * sx = ggml_sub(ctx, x_prev, cur);
  9260. struct ggml_tensor * xk = ggml_add(ctx, ggml_mul(ctx, sx, layer->channel_mix_lerp_k), cur);
  9261. struct ggml_tensor * xr = ggml_add(ctx, ggml_mul(ctx, sx, layer->channel_mix_lerp_r), cur);
  9262. struct ggml_tensor * r = ggml_sigmoid(ctx, llm_build_lora_mm(lctx, ctx, layer->channel_mix_receptance, xr));
  9263. struct ggml_tensor * k = ggml_sqr(
  9264. ctx,
  9265. ggml_relu(
  9266. ctx,
  9267. llm_build_lora_mm(lctx, ctx, layer->channel_mix_key, xk)
  9268. )
  9269. );
  9270. return ggml_mul(ctx, r, llm_build_lora_mm(lctx, ctx, layer->channel_mix_value, k));
  9271. }
  9272. struct llm_build_context {
  9273. const llama_model & model;
  9274. llama_context & lctx;
  9275. const llama_hparams & hparams;
  9276. const llama_cparams & cparams;
  9277. const llama_ubatch & ubatch;
  9278. const llama_kv_cache & kv_self;
  9279. const int64_t n_embd;
  9280. const int64_t n_layer;
  9281. const int64_t n_rot;
  9282. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  9283. const int64_t n_head;
  9284. const int64_t n_head_kv;
  9285. const int64_t n_embd_head_k;
  9286. const int64_t n_embd_k_gqa;
  9287. const int64_t n_embd_head_v;
  9288. const int64_t n_embd_v_gqa;
  9289. const int64_t n_expert;
  9290. const int64_t n_expert_used;
  9291. const float freq_base;
  9292. const float freq_scale;
  9293. const float ext_factor;
  9294. const float attn_factor;
  9295. const float beta_fast;
  9296. const float beta_slow;
  9297. const float norm_eps;
  9298. const float norm_rms_eps;
  9299. const int32_t n_tokens;
  9300. const int32_t n_kv; // size of KV cache to consider (n_kv <= kv_self.size)
  9301. const int32_t n_outputs;
  9302. const int32_t n_outputs_enc;
  9303. const int32_t kv_head; // index of where we store new KV data in the cache
  9304. const int32_t n_ctx_orig;
  9305. const bool flash_attn;
  9306. const enum llama_pooling_type pooling_type;
  9307. const enum llama_rope_type rope_type;
  9308. const llm_build_cb & cb;
  9309. std::vector<uint8_t> & buf_compute_meta;
  9310. struct ggml_context * ctx0 = nullptr;
  9311. // TODO: consider making the entire interface noexcept
  9312. llm_build_context(
  9313. llama_context & lctx,
  9314. const llama_ubatch & ubatch,
  9315. const llm_build_cb & cb,
  9316. bool worst_case) :
  9317. model (lctx.model),
  9318. lctx (lctx),
  9319. hparams (model.hparams),
  9320. cparams (lctx.cparams),
  9321. ubatch (ubatch),
  9322. kv_self (lctx.kv_self),
  9323. n_embd (hparams.n_embd),
  9324. n_layer (hparams.n_layer),
  9325. n_rot (hparams.n_rot),
  9326. n_ctx (cparams.n_ctx),
  9327. n_head (hparams.n_head()),
  9328. n_head_kv (hparams.n_head_kv()),
  9329. n_embd_head_k (hparams.n_embd_head_k),
  9330. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  9331. n_embd_head_v (hparams.n_embd_head_v),
  9332. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  9333. n_expert (hparams.n_expert),
  9334. n_expert_used (hparams.n_expert_used),
  9335. freq_base (cparams.rope_freq_base),
  9336. freq_scale (cparams.rope_freq_scale),
  9337. ext_factor (cparams.yarn_ext_factor),
  9338. attn_factor (cparams.yarn_attn_factor),
  9339. beta_fast (cparams.yarn_beta_fast),
  9340. beta_slow (cparams.yarn_beta_slow),
  9341. norm_eps (hparams.f_norm_eps),
  9342. norm_rms_eps (hparams.f_norm_rms_eps),
  9343. n_tokens (ubatch.n_tokens),
  9344. n_kv (worst_case ? kv_self.size : kv_self.n),
  9345. n_outputs (worst_case ? n_tokens : lctx.n_outputs),
  9346. n_outputs_enc (worst_case ? n_tokens : lctx.embd_enc.size() / hparams.n_embd),
  9347. kv_head (worst_case ? (kv_self.recurrent ? 0 : kv_self.size - n_tokens) : kv_self.head),
  9348. n_ctx_orig (cparams.n_ctx_orig_yarn),
  9349. flash_attn (cparams.flash_attn),
  9350. pooling_type (cparams.pooling_type),
  9351. rope_type (hparams.rope_type),
  9352. cb (cb),
  9353. buf_compute_meta (lctx.buf_compute_meta) {
  9354. // all initializations should be done in init()
  9355. }
  9356. void init() {
  9357. struct ggml_init_params params = {
  9358. /*.mem_size =*/ buf_compute_meta.size(),
  9359. /*.mem_buffer =*/ buf_compute_meta.data(),
  9360. /*.no_alloc =*/ true,
  9361. };
  9362. ctx0 = ggml_init(params);
  9363. lctx.inp_tokens = nullptr;
  9364. lctx.inp_embd = nullptr;
  9365. lctx.inp_pos = nullptr;
  9366. lctx.inp_out_ids = nullptr;
  9367. lctx.inp_KQ_mask = nullptr;
  9368. lctx.inp_KQ_mask_swa = nullptr;
  9369. lctx.inp_K_shift = nullptr;
  9370. lctx.inp_mean = nullptr;
  9371. lctx.inp_cls = nullptr;
  9372. lctx.inp_s_copy = nullptr;
  9373. lctx.inp_s_mask = nullptr;
  9374. lctx.inp_s_seq = nullptr;
  9375. lctx.inp_pos_bucket = nullptr;
  9376. lctx.inp_embd_enc = nullptr;
  9377. lctx.inp_KQ_mask_cross = nullptr;
  9378. lctx.inp_cross_attn_state = nullptr;
  9379. }
  9380. void free() {
  9381. ggml_free(ctx0);
  9382. ctx0 = nullptr;
  9383. }
  9384. struct ggml_cgraph * build_k_shift() {
  9385. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9386. GGML_ASSERT(kv_self.size == n_ctx);
  9387. lctx.inp_K_shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_ctx);
  9388. cb(lctx.inp_K_shift, "K_shift", -1);
  9389. ggml_set_input(lctx.inp_K_shift);
  9390. for (int il = 0; il < n_layer; ++il) {
  9391. const int64_t n_head_kv = hparams.n_head_kv(il);
  9392. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  9393. struct ggml_tensor * rope_factors = build_rope_factors(il);
  9394. struct ggml_tensor * k =
  9395. ggml_view_3d(ctx0, kv_self.k_l[il],
  9396. n_embd_head_k, n_head_kv, n_ctx,
  9397. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  9398. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  9399. 0);
  9400. struct ggml_tensor * tmp;
  9401. if (ggml_is_quantized(k->type)) {
  9402. // dequantize to f32 -> RoPE -> quantize back
  9403. tmp = ggml_cast(ctx0, k, GGML_TYPE_F32);
  9404. cb(tmp, "K_f32", il);
  9405. for (auto & backend : lctx.backends) {
  9406. // Figure out which backend KV cache belongs to
  9407. if (ggml_backend_supports_buft(backend.get(), ggml_backend_buffer_get_type(kv_self.k_l[il]->buffer))) {
  9408. ggml_backend_sched_set_tensor_backend(lctx.sched.get(), tmp, backend.get());
  9409. break;
  9410. }
  9411. }
  9412. tmp = ggml_rope_ext_inplace(ctx0, tmp,
  9413. lctx.inp_K_shift, rope_factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9414. ext_factor, attn_factor, beta_fast, beta_slow);
  9415. cb(tmp, "K_shifted_f32", il);
  9416. tmp = ggml_cpy(ctx0, tmp, k);
  9417. } else {
  9418. // we rotate only the first n_rot dimensions
  9419. tmp = ggml_rope_ext_inplace(ctx0, k,
  9420. lctx.inp_K_shift, rope_factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9421. ext_factor, attn_factor, beta_fast, beta_slow);
  9422. }
  9423. cb(tmp, "K_shifted", il);
  9424. ggml_build_forward_expand(gf, tmp);
  9425. }
  9426. return gf;
  9427. }
  9428. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  9429. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9430. for (uint32_t i = 0; i < ids.size(); ++i) {
  9431. const uint32_t id = ids[i];
  9432. if (i == id || id == ids.size()) {
  9433. continue;
  9434. }
  9435. uint32_t nm = 1;
  9436. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  9437. nm++;
  9438. }
  9439. for (int il = 0; il < n_layer; ++il) {
  9440. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  9441. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  9442. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  9443. n_embd_k_gqa, nm,
  9444. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  9445. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  9446. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  9447. n_embd_k_gqa, nm,
  9448. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  9449. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  9450. ggml_tensor * view_v_src;
  9451. ggml_tensor * view_v_dst;
  9452. if (flash_attn) {
  9453. // NOTE: the V cache is not transposed when using flash attention
  9454. view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  9455. n_embd_v_gqa, nm,
  9456. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa),
  9457. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*i));
  9458. view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  9459. n_embd_v_gqa, nm,
  9460. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa),
  9461. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*id));
  9462. } else {
  9463. view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  9464. nm, n_embd_v_gqa,
  9465. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  9466. ggml_row_size(kv_self.v_l[il]->type, i));
  9467. view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  9468. nm, n_embd_v_gqa,
  9469. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  9470. ggml_row_size(kv_self.v_l[il]->type, id));
  9471. }
  9472. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  9473. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  9474. }
  9475. i += nm - 1;
  9476. }
  9477. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  9478. return gf;
  9479. }
  9480. struct ggml_tensor * build_inp_pos() {
  9481. lctx.inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  9482. cb(lctx.inp_pos, "inp_pos", -1);
  9483. ggml_set_input(lctx.inp_pos);
  9484. return lctx.inp_pos;
  9485. }
  9486. struct ggml_tensor * build_rope_factors(int il) {
  9487. // choose long/short freq factors based on the context size
  9488. const auto n_ctx_pre_seq = cparams.n_ctx / cparams.n_seq_max;
  9489. if (model.layers[il].rope_freqs != nullptr) {
  9490. return model.layers[il].rope_freqs;
  9491. }
  9492. if (n_ctx_pre_seq > hparams.n_ctx_orig_yarn) {
  9493. return model.layers[il].rope_long;
  9494. }
  9495. return model.layers[il].rope_short;
  9496. }
  9497. struct ggml_tensor * build_inp_out_ids() {
  9498. lctx.inp_out_ids = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_outputs);
  9499. cb(lctx.inp_out_ids, "inp_out_ids", -1);
  9500. ggml_set_input(lctx.inp_out_ids);
  9501. return lctx.inp_out_ids;
  9502. }
  9503. struct ggml_tensor * build_inp_KQ_mask(bool causal = true) {
  9504. lctx.inp_KQ_mask = causal
  9505. ? ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD))
  9506. : ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  9507. cb(lctx.inp_KQ_mask, "KQ_mask", -1);
  9508. ggml_set_input(lctx.inp_KQ_mask);
  9509. return flash_attn ? ggml_cast(ctx0, lctx.inp_KQ_mask, GGML_TYPE_F16) : lctx.inp_KQ_mask;
  9510. }
  9511. struct ggml_tensor * build_inp_KQ_mask_swa(bool causal = true) {
  9512. GGML_ASSERT(hparams.n_swa > 0);
  9513. lctx.inp_KQ_mask_swa = causal
  9514. ? ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD))
  9515. : ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  9516. cb(lctx.inp_KQ_mask_swa, "KQ_mask_swa", -1);
  9517. ggml_set_input(lctx.inp_KQ_mask_swa);
  9518. return flash_attn ? ggml_cast(ctx0, lctx.inp_KQ_mask_swa, GGML_TYPE_F16) : lctx.inp_KQ_mask_swa;
  9519. }
  9520. struct ggml_tensor * build_inp_mean() {
  9521. lctx.inp_mean = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  9522. cb(lctx.inp_mean, "inp_mean", -1);
  9523. ggml_set_input(lctx.inp_mean);
  9524. return lctx.inp_mean;
  9525. }
  9526. struct ggml_tensor * build_inp_cls() {
  9527. lctx.inp_cls = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  9528. cb(lctx.inp_cls, "inp_cls", -1);
  9529. ggml_set_input(lctx.inp_cls);
  9530. return lctx.inp_cls;
  9531. }
  9532. struct ggml_tensor * build_inp_s_copy() {
  9533. lctx.inp_s_copy = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_kv);
  9534. cb(lctx.inp_s_copy, "inp_s_copy", -1);
  9535. ggml_set_input(lctx.inp_s_copy);
  9536. return lctx.inp_s_copy;
  9537. }
  9538. struct ggml_tensor * build_inp_s_mask() {
  9539. lctx.inp_s_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_kv);
  9540. cb(lctx.inp_s_mask, "inp_s_mask", -1);
  9541. ggml_set_input(lctx.inp_s_mask);
  9542. return lctx.inp_s_mask;
  9543. }
  9544. struct ggml_cgraph * append_pooling(struct ggml_cgraph * gf) {
  9545. // find result_norm tensor for input
  9546. struct ggml_tensor * inp = nullptr;
  9547. for (int i = ggml_graph_n_nodes(gf) - 1; i >= 0; --i) {
  9548. inp = ggml_graph_node(gf, i);
  9549. if (strcmp(inp->name, "result_norm") == 0 || strcmp(inp->name, "result_embd") == 0) {
  9550. break;
  9551. } else {
  9552. inp = nullptr;
  9553. }
  9554. }
  9555. GGML_ASSERT(inp != nullptr && "missing result_norm/result_embd tensor");
  9556. struct ggml_tensor * cur;
  9557. switch (pooling_type) {
  9558. case LLAMA_POOLING_TYPE_NONE:
  9559. {
  9560. cur = inp;
  9561. } break;
  9562. case LLAMA_POOLING_TYPE_MEAN:
  9563. {
  9564. struct ggml_tensor * inp_mean = build_inp_mean();
  9565. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, inp)), inp_mean);
  9566. } break;
  9567. case LLAMA_POOLING_TYPE_CLS:
  9568. case LLAMA_POOLING_TYPE_LAST:
  9569. {
  9570. struct ggml_tensor * inp_cls = build_inp_cls();
  9571. cur = ggml_get_rows(ctx0, inp, inp_cls);
  9572. } break;
  9573. case LLAMA_POOLING_TYPE_RANK:
  9574. {
  9575. struct ggml_tensor * inp_cls = build_inp_cls();
  9576. inp = ggml_get_rows(ctx0, inp, inp_cls);
  9577. // classification head
  9578. // https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/roberta/modeling_roberta.py#L1566
  9579. GGML_ASSERT(model.cls != nullptr);
  9580. GGML_ASSERT(model.cls_b != nullptr);
  9581. cur = ggml_add (ctx0, ggml_mul_mat(ctx0, model.cls, inp), model.cls_b);
  9582. cur = ggml_tanh(ctx0, cur);
  9583. // some models don't have `cls_out`, for example: https://huggingface.co/jinaai/jina-reranker-v1-tiny-en
  9584. // https://huggingface.co/jinaai/jina-reranker-v1-tiny-en/blob/cb5347e43979c3084a890e3f99491952603ae1b7/modeling_bert.py#L884-L896
  9585. if (model.cls_out) {
  9586. GGML_ASSERT(model.cls_out_b != nullptr);
  9587. cur = ggml_add (ctx0, ggml_mul_mat(ctx0, model.cls_out, cur), model.cls_out_b);
  9588. }
  9589. } break;
  9590. default:
  9591. {
  9592. GGML_ABORT("unknown pooling type");
  9593. }
  9594. }
  9595. cb(cur, "result_embd_pooled", -1);
  9596. ggml_build_forward_expand(gf, cur);
  9597. return gf;
  9598. }
  9599. struct ggml_tensor * llm_build_pos_bucket(bool causal) {
  9600. if (causal) {
  9601. lctx.inp_pos_bucket = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  9602. } else {
  9603. lctx.inp_pos_bucket = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_tokens);
  9604. }
  9605. ggml_set_input(lctx.inp_pos_bucket);
  9606. cb(lctx.inp_pos_bucket, "pos_bucket", -1);
  9607. return lctx.inp_pos_bucket;
  9608. }
  9609. struct ggml_tensor * llm_build_pos_bias(struct ggml_tensor * pos_bucket, struct ggml_tensor * attn_rel_b) {
  9610. struct ggml_tensor * pos_bucket_1d = ggml_view_1d(ctx0, pos_bucket, pos_bucket->ne[0] * pos_bucket->ne[1], 0);
  9611. cb(pos_bucket_1d, "pos_bucket_1d", -1);
  9612. struct ggml_tensor * pos_bias = ggml_get_rows(ctx0, attn_rel_b, pos_bucket_1d);
  9613. cb(pos_bias, "pos_bias", -1);
  9614. 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);
  9615. cb(pos_bias, "pos_bias", -1);
  9616. pos_bias = ggml_permute(ctx0, pos_bias, 2, 0, 1, 3);
  9617. cb(pos_bias, "pos_bias", -1);
  9618. pos_bias = ggml_cont(ctx0, pos_bias);
  9619. cb(pos_bias, "pos_bias", -1);
  9620. return pos_bias;
  9621. }
  9622. struct ggml_tensor * llm_build_inp_embd_enc() {
  9623. const int64_t n_embd = hparams.n_embd;
  9624. lctx.inp_embd_enc = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, n_outputs_enc);
  9625. ggml_set_input(lctx.inp_embd_enc);
  9626. cb(lctx.inp_embd_enc, "embd_enc", -1);
  9627. return lctx.inp_embd_enc;
  9628. }
  9629. struct ggml_tensor * llm_build_inp_KQ_mask_cross() {
  9630. lctx.inp_KQ_mask_cross = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_outputs_enc, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  9631. ggml_set_input(lctx.inp_KQ_mask_cross);
  9632. cb(lctx.inp_KQ_mask_cross, "KQ_mask_cross", -1);
  9633. return lctx.inp_KQ_mask_cross;
  9634. }
  9635. struct ggml_cgraph * build_llama() {
  9636. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9637. // mutable variable, needed during the last layer of the computation to skip unused tokens
  9638. int32_t n_tokens = this->n_tokens;
  9639. const int64_t n_embd_head = hparams.n_embd_head_v;
  9640. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9641. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9642. struct ggml_tensor * cur;
  9643. struct ggml_tensor * inpL;
  9644. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  9645. // inp_pos - contains the positions
  9646. struct ggml_tensor * inp_pos = build_inp_pos();
  9647. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9648. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9649. const float kq_scale = hparams.f_attention_scale == 0.0f ? 1.0f/sqrtf(float(n_embd_head)) : hparams.f_attention_scale;
  9650. for (int il = 0; il < n_layer; ++il) {
  9651. struct ggml_tensor * inpSA = inpL;
  9652. // norm
  9653. cur = llm_build_norm(ctx0, inpL, hparams,
  9654. model.layers[il].attn_norm, NULL,
  9655. LLM_NORM_RMS, cb, il);
  9656. cb(cur, "attn_norm", il);
  9657. // self-attention
  9658. {
  9659. // rope freq factors for llama3; may return nullptr for llama2 and other models
  9660. struct ggml_tensor * rope_factors = build_rope_factors(il);
  9661. // compute Q and K and RoPE them
  9662. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9663. cb(Qcur, "Qcur", il);
  9664. if (model.layers[il].bq) {
  9665. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9666. cb(Qcur, "Qcur", il);
  9667. }
  9668. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9669. cb(Kcur, "Kcur", il);
  9670. if (model.layers[il].bk) {
  9671. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9672. cb(Kcur, "Kcur", il);
  9673. }
  9674. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9675. cb(Vcur, "Vcur", il);
  9676. if (model.layers[il].bv) {
  9677. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9678. cb(Vcur, "Vcur", il);
  9679. }
  9680. Qcur = ggml_rope_ext(
  9681. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  9682. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9683. ext_factor, attn_factor, beta_fast, beta_slow
  9684. );
  9685. cb(Qcur, "Qcur", il);
  9686. Kcur = ggml_rope_ext(
  9687. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  9688. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9689. ext_factor, attn_factor, beta_fast, beta_slow
  9690. );
  9691. cb(Kcur, "Kcur", il);
  9692. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9693. model.layers[il].wo, model.layers[il].bo,
  9694. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  9695. }
  9696. if (il == n_layer - 1) {
  9697. // skip computing output for unused tokens
  9698. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9699. n_tokens = n_outputs;
  9700. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9701. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9702. }
  9703. // For Granite architecture
  9704. if (hparams.f_residual_scale) {
  9705. cur = ggml_scale(ctx0, cur, hparams.f_residual_scale);
  9706. }
  9707. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9708. cb(ffn_inp, "ffn_inp", il);
  9709. // feed-forward network
  9710. if (model.layers[il].ffn_gate_inp == nullptr) {
  9711. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9712. model.layers[il].ffn_norm, NULL,
  9713. LLM_NORM_RMS, cb, il);
  9714. cb(cur, "ffn_norm", il);
  9715. cur = llm_build_ffn(ctx0, lctx, cur,
  9716. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9717. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  9718. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9719. NULL,
  9720. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9721. cb(cur, "ffn_out", il);
  9722. } else {
  9723. // MoE branch
  9724. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9725. model.layers[il].ffn_norm, NULL,
  9726. LLM_NORM_RMS, cb, il);
  9727. cb(cur, "ffn_norm", il);
  9728. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  9729. model.layers[il].ffn_gate_inp,
  9730. model.layers[il].ffn_up_exps,
  9731. model.layers[il].ffn_gate_exps,
  9732. model.layers[il].ffn_down_exps,
  9733. n_expert, n_expert_used,
  9734. LLM_FFN_SILU, true,
  9735. false, 0.0,
  9736. cb, il);
  9737. cb(cur, "ffn_moe_out", il);
  9738. }
  9739. // For Granite architecture
  9740. if (hparams.f_residual_scale) {
  9741. cur = ggml_scale(ctx0, cur, hparams.f_residual_scale);
  9742. }
  9743. cur = ggml_add(ctx0, cur, ffn_inp);
  9744. cb(cur, "ffn_out", il);
  9745. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9746. cb(cur, "l_out", il);
  9747. // input for next layer
  9748. inpL = cur;
  9749. }
  9750. cur = inpL;
  9751. cur = llm_build_norm(ctx0, cur, hparams,
  9752. model.output_norm, NULL,
  9753. LLM_NORM_RMS, cb, -1);
  9754. cb(cur, "result_norm", -1);
  9755. // lm_head
  9756. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9757. // For Granite architecture
  9758. if (hparams.f_logit_scale) {
  9759. cur = ggml_scale(ctx0, cur, 1.0f / hparams.f_logit_scale);
  9760. }
  9761. cb(cur, "result_output", -1);
  9762. ggml_build_forward_expand(gf, cur);
  9763. return gf;
  9764. }
  9765. struct ggml_cgraph * build_mllama() {
  9766. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9767. // mutable variable, needed during the last layer of the computation to skip unused tokens
  9768. int32_t n_tokens = this->n_tokens;
  9769. const int64_t n_embd_head = hparams.n_embd_head_v;
  9770. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9771. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9772. struct ggml_tensor * cur;
  9773. struct ggml_tensor * inpL;
  9774. struct ggml_tensor * inpCAS;
  9775. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  9776. inpCAS = llm_build_inp_cross_attn_state(ctx0, lctx, hparams, cb);
  9777. // inp_pos - contains the positions
  9778. struct ggml_tensor * inp_pos = build_inp_pos();
  9779. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9780. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9781. for (int il = 0; il < n_layer; ++il) {
  9782. struct ggml_tensor * inpSA = inpL;
  9783. // norm
  9784. cur = llm_build_norm(ctx0, inpL, hparams,
  9785. model.layers[il].attn_norm, NULL,
  9786. LLM_NORM_RMS, cb, il);
  9787. cb(cur, "attn_norm", il);
  9788. if (hparams.cross_attention_layers(il)) {
  9789. if (!ubatch.embd && !cparams.cross_attn) {
  9790. continue;
  9791. }
  9792. // cross attention layer
  9793. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].cross_attn_q_proj, cur);
  9794. cb(Qcur, "Qcur", il);
  9795. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9796. cb(Qcur, "Qcur", il);
  9797. Qcur = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 0, 2, 1, 3));
  9798. cb(Qcur, "Qcur", il);
  9799. Qcur = llm_build_norm(ctx0, Qcur, hparams, model.layers[il].cross_attn_q_norm, NULL, LLM_NORM_RMS, cb, il);
  9800. cb(Qcur, "Qcur", il);
  9801. struct ggml_tensor * Kcur, * Vcur;
  9802. if (ubatch.embd) {
  9803. Kcur = ggml_mul_mat(ctx0, model.layers[il].cross_attn_k_proj, inpCAS);
  9804. cb(Kcur, "Kcur", il);
  9805. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, 6404);
  9806. cb(Kcur, "Kcur", il);
  9807. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  9808. cb(Kcur, "Kcur", il);
  9809. Kcur = llm_build_norm(ctx0, Kcur, hparams, model.layers[il].cross_attn_k_norm, NULL, LLM_NORM_RMS, cb, il);
  9810. cb(Kcur, "Kcur", il);
  9811. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, kv_self.k_l[il]));
  9812. Vcur = ggml_mul_mat(ctx0, model.layers[il].cross_attn_v_proj, inpCAS);
  9813. cb(Vcur, "Vcur", il);
  9814. Vcur = ggml_reshape_3d(ctx0, Vcur, n_embd_head, n_head_kv, 6404);
  9815. cb(Vcur, "Vcur", il);
  9816. Vcur = ggml_permute(ctx0, Vcur, 0, 2, 1, 3);
  9817. cb(Vcur, "Vcur", il);
  9818. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, kv_self.v_l[il]));
  9819. } else {
  9820. Kcur = ggml_view_tensor(ctx0, kv_self.k_l[il]);
  9821. cb(Kcur, "Kcur (view)", il);
  9822. Vcur = ggml_view_tensor(ctx0, kv_self.v_l[il]);
  9823. cb(Vcur, "Vcur (view)", il);
  9824. }
  9825. struct ggml_tensor * kq = ggml_mul_mat(ctx0, Kcur, Qcur);
  9826. cb(kq, "kq", il);
  9827. // TODO: apply causal masks
  9828. 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);
  9829. cb(kq_soft_max, "kq_soft_max", il);
  9830. Vcur = ggml_cont(ctx0, ggml_transpose(ctx0, Vcur));
  9831. cb(Vcur, "Vcur", il);
  9832. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, Vcur, kq_soft_max);
  9833. cb(kqv, "kqv", il);
  9834. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  9835. cb(kqv_merged, "kqv_merged", il);
  9836. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_head_v*n_head, n_tokens);
  9837. cb(cur, "kqv_merged_cont", il);
  9838. cur = ggml_mul_mat(ctx0, model.layers[il].cross_attn_o_proj, cur);
  9839. cb(cur, "cur", il);
  9840. // TODO: do this in place once?
  9841. cur = ggml_mul(ctx0, cur, ggml_tanh(ctx0, model.layers[il].cross_attn_attn_gate));
  9842. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9843. cb(ffn_inp, "ffn_inp", il);
  9844. // feed-forward network
  9845. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9846. model.layers[il].ffn_norm, NULL,
  9847. LLM_NORM_RMS, cb, il);
  9848. cb(cur, "ffn_norm", il);
  9849. cur = llm_build_ffn(ctx0, lctx, cur,
  9850. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9851. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  9852. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9853. NULL,
  9854. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9855. cb(cur, "ffn_out", il);
  9856. // TODO: do this inplace once?
  9857. cur = ggml_add_inplace(ctx0, ggml_mul_inplace(ctx0, cur, ggml_tanh(ctx0, model.layers[il].cross_attn_mlp_gate)), ffn_inp);
  9858. cb(cur, "ffn_out", il);
  9859. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9860. cb(cur, "l_out", il);
  9861. // input for next layer
  9862. inpL = cur;
  9863. } else {
  9864. // self attention layer
  9865. // rope freq factors for llama3; may return nullptr for llama2 and other models
  9866. struct ggml_tensor * rope_factors = build_rope_factors(il);
  9867. // compute Q and K and RoPE them
  9868. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9869. cb(Qcur, "Qcur", il);
  9870. if (model.layers[il].bq) {
  9871. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9872. cb(Qcur, "Qcur", il);
  9873. }
  9874. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9875. cb(Kcur, "Kcur", il);
  9876. if (model.layers[il].bk) {
  9877. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9878. cb(Kcur, "Kcur", il);
  9879. }
  9880. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9881. cb(Vcur, "Vcur", il);
  9882. if (model.layers[il].bv) {
  9883. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9884. cb(Vcur, "Vcur", il);
  9885. }
  9886. Qcur = ggml_rope_ext(
  9887. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  9888. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9889. ext_factor, attn_factor, beta_fast, beta_slow
  9890. );
  9891. cb(Qcur, "Qcur", il);
  9892. Kcur = ggml_rope_ext(
  9893. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  9894. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9895. ext_factor, attn_factor, beta_fast, beta_slow
  9896. );
  9897. cb(Kcur, "Kcur", il);
  9898. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9899. model.layers[il].wo, model.layers[il].bo,
  9900. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9901. if (il == n_layer - 1) {
  9902. // skip computing output for unused tokens
  9903. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9904. n_tokens = n_outputs;
  9905. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9906. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9907. }
  9908. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9909. cb(ffn_inp, "ffn_inp", il);
  9910. // feed-forward network
  9911. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9912. model.layers[il].ffn_norm, NULL,
  9913. LLM_NORM_RMS, cb, il);
  9914. cb(cur, "ffn_norm", il);
  9915. cur = llm_build_ffn(ctx0, lctx, cur,
  9916. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9917. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  9918. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9919. NULL,
  9920. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9921. cb(cur, "ffn_out", il);
  9922. cur = ggml_add(ctx0, cur, ffn_inp);
  9923. cb(cur, "ffn_out", il);
  9924. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9925. cb(cur, "l_out", il);
  9926. // input for next layer
  9927. inpL = cur;
  9928. }
  9929. }
  9930. cur = inpL;
  9931. cur = llm_build_norm(ctx0, cur, hparams,
  9932. model.output_norm, NULL,
  9933. LLM_NORM_RMS, cb, -1);
  9934. cb(cur, "result_norm", -1);
  9935. // lm_head
  9936. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9937. cb(cur, "result_output", -1);
  9938. ggml_build_forward_expand(gf, cur);
  9939. return gf;
  9940. }
  9941. struct ggml_cgraph * build_baichuan() {
  9942. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9943. const int64_t n_embd_head = hparams.n_embd_head_v;
  9944. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9945. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9946. struct ggml_tensor * cur;
  9947. struct ggml_tensor * inpL;
  9948. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  9949. // inp_pos - contains the positions
  9950. struct ggml_tensor * inp_pos = model.type == MODEL_7B ? build_inp_pos() : nullptr;
  9951. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9952. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9953. for (int il = 0; il < n_layer; ++il) {
  9954. struct ggml_tensor * inpSA = inpL;
  9955. cur = llm_build_norm(ctx0, inpL, hparams,
  9956. model.layers[il].attn_norm, NULL,
  9957. LLM_NORM_RMS, cb, il);
  9958. cb(cur, "attn_norm", il);
  9959. // self-attention
  9960. {
  9961. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9962. cb(Qcur, "Qcur", il);
  9963. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9964. cb(Kcur, "Kcur", il);
  9965. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9966. cb(Vcur, "Vcur", il);
  9967. switch (model.type) {
  9968. case MODEL_7B:
  9969. Qcur = ggml_rope_ext(
  9970. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9971. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9972. ext_factor, attn_factor, beta_fast, beta_slow
  9973. );
  9974. Kcur = ggml_rope_ext(
  9975. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9976. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9977. ext_factor, attn_factor, beta_fast, beta_slow
  9978. );
  9979. break;
  9980. case MODEL_13B:
  9981. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  9982. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  9983. break;
  9984. default:
  9985. GGML_ABORT("fatal error");
  9986. }
  9987. cb(Qcur, "Qcur", il);
  9988. cb(Kcur, "Kcur", il);
  9989. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9990. model.layers[il].wo, NULL,
  9991. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9992. }
  9993. if (il == n_layer - 1) {
  9994. // skip computing output for unused tokens
  9995. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9996. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9997. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9998. }
  9999. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10000. cb(ffn_inp, "ffn_inp", il);
  10001. // feed-forward network
  10002. {
  10003. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10004. model.layers[il].ffn_norm, NULL,
  10005. LLM_NORM_RMS, cb, il);
  10006. cb(cur, "ffn_norm", il);
  10007. cur = llm_build_ffn(ctx0, lctx, cur,
  10008. model.layers[il].ffn_up, NULL, NULL,
  10009. model.layers[il].ffn_gate, NULL, NULL,
  10010. model.layers[il].ffn_down, NULL, NULL,
  10011. NULL,
  10012. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10013. cb(cur, "ffn_out", il);
  10014. }
  10015. cur = ggml_add(ctx0, cur, ffn_inp);
  10016. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10017. cb(cur, "l_out", il);
  10018. // input for next layer
  10019. inpL = cur;
  10020. }
  10021. cur = inpL;
  10022. cur = llm_build_norm(ctx0, cur, hparams,
  10023. model.output_norm, NULL,
  10024. LLM_NORM_RMS, cb, -1);
  10025. cb(cur, "result_norm", -1);
  10026. // lm_head
  10027. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10028. cb(cur, "result_output", -1);
  10029. ggml_build_forward_expand(gf, cur);
  10030. return gf;
  10031. }
  10032. struct ggml_cgraph * build_xverse() {
  10033. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10034. const int64_t n_embd_head = hparams.n_embd_head_v;
  10035. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10036. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10037. struct ggml_tensor * cur;
  10038. struct ggml_tensor * inpL;
  10039. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10040. // inp_pos - contains the positions
  10041. struct ggml_tensor * inp_pos = build_inp_pos();
  10042. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10043. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10044. for (int il = 0; il < n_layer; ++il) {
  10045. struct ggml_tensor * inpSA = inpL;
  10046. cur = llm_build_norm(ctx0, inpL, hparams,
  10047. model.layers[il].attn_norm, NULL,
  10048. LLM_NORM_RMS, cb, il);
  10049. cb(cur, "attn_norm", il);
  10050. // self-attention
  10051. {
  10052. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10053. cb(Qcur, "Qcur", il);
  10054. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10055. cb(Kcur, "Kcur", il);
  10056. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10057. cb(Vcur, "Vcur", il);
  10058. Qcur = ggml_rope_ext(
  10059. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10060. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10061. ext_factor, attn_factor, beta_fast, beta_slow
  10062. );
  10063. cb(Qcur, "Qcur", il);
  10064. Kcur = ggml_rope_ext(
  10065. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10066. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10067. ext_factor, attn_factor, beta_fast, beta_slow
  10068. );
  10069. cb(Kcur, "Kcur", il);
  10070. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10071. model.layers[il].wo, NULL,
  10072. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10073. }
  10074. if (il == n_layer - 1) {
  10075. // skip computing output for unused tokens
  10076. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10077. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10078. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10079. }
  10080. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10081. cb(ffn_inp, "ffn_inp", il);
  10082. // feed-forward network
  10083. {
  10084. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10085. model.layers[il].ffn_norm, NULL,
  10086. LLM_NORM_RMS, cb, il);
  10087. cb(cur, "ffn_norm", il);
  10088. cur = llm_build_ffn(ctx0, lctx, cur,
  10089. model.layers[il].ffn_up, NULL, NULL,
  10090. model.layers[il].ffn_gate, NULL, NULL,
  10091. model.layers[il].ffn_down, NULL, NULL,
  10092. NULL,
  10093. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10094. cb(cur, "ffn_out", il);
  10095. }
  10096. cur = ggml_add(ctx0, cur, ffn_inp);
  10097. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10098. cb(cur, "l_out", il);
  10099. // input for next layer
  10100. inpL = cur;
  10101. }
  10102. cur = inpL;
  10103. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, NULL, LLM_NORM_RMS, cb, -1);
  10104. cb(cur, "result_norm", -1);
  10105. // lm_head
  10106. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10107. cb(cur, "result_output", -1);
  10108. ggml_build_forward_expand(gf, cur);
  10109. return gf;
  10110. }
  10111. struct ggml_cgraph * build_falcon() {
  10112. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10113. const int64_t n_embd_head = hparams.n_embd_head_v;
  10114. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10115. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10116. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10117. struct ggml_tensor * cur;
  10118. struct ggml_tensor * inpL;
  10119. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10120. // inp_pos - contains the positions
  10121. struct ggml_tensor * inp_pos = build_inp_pos();
  10122. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10123. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10124. for (int il = 0; il < n_layer; ++il) {
  10125. struct ggml_tensor * attn_norm;
  10126. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  10127. model.layers[il].attn_norm,
  10128. model.layers[il].attn_norm_b,
  10129. LLM_NORM, cb, il);
  10130. cb(attn_norm, "attn_norm", il);
  10131. // self-attention
  10132. {
  10133. if (model.layers[il].attn_norm_2) {
  10134. // Falcon-40B
  10135. cur = llm_build_norm(ctx0, inpL, hparams,
  10136. model.layers[il].attn_norm_2,
  10137. model.layers[il].attn_norm_2_b,
  10138. LLM_NORM, cb, il);
  10139. cb(cur, "attn_norm_2", il);
  10140. } else {
  10141. cur = attn_norm;
  10142. }
  10143. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10144. cb(cur, "wqkv", il);
  10145. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10146. 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)));
  10147. 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)));
  10148. cb(Qcur, "Qcur", il);
  10149. cb(Kcur, "Kcur", il);
  10150. cb(Vcur, "Vcur", il);
  10151. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10152. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10153. // using mode = 2 for neox mode
  10154. Qcur = ggml_rope_ext(
  10155. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  10156. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  10157. );
  10158. cb(Qcur, "Qcur", il);
  10159. Kcur = ggml_rope_ext(
  10160. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  10161. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  10162. );
  10163. cb(Kcur, "Kcur", il);
  10164. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10165. model.layers[il].wo, NULL,
  10166. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10167. }
  10168. if (il == n_layer - 1) {
  10169. // skip computing output for unused tokens
  10170. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10171. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10172. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10173. attn_norm = ggml_get_rows(ctx0, attn_norm, inp_out_ids);
  10174. }
  10175. struct ggml_tensor * ffn_inp = cur;
  10176. // feed forward
  10177. {
  10178. cur = llm_build_ffn(ctx0, lctx, attn_norm, // !! use the attn norm, not the result
  10179. model.layers[il].ffn_up, NULL, NULL,
  10180. NULL, NULL, NULL,
  10181. model.layers[il].ffn_down, NULL, NULL,
  10182. NULL,
  10183. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10184. cb(cur, "ffn_out", il);
  10185. }
  10186. cur = ggml_add(ctx0, cur, ffn_inp);
  10187. cur = ggml_add(ctx0, cur, inpL);
  10188. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10189. cb(cur, "l_out", il);
  10190. // input for next layer
  10191. inpL = cur;
  10192. }
  10193. cur = inpL;
  10194. // norm
  10195. cur = llm_build_norm(ctx0, cur, hparams,
  10196. model.output_norm,
  10197. model.output_norm_b,
  10198. LLM_NORM, cb, -1);
  10199. cb(cur, "result_norm", -1);
  10200. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10201. cb(cur, "result_output", -1);
  10202. ggml_build_forward_expand(gf, cur);
  10203. return gf;
  10204. }
  10205. struct ggml_cgraph * build_grok() {
  10206. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10207. // mutable variable, needed during the last layer of the computation to skip unused tokens
  10208. int32_t n_tokens = this->n_tokens;
  10209. const int64_t n_embd_head = hparams.n_embd_head_v;
  10210. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10211. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10212. struct ggml_tensor * cur;
  10213. struct ggml_tensor * inpL;
  10214. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10215. // multiply by embedding_multiplier_scale of 78.38367176906169
  10216. inpL = ggml_scale(ctx0, inpL, 78.38367176906169f);
  10217. // inp_pos - contains the positions
  10218. struct ggml_tensor * inp_pos = build_inp_pos();
  10219. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10220. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10221. for (int il = 0; il < n_layer; ++il) {
  10222. struct ggml_tensor * inpSA = inpL;
  10223. // norm
  10224. cur = llm_build_norm(ctx0, inpL, hparams,
  10225. model.layers[il].attn_norm, NULL,
  10226. LLM_NORM_RMS, cb, il);
  10227. cb(cur, "attn_norm", il);
  10228. // self-attention
  10229. {
  10230. // compute Q and K and RoPE them
  10231. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10232. cb(Qcur, "Qcur", il);
  10233. if (model.layers[il].bq) {
  10234. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10235. cb(Qcur, "Qcur", il);
  10236. }
  10237. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10238. cb(Kcur, "Kcur", il);
  10239. if (model.layers[il].bk) {
  10240. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10241. cb(Kcur, "Kcur", il);
  10242. }
  10243. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10244. cb(Vcur, "Vcur", il);
  10245. if (model.layers[il].bv) {
  10246. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  10247. cb(Vcur, "Vcur", il);
  10248. }
  10249. Qcur = ggml_rope_ext(
  10250. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10251. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10252. ext_factor, attn_factor, beta_fast, beta_slow
  10253. );
  10254. cb(Qcur, "Qcur", il);
  10255. Kcur = ggml_rope_ext(
  10256. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10257. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10258. ext_factor, attn_factor, beta_fast, beta_slow
  10259. );
  10260. cb(Kcur, "Kcur", il);
  10261. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10262. model.layers[il].wo, model.layers[il].bo,
  10263. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  10264. }
  10265. if (il == n_layer - 1) {
  10266. // skip computing output for unused tokens
  10267. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10268. n_tokens = n_outputs;
  10269. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10270. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10271. }
  10272. // Grok
  10273. // if attn_out_norm is present then apply it before adding the input
  10274. if (model.layers[il].attn_out_norm) {
  10275. cur = llm_build_norm(ctx0, cur, hparams,
  10276. model.layers[il].attn_out_norm, NULL,
  10277. LLM_NORM_RMS, cb, il);
  10278. cb(cur, "attn_out_norm", il);
  10279. }
  10280. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10281. cb(ffn_inp, "ffn_inp", il);
  10282. // feed-forward network
  10283. // MoE branch
  10284. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10285. model.layers[il].ffn_norm, NULL,
  10286. LLM_NORM_RMS, cb, il);
  10287. cb(cur, "ffn_norm", il);
  10288. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  10289. model.layers[il].ffn_gate_inp,
  10290. model.layers[il].ffn_up_exps,
  10291. model.layers[il].ffn_gate_exps,
  10292. model.layers[il].ffn_down_exps,
  10293. n_expert, n_expert_used,
  10294. LLM_FFN_GELU, true,
  10295. false, 0.0,
  10296. cb, il);
  10297. cb(cur, "ffn_moe_out", il);
  10298. // Grok
  10299. // if layer_out_norm is present then apply it before adding the input
  10300. // Idea: maybe ffn_out_norm is a better name
  10301. if (model.layers[il].layer_out_norm) {
  10302. cur = llm_build_norm(ctx0, cur, hparams,
  10303. model.layers[il].layer_out_norm, NULL,
  10304. LLM_NORM_RMS, cb, il);
  10305. cb(cur, "layer_out_norm", il);
  10306. }
  10307. cur = ggml_add(ctx0, cur, ffn_inp);
  10308. cb(cur, "ffn_out", il);
  10309. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10310. cb(cur, "l_out", il);
  10311. // input for next layer
  10312. inpL = cur;
  10313. }
  10314. cur = inpL;
  10315. cur = llm_build_norm(ctx0, cur, hparams,
  10316. model.output_norm, NULL,
  10317. LLM_NORM_RMS, cb, -1);
  10318. cb(cur, "result_norm", -1);
  10319. // lm_head
  10320. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10321. // Grok
  10322. // multiply logits by output_multiplier_scale of 0.5773502691896257
  10323. cur = ggml_scale(ctx0, cur, 0.5773502691896257f);
  10324. cb(cur, "result_output", -1);
  10325. ggml_build_forward_expand(gf, cur);
  10326. return gf;
  10327. }
  10328. struct ggml_cgraph * build_dbrx() {
  10329. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10330. // mutable variable, needed during the last layer of the computation to skip unused tokens
  10331. int32_t n_tokens = this->n_tokens;
  10332. const int64_t n_embd_head = hparams.n_embd_head_v;
  10333. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10334. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10335. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10336. struct ggml_tensor * cur;
  10337. struct ggml_tensor * inpL;
  10338. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10339. // inp_pos - contains the positions
  10340. struct ggml_tensor * inp_pos = build_inp_pos();
  10341. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10342. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10343. for (int il = 0; il < n_layer; ++il) {
  10344. struct ggml_tensor * inpSA = inpL;
  10345. // norm
  10346. cur = llm_build_norm(ctx0, inpL, hparams,
  10347. model.layers[il].attn_norm, NULL,
  10348. LLM_NORM, cb, il);
  10349. cb(cur, "attn_norm", il);
  10350. // self-attention
  10351. {
  10352. struct ggml_tensor * Qcur = nullptr;
  10353. struct ggml_tensor * Kcur = nullptr;
  10354. struct ggml_tensor * Vcur = nullptr;
  10355. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10356. cb(cur, "wqkv", il);
  10357. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  10358. cb(cur, "wqkv_clamped", il);
  10359. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10360. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  10361. 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)));
  10362. cb(Qcur, "Qcur", il);
  10363. cb(Kcur, "Kcur", il);
  10364. cb(Vcur, "Vcur", il);
  10365. Qcur = ggml_rope_ext(
  10366. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10367. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10368. ext_factor, attn_factor, beta_fast, beta_slow
  10369. );
  10370. cb(Qcur, "Qcur", il);
  10371. Kcur = ggml_rope_ext(
  10372. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10373. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10374. ext_factor, attn_factor, beta_fast, beta_slow
  10375. );
  10376. cb(Kcur, "Kcur", il);
  10377. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10378. model.layers[il].wo, NULL,
  10379. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10380. }
  10381. if (il == n_layer - 1) {
  10382. // skip computing output for unused tokens
  10383. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10384. n_tokens = n_outputs;
  10385. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10386. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10387. }
  10388. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10389. cb(ffn_inp, "ffn_inp", il);
  10390. // feed-forward network
  10391. // MoE branch
  10392. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10393. model.layers[il].attn_out_norm, NULL,
  10394. LLM_NORM, cb, il);
  10395. cb(cur, "attn_out_norm", il);
  10396. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  10397. model.layers[il].ffn_gate_inp,
  10398. model.layers[il].ffn_up_exps,
  10399. model.layers[il].ffn_gate_exps,
  10400. model.layers[il].ffn_down_exps,
  10401. n_expert, n_expert_used,
  10402. LLM_FFN_SILU, true,
  10403. false, 0.0,
  10404. cb, il);
  10405. cb(cur, "ffn_moe_out", il);
  10406. cur = ggml_add(ctx0, cur, ffn_inp);
  10407. cb(cur, "ffn_out", il);
  10408. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10409. cb(cur, "l_out", il);
  10410. // input for next layer
  10411. inpL = cur;
  10412. }
  10413. cur = inpL;
  10414. cur = llm_build_norm(ctx0, cur, hparams,
  10415. model.output_norm, NULL,
  10416. LLM_NORM, cb, -1);
  10417. cb(cur, "result_norm", -1);
  10418. // lm_head
  10419. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10420. cb(cur, "result_output", -1);
  10421. ggml_build_forward_expand(gf, cur);
  10422. return gf;
  10423. }
  10424. struct ggml_cgraph * build_starcoder() {
  10425. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10426. const int64_t n_embd_head = hparams.n_embd_head_v;
  10427. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10428. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10429. struct ggml_tensor * cur;
  10430. struct ggml_tensor * inpL;
  10431. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10432. // inp_pos - contains the positions
  10433. struct ggml_tensor * inp_pos = build_inp_pos();
  10434. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10435. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10436. struct ggml_tensor * pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  10437. cb(pos, "pos_embd", -1);
  10438. inpL = ggml_add(ctx0, inpL, pos);
  10439. cb(inpL, "inpL", -1);
  10440. for (int il = 0; il < n_layer; ++il) {
  10441. cur = llm_build_norm(ctx0, inpL, hparams,
  10442. model.layers[il].attn_norm,
  10443. model.layers[il].attn_norm_b,
  10444. LLM_NORM, cb, il);
  10445. cb(cur, "attn_norm", il);
  10446. // self-attention
  10447. {
  10448. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10449. cb(cur, "wqkv", il);
  10450. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10451. cb(cur, "bqkv", il);
  10452. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10453. 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)));
  10454. 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)));
  10455. cb(Qcur, "Qcur", il);
  10456. cb(Kcur, "Kcur", il);
  10457. cb(Vcur, "Vcur", il);
  10458. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10459. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10460. model.layers[il].wo, model.layers[il].bo,
  10461. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10462. }
  10463. if (il == n_layer - 1) {
  10464. // skip computing output for unused tokens
  10465. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10466. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10467. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10468. }
  10469. // add the input
  10470. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10471. cb(ffn_inp, "ffn_inp", il);
  10472. // FF
  10473. {
  10474. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10475. model.layers[il].ffn_norm,
  10476. model.layers[il].ffn_norm_b,
  10477. LLM_NORM, cb, il);
  10478. cb(cur, "ffn_norm", il);
  10479. cur = llm_build_ffn(ctx0, lctx, cur,
  10480. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10481. NULL, NULL, NULL,
  10482. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10483. NULL,
  10484. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10485. cb(cur, "ffn_out", il);
  10486. }
  10487. cur = ggml_add(ctx0, cur, ffn_inp);
  10488. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10489. cb(cur, "l_out", il);
  10490. // input for next layer
  10491. inpL = cur;
  10492. }
  10493. cur = llm_build_norm(ctx0, inpL, hparams,
  10494. model.output_norm,
  10495. model.output_norm_b,
  10496. LLM_NORM, cb, -1);
  10497. cb(cur, "result_norm", -1);
  10498. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10499. cb(cur, "result_output", -1);
  10500. ggml_build_forward_expand(gf, cur);
  10501. return gf;
  10502. }
  10503. struct ggml_cgraph * build_refact() {
  10504. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10505. const int64_t n_embd_head = hparams.n_embd_head_v;
  10506. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10507. struct ggml_tensor * cur;
  10508. struct ggml_tensor * inpL;
  10509. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10510. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10511. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10512. for (int il = 0; il < n_layer; ++il) {
  10513. struct ggml_tensor * inpSA = inpL;
  10514. cur = llm_build_norm(ctx0, inpL, hparams,
  10515. model.layers[il].attn_norm, NULL,
  10516. LLM_NORM_RMS, cb, il);
  10517. cb(cur, "attn_norm", il);
  10518. // self-attention
  10519. {
  10520. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10521. cb(Qcur, "Qcur", il);
  10522. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10523. cb(Kcur, "Kcur", il);
  10524. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10525. cb(Vcur, "Vcur", il);
  10526. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10527. cb(Kcur, "Kcur", il);
  10528. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10529. cb(Qcur, "Qcur", il);
  10530. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10531. model.layers[il].wo, NULL,
  10532. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10533. }
  10534. if (il == n_layer - 1) {
  10535. // skip computing output for unused tokens
  10536. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10537. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10538. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10539. }
  10540. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10541. cb(ffn_inp, "ffn_inp", il);
  10542. // feed-forward network
  10543. {
  10544. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10545. model.layers[il].ffn_norm, NULL,
  10546. LLM_NORM_RMS, cb, il);
  10547. cb(cur, "ffn_norm", il);
  10548. cur = llm_build_ffn(ctx0, lctx, cur,
  10549. model.layers[il].ffn_up, NULL, NULL,
  10550. model.layers[il].ffn_gate, NULL, NULL,
  10551. model.layers[il].ffn_down, NULL, NULL,
  10552. NULL,
  10553. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10554. cb(cur, "ffn_out", il);
  10555. }
  10556. cur = ggml_add(ctx0, cur, ffn_inp);
  10557. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10558. cb(cur, "l_out", il);
  10559. // input for next layer
  10560. inpL = cur;
  10561. }
  10562. cur = inpL;
  10563. cur = llm_build_norm(ctx0, cur, hparams,
  10564. model.output_norm, NULL,
  10565. LLM_NORM_RMS, cb, -1);
  10566. cb(cur, "result_norm", -1);
  10567. // lm_head
  10568. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10569. cb(cur, "result_output", -1);
  10570. ggml_build_forward_expand(gf, cur);
  10571. return gf;
  10572. }
  10573. struct ggml_cgraph * build_bert() {
  10574. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10575. const int64_t n_embd_head = hparams.n_embd_head_v;
  10576. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10577. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10578. struct ggml_tensor * cur;
  10579. struct ggml_tensor * inpL;
  10580. struct ggml_tensor * inp_pos = nullptr;
  10581. if (model.arch != LLM_ARCH_JINA_BERT_V2) {
  10582. inp_pos = build_inp_pos();
  10583. }
  10584. // construct input embeddings (token, type, position)
  10585. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10586. // token types are hardcoded to zero ("Sentence A")
  10587. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  10588. inpL = ggml_add(ctx0, inpL, type_row0);
  10589. if (model.arch == LLM_ARCH_BERT) {
  10590. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  10591. }
  10592. cb(inpL, "inp_embd", -1);
  10593. // embed layer norm
  10594. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  10595. cb(inpL, "inp_norm", -1);
  10596. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10597. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(false);
  10598. // iterate layers
  10599. for (int il = 0; il < n_layer; ++il) {
  10600. struct ggml_tensor * cur = inpL;
  10601. struct ggml_tensor * Qcur;
  10602. struct ggml_tensor * Kcur;
  10603. struct ggml_tensor * Vcur;
  10604. // self-attention
  10605. if (model.arch == LLM_ARCH_BERT || model.arch == LLM_ARCH_JINA_BERT_V2) {
  10606. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  10607. cb(Qcur, "Qcur", il);
  10608. if (model.layers[il].attn_q_norm) {
  10609. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  10610. model.layers[il].attn_q_norm,
  10611. model.layers[il].attn_q_norm_b,
  10612. LLM_NORM, cb, il);
  10613. }
  10614. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  10615. cb(Kcur, "Kcur", il);
  10616. if (model.layers[il].attn_k_norm) {
  10617. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  10618. model.layers[il].attn_k_norm,
  10619. model.layers[il].attn_k_norm_b,
  10620. LLM_NORM, cb, il);
  10621. }
  10622. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  10623. cb(Vcur, "Vcur", il);
  10624. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10625. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10626. } else {
  10627. // compute Q and K and RoPE them
  10628. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10629. cb(cur, "wqkv", il);
  10630. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10631. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  10632. 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)));
  10633. cb(Qcur, "Qcur", il);
  10634. cb(Kcur, "Kcur", il);
  10635. cb(Vcur, "Vcur", il);
  10636. Qcur = ggml_rope_ext(
  10637. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10638. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10639. ext_factor, attn_factor, beta_fast, beta_slow
  10640. );
  10641. cb(Qcur, "Qcur", il);
  10642. Kcur = ggml_rope_ext(
  10643. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10644. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10645. ext_factor, attn_factor, beta_fast, beta_slow
  10646. );
  10647. cb(Kcur, "Kcur", il);
  10648. }
  10649. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  10650. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  10651. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  10652. cb(kq, "kq", il);
  10653. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask, 1.0f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  10654. cb(kq, "kq_soft_max_ext", il);
  10655. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  10656. cb(v, "v", il);
  10657. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  10658. cb(kqv, "kqv", il);
  10659. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  10660. cb(kqv_merged, "kqv_merged", il);
  10661. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  10662. cb(cur, "kqv_merged_cont", il);
  10663. ggml_build_forward_expand(gf, cur);
  10664. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  10665. if (model.layers[il].bo) {
  10666. cb(cur, "kqv_wo", il);
  10667. }
  10668. if (model.layers[il].bo) {
  10669. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  10670. }
  10671. cb(cur, "kqv_out", il);
  10672. if (il == n_layer - 1 && pooling_type == LLAMA_POOLING_TYPE_NONE) {
  10673. // skip computing output for unused tokens
  10674. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10675. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10676. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10677. }
  10678. // re-add the layer input
  10679. cur = ggml_add(ctx0, cur, inpL);
  10680. // attention layer norm
  10681. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  10682. if (model.layers[il].attn_norm_2 != nullptr) {
  10683. cur = ggml_add(ctx0, cur, inpL); // re-add the layer input
  10684. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_norm_2, model.layers[il].attn_norm_2_b, LLM_NORM, cb, il);
  10685. }
  10686. struct ggml_tensor * ffn_inp = cur;
  10687. cb(ffn_inp, "ffn_inp", il);
  10688. // feed-forward network
  10689. if (model.arch == LLM_ARCH_BERT) {
  10690. cur = llm_build_ffn(ctx0, lctx, cur,
  10691. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10692. NULL, NULL, NULL,
  10693. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10694. NULL,
  10695. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10696. } else if (model.arch == LLM_ARCH_JINA_BERT_V2) {
  10697. cur = llm_build_ffn(ctx0, lctx, cur,
  10698. model.layers[il].ffn_up, NULL, NULL,
  10699. model.layers[il].ffn_gate, NULL, NULL,
  10700. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10701. NULL,
  10702. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  10703. } else {
  10704. cur = llm_build_ffn(ctx0, lctx, cur,
  10705. model.layers[il].ffn_up, NULL, NULL,
  10706. model.layers[il].ffn_gate, NULL, NULL,
  10707. model.layers[il].ffn_down, NULL, NULL,
  10708. NULL,
  10709. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10710. }
  10711. cb(cur, "ffn_out", il);
  10712. // attentions bypass the intermediate layer
  10713. cur = ggml_add(ctx0, cur, ffn_inp);
  10714. // output layer norm
  10715. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  10716. // input for next layer
  10717. inpL = cur;
  10718. }
  10719. cur = inpL;
  10720. cb(cur, "result_embd", -1);
  10721. ggml_build_forward_expand(gf, cur);
  10722. return gf;
  10723. }
  10724. struct ggml_cgraph * build_bloom() {
  10725. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10726. const int64_t n_embd_head = hparams.n_embd_head_v;
  10727. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10728. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10729. struct ggml_tensor * cur;
  10730. struct ggml_tensor * inpL;
  10731. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10732. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10733. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10734. inpL = llm_build_norm(ctx0, inpL, hparams,
  10735. model.tok_norm,
  10736. model.tok_norm_b,
  10737. LLM_NORM, cb, -1);
  10738. cb(inpL, "inp_norm", -1);
  10739. for (int il = 0; il < n_layer; ++il) {
  10740. cur = llm_build_norm(ctx0, inpL, hparams,
  10741. model.layers[il].attn_norm,
  10742. model.layers[il].attn_norm_b,
  10743. LLM_NORM, cb, il);
  10744. cb(cur, "attn_norm", il);
  10745. // self-attention
  10746. {
  10747. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10748. cb(cur, "wqkv", il);
  10749. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10750. cb(cur, "bqkv", il);
  10751. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10752. 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)));
  10753. 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)));
  10754. cb(Qcur, "Qcur", il);
  10755. cb(Kcur, "Kcur", il);
  10756. cb(Vcur, "Vcur", il);
  10757. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10758. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10759. model.layers[il].wo, model.layers[il].bo,
  10760. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10761. }
  10762. if (il == n_layer - 1) {
  10763. // skip computing output for unused tokens
  10764. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10765. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10766. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10767. }
  10768. // Add the input
  10769. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10770. cb(ffn_inp, "ffn_inp", il);
  10771. // FF
  10772. {
  10773. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10774. model.layers[il].ffn_norm,
  10775. model.layers[il].ffn_norm_b,
  10776. LLM_NORM, cb, il);
  10777. cb(cur, "ffn_norm", il);
  10778. cur = llm_build_ffn(ctx0, lctx, cur,
  10779. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10780. NULL, NULL, NULL,
  10781. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10782. NULL,
  10783. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10784. cb(cur, "ffn_out", il);
  10785. }
  10786. cur = ggml_add(ctx0, cur, ffn_inp);
  10787. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10788. cb(cur, "l_out", il);
  10789. // input for next layer
  10790. inpL = cur;
  10791. }
  10792. cur = llm_build_norm(ctx0, inpL, hparams,
  10793. model.output_norm,
  10794. model.output_norm_b,
  10795. LLM_NORM, cb, -1);
  10796. cb(cur, "result_norm", -1);
  10797. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10798. cb(cur, "result_output", -1);
  10799. ggml_build_forward_expand(gf, cur);
  10800. return gf;
  10801. }
  10802. struct ggml_cgraph * build_mpt() {
  10803. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10804. const int64_t n_embd_head = hparams.n_embd_head_v;
  10805. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10806. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10807. struct ggml_tensor * cur;
  10808. struct ggml_tensor * pos;
  10809. struct ggml_tensor * inpL;
  10810. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10811. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10812. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10813. if (model.pos_embd) {
  10814. // inp_pos - contains the positions
  10815. struct ggml_tensor * inp_pos = build_inp_pos();
  10816. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  10817. cb(pos, "pos_embd", -1);
  10818. inpL = ggml_add(ctx0, inpL, pos);
  10819. cb(inpL, "inpL", -1);
  10820. }
  10821. for (int il = 0; il < n_layer; ++il) {
  10822. struct ggml_tensor * attn_norm;
  10823. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  10824. model.layers[il].attn_norm,
  10825. model.layers[il].attn_norm_b,
  10826. LLM_NORM, cb, il);
  10827. cb(attn_norm, "attn_norm", il);
  10828. // self-attention
  10829. {
  10830. cur = attn_norm;
  10831. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10832. cb(cur, "wqkv", il);
  10833. if (model.layers[il].bqkv){
  10834. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10835. cb(cur, "bqkv", il);
  10836. }
  10837. if (hparams.f_clamp_kqv > 0.0f) {
  10838. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  10839. cb(cur, "wqkv_clamped", il);
  10840. }
  10841. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10842. 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)));
  10843. 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)));
  10844. cb(Qcur, "Qcur", il);
  10845. cb(Kcur, "Kcur", il);
  10846. cb(Vcur, "Vcur", il);
  10847. // Q/K Layernorm
  10848. if (model.layers[il].attn_q_norm) {
  10849. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  10850. model.layers[il].attn_q_norm,
  10851. model.layers[il].attn_q_norm_b,
  10852. LLM_NORM, cb, il);
  10853. cb(Qcur, "Qcur", il);
  10854. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  10855. model.layers[il].attn_k_norm,
  10856. model.layers[il].attn_k_norm_b,
  10857. LLM_NORM, cb, il);
  10858. cb(Kcur, "Kcur", il);
  10859. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10860. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10861. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10862. model.layers[il].wo, model.layers[il].bo,
  10863. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10864. } else {
  10865. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10866. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10867. model.layers[il].wo, model.layers[il].bo,
  10868. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10869. }
  10870. }
  10871. if (il == n_layer - 1) {
  10872. // skip computing output for unused tokens
  10873. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10874. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10875. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10876. }
  10877. // Add the input
  10878. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10879. cb(ffn_inp, "ffn_inp", il);
  10880. // feed forward
  10881. {
  10882. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10883. model.layers[il].ffn_norm,
  10884. model.layers[il].ffn_norm_b,
  10885. LLM_NORM, cb, il);
  10886. cb(cur, "ffn_norm", il);
  10887. cur = llm_build_ffn(ctx0, lctx, cur,
  10888. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10889. NULL, NULL, NULL,
  10890. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10891. model.layers[il].ffn_act,
  10892. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10893. cb(cur, "ffn_out", il);
  10894. }
  10895. cur = ggml_add(ctx0, cur, ffn_inp);
  10896. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10897. cb(cur, "l_out", il);
  10898. // input for next layer
  10899. inpL = cur;
  10900. }
  10901. cur = inpL;
  10902. cur = llm_build_norm(ctx0, cur, hparams,
  10903. model.output_norm,
  10904. model.output_norm_b,
  10905. LLM_NORM, cb, -1);
  10906. cb(cur, "result_norm", -1);
  10907. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10908. cb(cur, "result_output", -1);
  10909. ggml_build_forward_expand(gf, cur);
  10910. return gf;
  10911. }
  10912. struct ggml_cgraph * build_stablelm() {
  10913. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  10914. const int64_t n_embd_head = hparams.n_embd_head_v;
  10915. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10916. struct ggml_tensor * cur;
  10917. struct ggml_tensor * inpL;
  10918. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  10919. // inp_pos - contains the positions
  10920. struct ggml_tensor * inp_pos = build_inp_pos();
  10921. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10922. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10923. for (int il = 0; il < n_layer; ++il) {
  10924. // norm
  10925. cur = llm_build_norm(ctx0, inpL, hparams,
  10926. model.layers[il].attn_norm,
  10927. model.layers[il].attn_norm_b,
  10928. LLM_NORM, cb, il);
  10929. cb(cur, "attn_norm", il);
  10930. struct ggml_tensor * inpSA = cur;
  10931. // self-attention
  10932. {
  10933. // compute Q and K and RoPE them
  10934. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10935. cb(Qcur, "Qcur", il);
  10936. if (model.layers[il].bq) {
  10937. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10938. cb(Qcur, "Qcur", il);
  10939. }
  10940. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10941. cb(Kcur, "Kcur", il);
  10942. if (model.layers[il].bk) {
  10943. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10944. cb(Kcur, "Kcur", il);
  10945. }
  10946. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10947. cb(Vcur, "Vcur", il);
  10948. if (model.layers[il].bv) {
  10949. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  10950. cb(Vcur, "Vcur", il);
  10951. }
  10952. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10953. cb(Qcur, "Qcur", il);
  10954. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10955. cb(Kcur, "Kcur", il);
  10956. if (model.layers[il].attn_q_norm) {
  10957. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  10958. model.layers[il].attn_q_norm,
  10959. NULL,
  10960. LLM_NORM, cb, il);
  10961. cb(Qcur, "Qcur", il);
  10962. }
  10963. if (model.layers[il].attn_k_norm) {
  10964. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  10965. model.layers[il].attn_k_norm,
  10966. NULL,
  10967. LLM_NORM, cb, il);
  10968. cb(Kcur, "Kcur", il);
  10969. }
  10970. Qcur = ggml_rope_ext(
  10971. ctx0, Qcur, inp_pos, nullptr,
  10972. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10973. ext_factor, attn_factor, beta_fast, beta_slow
  10974. );
  10975. cb(Qcur, "Qcur", il);
  10976. Kcur = ggml_rope_ext(
  10977. ctx0, Kcur, inp_pos, nullptr,
  10978. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10979. ext_factor, attn_factor, beta_fast, beta_slow
  10980. );
  10981. cb(Kcur, "Kcur", il);
  10982. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10983. model.layers[il].wo, NULL,
  10984. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10985. }
  10986. if (il == n_layer - 1) {
  10987. // skip computing output for unused tokens
  10988. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10989. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10990. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10991. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10992. }
  10993. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10994. cb(ffn_inp, "ffn_inp", il);
  10995. // feed-forward network
  10996. {
  10997. if (model.layers[il].ffn_norm) {
  10998. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10999. model.layers[il].ffn_norm,
  11000. model.layers[il].ffn_norm_b,
  11001. LLM_NORM, cb, il);
  11002. cb(cur, "ffn_norm", il);
  11003. } else {
  11004. // parallel residual
  11005. cur = inpSA;
  11006. }
  11007. cur = llm_build_ffn(ctx0, lctx, cur,
  11008. model.layers[il].ffn_up, NULL, NULL,
  11009. model.layers[il].ffn_gate, NULL, NULL,
  11010. model.layers[il].ffn_down, NULL, NULL,
  11011. NULL,
  11012. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11013. cb(cur, "ffn_out", il);
  11014. }
  11015. cur = ggml_add(ctx0, cur, ffn_inp);
  11016. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11017. cb(cur, "l_out", il);
  11018. // input for next layer
  11019. inpL = cur;
  11020. }
  11021. cur = inpL;
  11022. cur = llm_build_norm(ctx0, cur, hparams,
  11023. model.output_norm,
  11024. model.output_norm_b,
  11025. LLM_NORM, cb, -1);
  11026. cb(cur, "result_norm", -1);
  11027. // lm_head
  11028. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11029. cb(cur, "result_output", -1);
  11030. ggml_build_forward_expand(gf, cur);
  11031. return gf;
  11032. }
  11033. struct ggml_cgraph * build_qwen() {
  11034. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11035. const int64_t n_embd_head = hparams.n_embd_head_v;
  11036. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11037. struct ggml_tensor * cur;
  11038. struct ggml_tensor * inpL;
  11039. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11040. // inp_pos - contains the positions
  11041. struct ggml_tensor * inp_pos = build_inp_pos();
  11042. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11043. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11044. for (int il = 0; il < n_layer; ++il) {
  11045. struct ggml_tensor * inpSA = inpL;
  11046. cur = llm_build_norm(ctx0, inpL, hparams,
  11047. model.layers[il].attn_norm, NULL,
  11048. LLM_NORM_RMS, cb, il);
  11049. cb(cur, "attn_norm", il);
  11050. // self-attention
  11051. {
  11052. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  11053. cb(cur, "wqkv", il);
  11054. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  11055. cb(cur, "bqkv", il);
  11056. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  11057. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  11058. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  11059. cb(Qcur, "Qcur", il);
  11060. cb(Kcur, "Kcur", il);
  11061. cb(Vcur, "Vcur", il);
  11062. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11063. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  11064. // using mode = 2 for neox mode
  11065. Qcur = ggml_rope_ext(
  11066. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  11067. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  11068. );
  11069. cb(Qcur, "Qcur", il);
  11070. Kcur = ggml_rope_ext(
  11071. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  11072. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  11073. );
  11074. cb(Kcur, "Kcur", il);
  11075. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11076. model.layers[il].wo, NULL,
  11077. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11078. }
  11079. if (il == n_layer - 1) {
  11080. // skip computing output for unused tokens
  11081. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11082. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11083. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11084. }
  11085. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11086. cb(ffn_inp, "ffn_inp", il);
  11087. // feed-forward forward
  11088. {
  11089. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11090. model.layers[il].ffn_norm, NULL,
  11091. LLM_NORM_RMS, cb, il);
  11092. cb(cur, "ffn_norm", il);
  11093. cur = llm_build_ffn(ctx0, lctx, cur,
  11094. model.layers[il].ffn_up, NULL, NULL,
  11095. model.layers[il].ffn_gate, NULL, NULL,
  11096. model.layers[il].ffn_down, NULL, NULL,
  11097. NULL,
  11098. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11099. cb(cur, "ffn_out", il);
  11100. }
  11101. cur = ggml_add(ctx0, cur, ffn_inp);
  11102. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11103. cb(cur, "l_out", il);
  11104. // input for next layer
  11105. inpL = cur;
  11106. }
  11107. cur = inpL;
  11108. cur = llm_build_norm(ctx0, cur, hparams,
  11109. model.output_norm, NULL,
  11110. LLM_NORM_RMS, cb, -1);
  11111. cb(cur, "result_norm", -1);
  11112. // lm_head
  11113. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11114. cb(cur, "result_output", -1);
  11115. ggml_build_forward_expand(gf, cur);
  11116. return gf;
  11117. }
  11118. struct ggml_cgraph * build_qwen2() {
  11119. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11120. const int64_t n_embd_head = hparams.n_embd_head_v;
  11121. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11122. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11123. struct ggml_tensor * cur;
  11124. struct ggml_tensor * inpL;
  11125. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11126. // inp_pos - contains the positions
  11127. struct ggml_tensor * inp_pos = build_inp_pos();
  11128. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11129. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11130. for (int il = 0; il < n_layer; ++il) {
  11131. struct ggml_tensor * inpSA = inpL;
  11132. // norm
  11133. cur = llm_build_norm(ctx0, inpL, hparams,
  11134. model.layers[il].attn_norm, NULL,
  11135. LLM_NORM_RMS, cb, il);
  11136. cb(cur, "attn_norm", il);
  11137. // self-attention
  11138. {
  11139. // compute Q and K and RoPE them
  11140. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11141. cb(Qcur, "Qcur", il);
  11142. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  11143. cb(Qcur, "Qcur", il);
  11144. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11145. cb(Kcur, "Kcur", il);
  11146. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  11147. cb(Kcur, "Kcur", il);
  11148. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11149. cb(Vcur, "Vcur", il);
  11150. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11151. cb(Vcur, "Vcur", il);
  11152. Qcur = ggml_rope_ext(
  11153. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11154. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11155. ext_factor, attn_factor, beta_fast, beta_slow
  11156. );
  11157. cb(Qcur, "Qcur", il);
  11158. Kcur = ggml_rope_ext(
  11159. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11160. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11161. ext_factor, attn_factor, beta_fast, beta_slow
  11162. );
  11163. cb(Kcur, "Kcur", il);
  11164. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11165. model.layers[il].wo, model.layers[il].bo,
  11166. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11167. }
  11168. if (il == n_layer - 1) {
  11169. // skip computing output for unused tokens
  11170. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11171. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11172. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11173. }
  11174. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11175. cb(ffn_inp, "ffn_inp", il);
  11176. // feed-forward network
  11177. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11178. model.layers[il].ffn_norm, NULL,
  11179. LLM_NORM_RMS, cb, il);
  11180. cb(cur, "ffn_norm", il);
  11181. cur = llm_build_ffn(ctx0, lctx, cur,
  11182. model.layers[il].ffn_up, NULL, NULL,
  11183. model.layers[il].ffn_gate, NULL, NULL,
  11184. model.layers[il].ffn_down, NULL, NULL,
  11185. NULL,
  11186. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11187. cb(cur, "ffn_out", il);
  11188. cur = ggml_add(ctx0, cur, ffn_inp);
  11189. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11190. cb(cur, "l_out", il);
  11191. // input for next layer
  11192. inpL = cur;
  11193. }
  11194. cur = inpL;
  11195. cur = llm_build_norm(ctx0, cur, hparams,
  11196. model.output_norm, NULL,
  11197. LLM_NORM_RMS, cb, -1);
  11198. cb(cur, "result_norm", -1);
  11199. // lm_head
  11200. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11201. cb(cur, "result_output", -1);
  11202. ggml_build_forward_expand(gf, cur);
  11203. return gf;
  11204. }
  11205. struct ggml_cgraph * build_qwen2vl() {
  11206. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11207. const int64_t n_embd_head = hparams.n_embd_head_v;
  11208. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11209. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11210. struct ggml_tensor * cur;
  11211. struct ggml_tensor * inpL;
  11212. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11213. // inp_pos - contains the positions
  11214. lctx.inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens * 4);
  11215. cb(lctx.inp_pos, "inp_pos", -1);
  11216. ggml_set_input(lctx.inp_pos);
  11217. struct ggml_tensor * inp_pos = lctx.inp_pos;
  11218. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11219. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11220. int sections[4];
  11221. std::copy(std::begin(hparams.rope_sections), std::begin(hparams.rope_sections) + 4, sections);
  11222. for (int il = 0; il < n_layer; ++il) {
  11223. struct ggml_tensor * inpSA = inpL;
  11224. // norm
  11225. cur = llm_build_norm(ctx0, inpL, hparams,
  11226. model.layers[il].attn_norm, NULL,
  11227. LLM_NORM_RMS, cb, il);
  11228. cb(cur, "attn_norm", il);
  11229. // self-attention
  11230. {
  11231. // compute Q and K and RoPE them
  11232. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11233. cb(Qcur, "Qcur", il);
  11234. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  11235. cb(Qcur, "Qcur", il);
  11236. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11237. cb(Kcur, "Kcur", il);
  11238. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  11239. cb(Kcur, "Kcur", il);
  11240. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11241. cb(Vcur, "Vcur", il);
  11242. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11243. cb(Vcur, "Vcur", il);
  11244. Qcur = ggml_rope_multi(
  11245. ctx0,
  11246. ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11247. n_rot, sections, rope_type, n_ctx_orig, freq_base, freq_scale,
  11248. ext_factor, attn_factor, beta_fast, beta_slow
  11249. );
  11250. cb(Qcur, "Qcur", il);
  11251. Kcur = ggml_rope_multi(
  11252. ctx0,
  11253. ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11254. n_rot, sections, rope_type, n_ctx_orig, freq_base, freq_scale,
  11255. ext_factor, attn_factor, beta_fast, beta_slow
  11256. );
  11257. cb(Kcur, "Kcur", il);
  11258. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11259. model.layers[il].wo, model.layers[il].bo,
  11260. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11261. }
  11262. if (il == n_layer - 1) {
  11263. // skip computing output for unused tokens
  11264. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11265. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11266. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11267. }
  11268. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11269. cb(ffn_inp, "ffn_inp", il);
  11270. // feed-forward network
  11271. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11272. model.layers[il].ffn_norm, NULL,
  11273. LLM_NORM_RMS, cb, il);
  11274. cb(cur, "ffn_norm", il);
  11275. cur = llm_build_ffn(ctx0, lctx, cur,
  11276. model.layers[il].ffn_up, NULL, NULL,
  11277. model.layers[il].ffn_gate, NULL, NULL,
  11278. model.layers[il].ffn_down, NULL, NULL,
  11279. NULL,
  11280. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11281. cb(cur, "ffn_out", il);
  11282. cur = ggml_add(ctx0, cur, ffn_inp);
  11283. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11284. cb(cur, "l_out", il);
  11285. // input for next layer
  11286. inpL = cur;
  11287. }
  11288. cur = inpL;
  11289. cur = llm_build_norm(ctx0, cur, hparams,
  11290. model.output_norm, NULL,
  11291. LLM_NORM_RMS, cb, -1);
  11292. cb(cur, "result_norm", -1);
  11293. // lm_head
  11294. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11295. cb(cur, "result_output", -1);
  11296. ggml_build_forward_expand(gf, cur);
  11297. return gf;
  11298. }
  11299. struct ggml_cgraph * build_qwen2moe() {
  11300. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11301. // mutable variable, needed during the last layer of the computation to skip unused tokens
  11302. int32_t n_tokens = this->n_tokens;
  11303. const int64_t n_embd_head = hparams.n_embd_head_v;
  11304. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11305. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11306. struct ggml_tensor * cur;
  11307. struct ggml_tensor * inpL;
  11308. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11309. // inp_pos - contains the positions
  11310. struct ggml_tensor * inp_pos = build_inp_pos();
  11311. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11312. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11313. for (int il = 0; il < n_layer; ++il) {
  11314. struct ggml_tensor * inpSA = inpL;
  11315. // norm
  11316. cur = llm_build_norm(ctx0, inpL, hparams,
  11317. model.layers[il].attn_norm, NULL,
  11318. LLM_NORM_RMS, cb, il);
  11319. cb(cur, "attn_norm", il);
  11320. // self_attention
  11321. {
  11322. // compute Q and K and RoPE them
  11323. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11324. cb(Qcur, "Qcur", il);
  11325. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  11326. cb(Qcur, "Qcur", il);
  11327. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11328. cb(Kcur, "Kcur", il);
  11329. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  11330. cb(Kcur, "Kcur", il);
  11331. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11332. cb(Vcur, "Vcur", il);
  11333. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11334. cb(Vcur, "Vcur", il);
  11335. Qcur = ggml_rope_ext(
  11336. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11337. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11338. ext_factor, attn_factor, beta_fast, beta_slow
  11339. );
  11340. cb(Qcur, "Qcur", il);
  11341. Kcur = ggml_rope_ext(
  11342. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11343. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11344. ext_factor, attn_factor, beta_fast, beta_slow
  11345. );
  11346. cb(Kcur, "Kcur", il);
  11347. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11348. model.layers[il].wo, model.layers[il].bo,
  11349. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11350. }
  11351. if (il == n_layer - 1) {
  11352. // skip computing output for unused tokens
  11353. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11354. n_tokens = n_outputs;
  11355. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11356. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11357. }
  11358. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11359. cb(ffn_inp, "ffn_inp", il);
  11360. // MoE branch
  11361. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11362. model.layers[il].ffn_norm, NULL,
  11363. LLM_NORM_RMS, cb, il);
  11364. cb(cur, "ffn_norm", il);
  11365. ggml_tensor * moe_out =
  11366. llm_build_moe_ffn(ctx0, lctx, cur,
  11367. model.layers[il].ffn_gate_inp,
  11368. model.layers[il].ffn_up_exps,
  11369. model.layers[il].ffn_gate_exps,
  11370. model.layers[il].ffn_down_exps,
  11371. n_expert, n_expert_used,
  11372. LLM_FFN_SILU, false,
  11373. false, 0.0,
  11374. cb, il);
  11375. cb(cur, "ffn_moe_out", il);
  11376. // FFN shared expert
  11377. {
  11378. ggml_tensor * cur_gate_inp = llm_build_lora_mm(lctx, ctx0, model.layers[il].ffn_gate_inp_shexp, cur);
  11379. cb(cur_gate_inp, "ffn_shexp_gate_inp", il);
  11380. // sigmoid
  11381. ggml_tensor * cur_gate = ggml_div(ctx0, ggml_silu(ctx0, cur_gate_inp), cur_gate_inp);
  11382. cb(cur_gate, "ffn_shexp_gate", il);
  11383. ggml_tensor * cur_ffn = llm_build_ffn(ctx0, lctx, cur,
  11384. model.layers[il].ffn_up_shexp, NULL, NULL,
  11385. model.layers[il].ffn_gate_shexp, NULL, NULL,
  11386. model.layers[il].ffn_down_shexp, NULL, NULL,
  11387. NULL,
  11388. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11389. cb(cur_ffn, "ffn_shexp", il);
  11390. ggml_tensor * ffn_shexp_out = ggml_mul(ctx0, cur_ffn, cur_gate);
  11391. cb(ffn_shexp_out, "ffn_shexp_out", il);
  11392. moe_out = ggml_add(ctx0, moe_out, ffn_shexp_out);
  11393. cb(moe_out, "ffn_out", il);
  11394. cur = moe_out;
  11395. }
  11396. cur = ggml_add(ctx0, cur, ffn_inp);
  11397. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11398. cb(cur, "l_out", il);
  11399. // input for next layer
  11400. inpL = cur;
  11401. }
  11402. cur = inpL;
  11403. cur = llm_build_norm(ctx0, cur, hparams,
  11404. model.output_norm, NULL,
  11405. LLM_NORM_RMS, cb, -1);
  11406. cb(cur, "result_norm", -1);
  11407. // lm_head
  11408. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11409. cb(cur, "result_output", -1);
  11410. ggml_build_forward_expand(gf, cur);
  11411. return gf;
  11412. }
  11413. struct ggml_cgraph * build_phi2() {
  11414. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11415. const int64_t n_embd_head = hparams.n_embd_head_v;
  11416. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11417. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11418. struct ggml_tensor * cur;
  11419. struct ggml_tensor * attn_norm_output;
  11420. struct ggml_tensor * ffn_output;
  11421. struct ggml_tensor * inpL;
  11422. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11423. // inp_pos - contains the positions
  11424. struct ggml_tensor * inp_pos = build_inp_pos();
  11425. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11426. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11427. for (int il = 0; il < n_layer; ++il) {
  11428. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  11429. model.layers[il].attn_norm,
  11430. model.layers[il].attn_norm_b,
  11431. LLM_NORM, cb, il);
  11432. cb(attn_norm_output, "attn_norm", il);
  11433. // self-attention
  11434. {
  11435. struct ggml_tensor * Qcur = nullptr;
  11436. struct ggml_tensor * Kcur = nullptr;
  11437. struct ggml_tensor * Vcur = nullptr;
  11438. if (model.layers[il].wqkv) {
  11439. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, attn_norm_output);
  11440. cb(cur, "wqkv", il);
  11441. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  11442. cb(cur, "bqkv", il);
  11443. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  11444. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  11445. 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)));
  11446. } else {
  11447. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  11448. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  11449. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  11450. }
  11451. cb(Qcur, "Qcur", il);
  11452. cb(Kcur, "Kcur", il);
  11453. cb(Vcur, "Vcur", il);
  11454. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11455. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  11456. Qcur = ggml_rope_ext(
  11457. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  11458. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  11459. );
  11460. cb(Qcur, "Qcur", il);
  11461. // with phi2, we scale the Q to avoid precision issues
  11462. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  11463. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  11464. cb(Qcur, "Qcur", il);
  11465. Kcur = ggml_rope_ext(
  11466. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  11467. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  11468. );
  11469. cb(Kcur, "Kcur", il);
  11470. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11471. model.layers[il].wo, model.layers[il].bo,
  11472. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  11473. }
  11474. if (il == n_layer - 1) {
  11475. // skip computing output for unused tokens
  11476. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11477. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11478. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11479. attn_norm_output = ggml_get_rows(ctx0, attn_norm_output, inp_out_ids);
  11480. }
  11481. // FF
  11482. {
  11483. ffn_output = llm_build_ffn(ctx0, lctx, attn_norm_output,
  11484. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  11485. NULL, NULL, NULL,
  11486. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  11487. NULL,
  11488. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  11489. cb(ffn_output, "ffn_out", il);
  11490. }
  11491. cur = ggml_add(ctx0, cur, ffn_output);
  11492. cur = ggml_add(ctx0, cur, inpL);
  11493. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11494. cb(cur, "l_out", il);
  11495. // input for next layer
  11496. inpL = cur;
  11497. }
  11498. cur = llm_build_norm(ctx0, inpL, hparams,
  11499. model.output_norm,
  11500. model.output_norm_b,
  11501. LLM_NORM, cb, -1);
  11502. cb(cur, "result_norm", -1);
  11503. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11504. cb(cur, "result_output_no_bias", -1);
  11505. cur = ggml_add(ctx0, cur, model.output_b);
  11506. cb(cur, "result_output", -1);
  11507. ggml_build_forward_expand(gf, cur);
  11508. return gf;
  11509. }
  11510. struct ggml_cgraph * build_phi3() {
  11511. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11512. const int64_t n_embd_head = hparams.n_embd_head_v;
  11513. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11514. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11515. struct ggml_tensor * cur;
  11516. struct ggml_tensor * inpL;
  11517. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11518. // inp_pos - contains the positions
  11519. struct ggml_tensor * inp_pos = build_inp_pos();
  11520. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11521. struct ggml_tensor * KQ_mask_swa = build_inp_KQ_mask_swa();
  11522. for (int il = 0; il < n_layer; ++il) {
  11523. auto residual = inpL;
  11524. // self-attention
  11525. {
  11526. // rope freq factors for 128k context
  11527. struct ggml_tensor * rope_factors = build_rope_factors(il);
  11528. struct ggml_tensor* attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  11529. model.layers[il].attn_norm,
  11530. NULL,
  11531. LLM_NORM_RMS, cb, il);
  11532. cb(attn_norm_output, "attn_norm", il);
  11533. struct ggml_tensor * Qcur = nullptr;
  11534. struct ggml_tensor * Kcur = nullptr;
  11535. struct ggml_tensor * Vcur = nullptr;
  11536. if (model.layers[il].wqkv) {
  11537. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, attn_norm_output);
  11538. cb(cur, "wqkv", il);
  11539. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0 * sizeof(float) * (n_embd)));
  11540. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1 * sizeof(float) * (n_embd)));
  11541. 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)));
  11542. }
  11543. else {
  11544. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  11545. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  11546. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  11547. }
  11548. cb(Qcur, "Qcur", il);
  11549. cb(Kcur, "Kcur", il);
  11550. cb(Vcur, "Vcur", il);
  11551. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11552. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  11553. Qcur = ggml_rope_ext(
  11554. ctx0, Qcur, inp_pos, rope_factors, n_rot, rope_type, n_ctx_orig,
  11555. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  11556. );
  11557. cb(Qcur, "Qcur", il);
  11558. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head)));
  11559. cb(Qcur, "Qcur", il);
  11560. Kcur = ggml_rope_ext(
  11561. ctx0, Kcur, inp_pos, rope_factors, n_rot, rope_type, n_ctx_orig,
  11562. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  11563. );
  11564. cb(Kcur, "Kcur", il);
  11565. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11566. model.layers[il].wo, model.layers[il].bo,
  11567. Kcur, Vcur, Qcur, KQ_mask_swa, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  11568. }
  11569. if (il == n_layer - 1) {
  11570. // skip computing output for unused tokens
  11571. struct ggml_tensor* inp_out_ids = build_inp_out_ids();
  11572. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11573. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  11574. }
  11575. cur = ggml_add(ctx0, cur, residual);
  11576. residual = cur;
  11577. cur = llm_build_norm(ctx0, cur, hparams,
  11578. model.layers[il].ffn_norm, NULL,
  11579. LLM_NORM_RMS, cb, il);
  11580. cb(cur, "ffn_norm", il);
  11581. // FF
  11582. // special-case: the up and gate tensors are merged into a single tensor
  11583. // TOOD: support into llm_build_ffn
  11584. {
  11585. cur = llm_build_ffn(ctx0, lctx, cur,
  11586. model.layers[il].ffn_up, NULL, NULL,
  11587. NULL, NULL, NULL,
  11588. model.layers[il].ffn_down, NULL, NULL,
  11589. NULL,
  11590. LLM_FFN_SWIGLU, LLM_FFN_SEQ, cb, il);
  11591. cb(cur, "ffn_out", il);
  11592. }
  11593. cur = ggml_add(ctx0, residual, cur);
  11594. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11595. cb(cur, "l_out", il);
  11596. // input for next layer
  11597. inpL = cur;
  11598. }
  11599. cur = llm_build_norm(ctx0, inpL, hparams,
  11600. model.output_norm,
  11601. NULL,
  11602. LLM_NORM_RMS, cb, -1);
  11603. cb(cur, "result_norm", -1);
  11604. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11605. cb(cur, "result_output", -1);
  11606. ggml_build_forward_expand(gf, cur);
  11607. return gf;
  11608. }
  11609. struct ggml_cgraph * build_plamo() {
  11610. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  11611. const int64_t n_embd_head = hparams.n_embd_head_v;
  11612. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11613. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11614. struct ggml_tensor * cur;
  11615. struct ggml_tensor * inpL;
  11616. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11617. // inp_pos - contains the positions
  11618. struct ggml_tensor * inp_pos = build_inp_pos();
  11619. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11620. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11621. for (int il = 0; il < n_layer; ++il) {
  11622. // norm
  11623. cur = llm_build_norm(ctx0, inpL, hparams,
  11624. model.layers[il].attn_norm, NULL,
  11625. LLM_NORM_RMS, cb, il);
  11626. cb(cur, "attn_norm", il);
  11627. struct ggml_tensor * attention_norm = cur;
  11628. // self-attention
  11629. {
  11630. // compute Q and K and RoPE them
  11631. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11632. cb(Qcur, "Qcur", il);
  11633. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11634. cb(Kcur, "Kcur", il);
  11635. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11636. cb(Vcur, "Vcur", il);
  11637. Qcur = ggml_rope_ext(
  11638. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos, nullptr,
  11639. n_embd_head, rope_type, n_ctx_orig, freq_base, freq_scale,
  11640. ext_factor, attn_factor, beta_fast, beta_slow);
  11641. cb(Qcur, "Qcur", il);
  11642. Kcur = ggml_rope_ext(
  11643. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos, nullptr,
  11644. n_embd_head, rope_type, n_ctx_orig, freq_base, freq_scale,
  11645. ext_factor, attn_factor, beta_fast, beta_slow);
  11646. cb(Kcur, "Kcur", il);
  11647. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11648. model.layers[il].wo, NULL,
  11649. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11650. }
  11651. struct ggml_tensor * sa_out = cur;
  11652. cur = attention_norm;
  11653. if (il == n_layer - 1) {
  11654. // skip computing output for unused tokens
  11655. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11656. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11657. sa_out = ggml_get_rows(ctx0, sa_out, inp_out_ids);
  11658. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11659. }
  11660. // feed-forward network
  11661. {
  11662. cur = llm_build_ffn(ctx0, lctx, cur,
  11663. model.layers[il].ffn_up, NULL, NULL,
  11664. model.layers[il].ffn_gate, NULL, NULL,
  11665. model.layers[il].ffn_down, NULL, NULL,
  11666. NULL,
  11667. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11668. cb(cur, "ffn_out", il);
  11669. }
  11670. cur = ggml_add(ctx0, cur, sa_out);
  11671. cur = ggml_add(ctx0, cur, inpL);
  11672. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11673. cb(cur, "l_out", il);
  11674. // input for next layer
  11675. inpL = cur;
  11676. }
  11677. cur = inpL;
  11678. cur = llm_build_norm(ctx0, cur, hparams,
  11679. model.output_norm, NULL,
  11680. LLM_NORM_RMS, cb, -1);
  11681. cb(cur, "result_norm", -1);
  11682. // lm_head
  11683. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11684. cb(cur, "result_output", -1);
  11685. ggml_build_forward_expand(gf, cur);
  11686. return gf;
  11687. }
  11688. struct ggml_cgraph * build_gpt2() {
  11689. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11690. const int64_t n_embd_head = hparams.n_embd_head_v;
  11691. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11692. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11693. struct ggml_tensor * cur;
  11694. struct ggml_tensor * pos;
  11695. struct ggml_tensor * inpL;
  11696. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11697. // inp_pos - contains the positions
  11698. struct ggml_tensor * inp_pos = build_inp_pos();
  11699. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11700. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11701. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  11702. cb(pos, "pos_embd", -1);
  11703. inpL = ggml_add(ctx0, inpL, pos);
  11704. cb(inpL, "inpL", -1);
  11705. for (int il = 0; il < n_layer; ++il) {
  11706. cur = llm_build_norm(ctx0, inpL, hparams,
  11707. model.layers[il].attn_norm,
  11708. model.layers[il].attn_norm_b,
  11709. LLM_NORM, cb, il);
  11710. cb(cur, "attn_norm", il);
  11711. // self-attention
  11712. {
  11713. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  11714. cb(cur, "wqkv", il);
  11715. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  11716. cb(cur, "bqkv", il);
  11717. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  11718. 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)));
  11719. 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)));
  11720. cb(Qcur, "Qcur", il);
  11721. cb(Kcur, "Kcur", il);
  11722. cb(Vcur, "Vcur", il);
  11723. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11724. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11725. model.layers[il].wo, model.layers[il].bo,
  11726. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11727. }
  11728. if (il == n_layer - 1) {
  11729. // skip computing output for unused tokens
  11730. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11731. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11732. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11733. }
  11734. // add the input
  11735. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  11736. cb(ffn_inp, "ffn_inp", il);
  11737. // FF
  11738. {
  11739. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11740. model.layers[il].ffn_norm,
  11741. model.layers[il].ffn_norm_b,
  11742. LLM_NORM, cb, il);
  11743. cb(cur, "ffn_norm", il);
  11744. cur = llm_build_ffn(ctx0, lctx, cur,
  11745. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  11746. NULL, NULL, NULL,
  11747. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  11748. NULL,
  11749. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  11750. cb(cur, "ffn_out", il);
  11751. }
  11752. cur = ggml_add(ctx0, cur, ffn_inp);
  11753. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11754. cb(cur, "l_out", il);
  11755. // input for next layer
  11756. inpL = cur;
  11757. }
  11758. cur = llm_build_norm(ctx0, inpL, hparams,
  11759. model.output_norm,
  11760. model.output_norm_b,
  11761. LLM_NORM, cb, -1);
  11762. cb(cur, "result_norm", -1);
  11763. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11764. cb(cur, "result_output", -1);
  11765. ggml_build_forward_expand(gf, cur);
  11766. return gf;
  11767. }
  11768. struct ggml_cgraph * build_codeshell() {
  11769. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11770. const int64_t n_embd_head = hparams.n_embd_head_v;
  11771. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11772. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11773. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11774. struct ggml_tensor * cur;
  11775. struct ggml_tensor * inpL;
  11776. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11777. // inp_pos - contains the positions
  11778. struct ggml_tensor * inp_pos = build_inp_pos();
  11779. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11780. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11781. for (int il = 0; il < n_layer; ++il) {
  11782. cur = llm_build_norm(ctx0, inpL, hparams,
  11783. model.layers[il].attn_norm,
  11784. model.layers[il].attn_norm_b,
  11785. LLM_NORM, cb, il);
  11786. cb(cur, "attn_norm", il);
  11787. // self-attention
  11788. {
  11789. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  11790. cb(cur, "wqkv", il);
  11791. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  11792. cb(cur, "bqkv", il);
  11793. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  11794. 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)));
  11795. 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)));
  11796. cb(tmpq, "tmpq", il);
  11797. cb(tmpk, "tmpk", il);
  11798. cb(Vcur, "Vcur", il);
  11799. struct ggml_tensor * Qcur = ggml_rope_ext(
  11800. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11801. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11802. ext_factor, attn_factor, beta_fast, beta_slow
  11803. );
  11804. cb(Qcur, "Qcur", il);
  11805. struct ggml_tensor * Kcur = ggml_rope_ext(
  11806. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11807. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11808. ext_factor, attn_factor, beta_fast, beta_slow
  11809. );
  11810. cb(Kcur, "Kcur", il);
  11811. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11812. model.layers[il].wo, model.layers[il].bo,
  11813. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11814. }
  11815. if (il == n_layer - 1) {
  11816. // skip computing output for unused tokens
  11817. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11818. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11819. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11820. }
  11821. // add the input
  11822. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  11823. cb(ffn_inp, "ffn_inp", il);
  11824. // FF
  11825. {
  11826. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11827. model.layers[il].ffn_norm,
  11828. model.layers[il].ffn_norm_b,
  11829. LLM_NORM, cb, il);
  11830. cb(cur, "ffn_norm", il);
  11831. cur = llm_build_ffn(ctx0, lctx, cur,
  11832. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  11833. NULL, NULL, NULL,
  11834. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  11835. NULL,
  11836. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  11837. cb(cur, "ffn_out", il);
  11838. }
  11839. cur = ggml_add(ctx0, cur, ffn_inp);
  11840. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11841. cb(cur, "l_out", il);
  11842. // input for next layer
  11843. inpL = cur;
  11844. }
  11845. cur = llm_build_norm(ctx0, inpL, hparams,
  11846. model.output_norm,
  11847. model.output_norm_b,
  11848. LLM_NORM, cb, -1);
  11849. cb(cur, "result_norm", -1);
  11850. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11851. cb(cur, "result_output", -1);
  11852. ggml_build_forward_expand(gf, cur);
  11853. return gf;
  11854. }
  11855. struct ggml_cgraph * build_orion() {
  11856. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11857. const int64_t n_embd_head = hparams.n_embd_head_v;
  11858. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11859. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11860. struct ggml_tensor * cur;
  11861. struct ggml_tensor * inpL;
  11862. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11863. // inp_pos - contains the positions
  11864. struct ggml_tensor * inp_pos = build_inp_pos();
  11865. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11866. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11867. for (int il = 0; il < n_layer; ++il) {
  11868. struct ggml_tensor * inpSA = inpL;
  11869. // norm
  11870. cur = llm_build_norm(ctx0, inpL, hparams,
  11871. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  11872. LLM_NORM, cb, il);
  11873. cb(cur, "attn_norm", il);
  11874. // self-attention
  11875. {
  11876. // compute Q and K and RoPE them
  11877. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11878. cb(Qcur, "Qcur", il);
  11879. // if (model.layers[il].bq) {
  11880. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  11881. // cb(Qcur, "Qcur", il);
  11882. // }
  11883. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11884. cb(Kcur, "Kcur", il);
  11885. // if (model.layers[il].bk) {
  11886. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  11887. // cb(Kcur, "Kcur", il);
  11888. // }
  11889. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11890. cb(Vcur, "Vcur", il);
  11891. // if (model.layers[il].bv) {
  11892. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11893. // cb(Vcur, "Vcur", il);
  11894. // }
  11895. Qcur = ggml_rope_ext(
  11896. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11897. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11898. ext_factor, attn_factor, beta_fast, beta_slow
  11899. );
  11900. cb(Qcur, "Qcur", il);
  11901. Kcur = ggml_rope_ext(
  11902. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11903. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11904. ext_factor, attn_factor, beta_fast, beta_slow
  11905. );
  11906. cb(Kcur, "Kcur", il);
  11907. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11908. model.layers[il].wo, NULL,
  11909. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11910. }
  11911. if (il == n_layer - 1) {
  11912. // skip computing output for unused tokens
  11913. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11914. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11915. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11916. }
  11917. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11918. cb(ffn_inp, "ffn_inp", il);
  11919. // feed-forward network
  11920. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11921. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  11922. LLM_NORM, cb, il);
  11923. cb(cur, "ffn_norm", il);
  11924. cur = llm_build_ffn(ctx0, lctx, cur,
  11925. model.layers[il].ffn_up, NULL, NULL,
  11926. model.layers[il].ffn_gate, NULL, NULL,
  11927. model.layers[il].ffn_down, NULL, NULL,
  11928. NULL,
  11929. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11930. cb(cur, "ffn_out", il);
  11931. cur = ggml_add(ctx0, cur, ffn_inp);
  11932. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11933. cb(cur, "l_out", il);
  11934. // input for next layer
  11935. inpL = cur;
  11936. }
  11937. cur = inpL;
  11938. cur = llm_build_norm(ctx0, cur, hparams,
  11939. model.output_norm, model.output_norm_b,
  11940. LLM_NORM, cb, -1);
  11941. cb(cur, "result_norm", -1);
  11942. // lm_head
  11943. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11944. cb(cur, "result_output", -1);
  11945. ggml_build_forward_expand(gf, cur);
  11946. return gf;
  11947. }
  11948. struct ggml_cgraph * build_internlm2() {
  11949. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11950. const int64_t n_embd_head = hparams.n_embd_head_v;
  11951. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11952. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11953. struct ggml_tensor * cur;
  11954. struct ggml_tensor * inpL;
  11955. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  11956. // inp_pos - contains the positions
  11957. struct ggml_tensor * inp_pos = build_inp_pos();
  11958. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11959. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11960. for (int il = 0; il < n_layer; ++il) {
  11961. struct ggml_tensor * inpSA = inpL;
  11962. // norm
  11963. cur = llm_build_norm(ctx0, inpL, hparams,
  11964. model.layers[il].attn_norm, NULL,
  11965. LLM_NORM_RMS, cb, il);
  11966. cb(cur, "attn_norm", il);
  11967. // self-attention
  11968. {
  11969. // compute Q and K and RoPE them
  11970. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11971. cb(Qcur, "Qcur", il);
  11972. if (model.layers[il].bq) {
  11973. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  11974. cb(Qcur, "Qcur", il);
  11975. }
  11976. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11977. cb(Kcur, "Kcur", il);
  11978. if (model.layers[il].bk) {
  11979. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  11980. cb(Kcur, "Kcur", il);
  11981. }
  11982. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11983. cb(Vcur, "Vcur", il);
  11984. if (model.layers[il].bv) {
  11985. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11986. cb(Vcur, "Vcur", il);
  11987. }
  11988. Qcur = ggml_rope_ext(
  11989. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11990. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11991. ext_factor, attn_factor, beta_fast, beta_slow
  11992. );
  11993. cb(Qcur, "Qcur", il);
  11994. Kcur = ggml_rope_ext(
  11995. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11996. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11997. ext_factor, attn_factor, beta_fast, beta_slow
  11998. );
  11999. cb(Kcur, "Kcur", il);
  12000. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12001. model.layers[il].wo, model.layers[il].bo,
  12002. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12003. }
  12004. if (il == n_layer - 1) {
  12005. // skip computing output for unused tokens
  12006. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12007. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12008. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12009. }
  12010. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12011. cb(ffn_inp, "ffn_inp", il);
  12012. // feed-forward network
  12013. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12014. model.layers[il].ffn_norm, NULL,
  12015. LLM_NORM_RMS, cb, il);
  12016. cb(cur, "ffn_norm", il);
  12017. cur = llm_build_ffn(ctx0, lctx, cur,
  12018. model.layers[il].ffn_up, NULL, NULL,
  12019. model.layers[il].ffn_gate, NULL, NULL,
  12020. model.layers[il].ffn_down, NULL, NULL,
  12021. NULL,
  12022. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12023. cb(cur, "ffn_out", il);
  12024. cur = ggml_add(ctx0, cur, ffn_inp);
  12025. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12026. cb(cur, "l_out", il);
  12027. // input for next layer
  12028. inpL = cur;
  12029. }
  12030. cur = inpL;
  12031. cur = llm_build_norm(ctx0, cur, hparams,
  12032. model.output_norm, NULL,
  12033. LLM_NORM_RMS, cb, -1);
  12034. cb(cur, "result_norm", -1);
  12035. // lm_head
  12036. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12037. cb(cur, "result_output", -1);
  12038. ggml_build_forward_expand(gf, cur);
  12039. return gf;
  12040. }
  12041. struct ggml_cgraph * build_minicpm3() {
  12042. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12043. //TODO: if the model varies, these parameters need to be read from the model
  12044. const int64_t n_embd_base = 256;
  12045. const float scale_embd = 12.0f;
  12046. const float scale_depth = 1.4f;
  12047. const float kq_scale = 1.0f / sqrtf(float(hparams.n_embd_head_k));
  12048. const uint32_t n_embd_head_qk_rope = hparams.n_rot;
  12049. const uint32_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  12050. const uint32_t kv_lora_rank = hparams.n_lora_kv;
  12051. struct ggml_tensor * cur;
  12052. struct ggml_tensor * inpL;
  12053. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12054. // scale the input embeddings
  12055. inpL = ggml_scale(ctx0, inpL, scale_embd);
  12056. cb(inpL, "inp_scaled", -1);
  12057. // inp_pos - contains the positions
  12058. struct ggml_tensor * inp_pos = build_inp_pos();
  12059. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12060. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12061. for (int il = 0; il < n_layer; ++il) {
  12062. struct ggml_tensor * inpSA = inpL;
  12063. struct ggml_tensor * rope_factors = build_rope_factors(il);
  12064. // norm
  12065. cur = llm_build_norm(ctx0, inpL, hparams,
  12066. model.layers[il].attn_norm, NULL,
  12067. LLM_NORM_RMS, cb, il);
  12068. cb(cur, "attn_norm", il);
  12069. // self_attention
  12070. {
  12071. struct ggml_tensor * q = NULL;
  12072. // {n_embd, q_lora_rank} * {n_embd, n_tokens} -> {q_lora_rank, n_tokens}
  12073. q = ggml_mul_mat(ctx0, model.layers[il].wq_a, cur);
  12074. cb(q, "q", il);
  12075. q = llm_build_norm(ctx0, q, hparams,
  12076. model.layers[il].attn_q_a_norm, NULL,
  12077. LLM_NORM_RMS, cb, il);
  12078. cb(q, "q", il);
  12079. // {q_lora_rank, n_head * hparams.n_embd_head_k} * {q_lora_rank, n_tokens} -> {n_head * hparams.n_embd_head_k, n_tokens}
  12080. q = ggml_mul_mat(ctx0, model.layers[il].wq_b, q);
  12081. cb(q, "q", il);
  12082. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  12083. struct ggml_tensor * q_nope = ggml_view_3d(ctx0, q, n_embd_head_qk_nope, n_head, n_tokens,
  12084. ggml_row_size(q->type, hparams.n_embd_head_k),
  12085. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  12086. 0);
  12087. cb(q_nope, "q_nope", il);
  12088. // and {n_head * n_embd_head_qk_rope, n_tokens}
  12089. struct ggml_tensor * q_pe = ggml_view_3d(ctx0, q, n_embd_head_qk_rope, n_head, n_tokens,
  12090. ggml_row_size(q->type, hparams.n_embd_head_k),
  12091. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  12092. ggml_row_size(q->type, n_embd_head_qk_nope));
  12093. cb(q_pe, "q_pe", il);
  12094. // {n_embd, kv_lora_rank + n_embd_head_qk_rope} * {n_embd, n_tokens} -> {kv_lora_rank + n_embd_head_qk_rope, n_tokens}
  12095. struct ggml_tensor * kv_pe_compresseed = ggml_mul_mat(ctx0, model.layers[il].wkv_a_mqa, cur);
  12096. cb(kv_pe_compresseed, "kv_pe_compresseed", il);
  12097. // split into {kv_lora_rank, n_tokens}
  12098. struct ggml_tensor * kv_compressed = ggml_view_2d(ctx0, kv_pe_compresseed, kv_lora_rank, n_tokens,
  12099. kv_pe_compresseed->nb[1],
  12100. 0);
  12101. cb(kv_compressed, "kv_compressed", il);
  12102. // and {n_embd_head_qk_rope, n_tokens}
  12103. struct ggml_tensor * k_pe = ggml_view_3d(ctx0, kv_pe_compresseed, n_embd_head_qk_rope, 1, n_tokens,
  12104. kv_pe_compresseed->nb[1],
  12105. kv_pe_compresseed->nb[1],
  12106. ggml_row_size(kv_pe_compresseed->type, kv_lora_rank));
  12107. cb(k_pe, "k_pe", il);
  12108. kv_compressed = ggml_cont(ctx0, kv_compressed); // TODO: the CUDA backend does not support non-contiguous norm
  12109. kv_compressed = llm_build_norm(ctx0, kv_compressed, hparams,
  12110. model.layers[il].attn_kv_a_norm, NULL,
  12111. LLM_NORM_RMS, cb, il);
  12112. cb(kv_compressed, "kv_compressed", il);
  12113. // {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}
  12114. struct ggml_tensor * kv = ggml_mul_mat(ctx0, model.layers[il].wkv_b, kv_compressed);
  12115. cb(kv, "kv", il);
  12116. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  12117. struct ggml_tensor * k_nope = ggml_view_3d(ctx0, kv, n_embd_head_qk_nope, n_head, n_tokens,
  12118. ggml_row_size(kv->type, n_embd_head_qk_nope + hparams.n_embd_head_v),
  12119. ggml_row_size(kv->type, n_head * (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  12120. 0);
  12121. cb(k_nope, "k_nope", il);
  12122. // and {n_head * n_embd_head_v, n_tokens}
  12123. struct ggml_tensor * v_states = ggml_view_3d(ctx0, kv, hparams.n_embd_head_v, n_head, n_tokens,
  12124. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  12125. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)*n_head),
  12126. ggml_row_size(kv->type, (n_embd_head_qk_nope)));
  12127. cb(v_states, "v_states", il);
  12128. v_states = ggml_cont(ctx0, v_states);
  12129. cb(v_states, "v_states", il);
  12130. v_states = ggml_view_2d(ctx0, v_states, hparams.n_embd_head_v * n_head, n_tokens,
  12131. ggml_row_size(kv->type, hparams.n_embd_head_v * n_head),
  12132. 0);
  12133. cb(v_states, "v_states", il);
  12134. q_pe = ggml_cont(ctx0, q_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  12135. q_pe = ggml_rope_ext(
  12136. ctx0, q_pe, inp_pos, rope_factors,
  12137. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12138. ext_factor, attn_factor, beta_fast, beta_slow
  12139. );
  12140. cb(q_pe, "q_pe", il);
  12141. // shared RoPE key
  12142. k_pe = ggml_cont(ctx0, k_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  12143. k_pe = ggml_rope_ext(
  12144. ctx0, k_pe, inp_pos, rope_factors,
  12145. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12146. ext_factor, attn_factor, beta_fast, beta_slow
  12147. );
  12148. cb(k_pe, "k_pe", il);
  12149. struct ggml_tensor * q_states = ggml_concat(ctx0, q_nope, q_pe, 0);
  12150. cb(q_states, "q_states", il);
  12151. struct ggml_tensor * k_states = ggml_concat(ctx0, k_nope, ggml_repeat(ctx0, k_pe, q_pe), 0);
  12152. cb(k_states, "k_states", il);
  12153. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12154. model.layers[il].wo, NULL,
  12155. k_states, v_states, q_states, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  12156. }
  12157. if (il == n_layer - 1) {
  12158. // skip computing output for unused tokens
  12159. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12160. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12161. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12162. }
  12163. // scale_res - scale the hidden states for residual connection
  12164. const float scale_res = scale_depth/sqrtf(float(n_layer));
  12165. cur = ggml_scale(ctx0, cur, scale_res);
  12166. cb(cur, "hidden_scaled", il);
  12167. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12168. cb(ffn_inp, "ffn_inp", il);
  12169. // feed-forward network
  12170. {
  12171. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12172. model.layers[il].ffn_norm, NULL,
  12173. LLM_NORM_RMS, cb, il);
  12174. cb(cur, "ffn_norm", il);
  12175. cur = llm_build_ffn(ctx0, lctx, cur,
  12176. model.layers[il].ffn_up, NULL, NULL,
  12177. model.layers[il].ffn_gate, NULL, NULL,
  12178. model.layers[il].ffn_down, NULL, NULL,
  12179. NULL,
  12180. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12181. cb(cur, "ffn_out", il);
  12182. }
  12183. // scale the hidden states for residual connection
  12184. cur = ggml_scale(ctx0, cur, scale_res);
  12185. cb(cur, "hidden_scaled_ffn", il);
  12186. cur = ggml_add(ctx0, cur, ffn_inp);
  12187. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12188. cb(cur, "l_out", il);
  12189. // input for next layer
  12190. inpL = cur;
  12191. }
  12192. cur = inpL;
  12193. cur = llm_build_norm(ctx0, cur, hparams,
  12194. model.output_norm, NULL,
  12195. LLM_NORM_RMS, cb, -1);
  12196. cb(cur, "result_norm", -1);
  12197. // lm_head scaling
  12198. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  12199. cur = ggml_scale(ctx0, cur, scale_lmhead);
  12200. cb(cur, "lmhead_scaling", -1);
  12201. // lm_head
  12202. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12203. cb(cur, "result_output", -1);
  12204. ggml_build_forward_expand(gf, cur);
  12205. return gf;
  12206. }
  12207. struct ggml_cgraph * build_gemma() {
  12208. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12209. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  12210. struct ggml_tensor * cur;
  12211. struct ggml_tensor * inpL;
  12212. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12213. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  12214. cb(inpL, "inp_scaled", -1);
  12215. // inp_pos - contains the positions
  12216. struct ggml_tensor * inp_pos = build_inp_pos();
  12217. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12218. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12219. for (int il = 0; il < n_layer; ++il) {
  12220. // norm
  12221. cur = llm_build_norm(ctx0, inpL, hparams,
  12222. model.layers[il].attn_norm, NULL,
  12223. LLM_NORM_RMS, cb, il);
  12224. cb(cur, "attn_norm", il);
  12225. // self-attention
  12226. {
  12227. // compute Q and K and RoPE them
  12228. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12229. cb(Qcur, "Qcur", il);
  12230. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12231. cb(Kcur, "Kcur", il);
  12232. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12233. cb(Vcur, "Vcur", il);
  12234. Qcur = ggml_rope_ext(
  12235. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos, nullptr,
  12236. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12237. ext_factor, attn_factor, beta_fast, beta_slow);
  12238. cb(Qcur, "Qcur", il);
  12239. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  12240. cb(Qcur, "Qcur_scaled", il);
  12241. Kcur = ggml_rope_ext(
  12242. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos, nullptr,
  12243. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12244. ext_factor, attn_factor, beta_fast, beta_slow);
  12245. cb(Kcur, "Kcur", il);
  12246. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12247. model.layers[il].wo, NULL,
  12248. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  12249. }
  12250. if (il == n_layer - 1) {
  12251. // skip computing output for unused tokens
  12252. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12253. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12254. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  12255. }
  12256. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  12257. cb(sa_out, "sa_out", il);
  12258. cur = llm_build_norm(ctx0, sa_out, hparams,
  12259. model.layers[il].ffn_norm, NULL,
  12260. LLM_NORM_RMS, cb, il);
  12261. cb(cur, "ffn_norm", il);
  12262. // feed-forward network
  12263. {
  12264. cur = llm_build_ffn(ctx0, lctx, cur,
  12265. model.layers[il].ffn_up, NULL, NULL,
  12266. model.layers[il].ffn_gate, NULL, NULL,
  12267. model.layers[il].ffn_down, NULL, NULL,
  12268. NULL,
  12269. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  12270. cb(cur, "ffn_out", il);
  12271. }
  12272. cur = ggml_add(ctx0, cur, sa_out);
  12273. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12274. cb(cur, "l_out", il);
  12275. // input for next layer
  12276. inpL = cur;
  12277. }
  12278. cur = inpL;
  12279. cur = llm_build_norm(ctx0, cur, hparams,
  12280. model.output_norm, NULL,
  12281. LLM_NORM_RMS, cb, -1);
  12282. cb(cur, "result_norm", -1);
  12283. // lm_head
  12284. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12285. cb(cur, "result_output", -1);
  12286. ggml_build_forward_expand(gf, cur);
  12287. return gf;
  12288. }
  12289. struct ggml_cgraph * build_gemma2() {
  12290. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12291. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  12292. struct ggml_tensor * cur;
  12293. struct ggml_tensor * inpL;
  12294. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12295. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  12296. cb(inpL, "inp_scaled", -1);
  12297. // inp_pos - contains the positions
  12298. struct ggml_tensor * inp_pos = build_inp_pos();
  12299. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12300. // gemma 2 requires different mask for layers using sliding window (SWA)
  12301. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(true);
  12302. struct ggml_tensor * KQ_mask_swa = build_inp_KQ_mask_swa(true);
  12303. for (int il = 0; il < n_layer; ++il) {
  12304. // (il % 2) layers use SWA
  12305. struct ggml_tensor * KQ_mask_l = (il % 2 == 0) ? KQ_mask_swa : KQ_mask;
  12306. // norm
  12307. cur = llm_build_norm(ctx0, inpL, hparams,
  12308. model.layers[il].attn_norm, NULL,
  12309. LLM_NORM_RMS, cb, il);
  12310. cb(cur, "attn_norm", il);
  12311. // self-attention
  12312. {
  12313. // compute Q and K and RoPE them
  12314. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12315. cb(Qcur, "Qcur", il);
  12316. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12317. cb(Kcur, "Kcur", il);
  12318. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12319. cb(Vcur, "Vcur", il);
  12320. Qcur = ggml_rope_ext(
  12321. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos, nullptr,
  12322. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12323. ext_factor, attn_factor, beta_fast, beta_slow);
  12324. cb(Qcur, "Qcur", il);
  12325. // ref: https://github.com/google/gemma_pytorch/commit/03e657582d17cb5a8617ebf333c1c16f3694670e
  12326. switch (model.type) {
  12327. case e_model::MODEL_2B:
  12328. case e_model::MODEL_9B: Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k))); break;
  12329. case e_model::MODEL_27B: Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd / n_head))); break;
  12330. default: GGML_ABORT("fatal error");
  12331. };
  12332. cb(Qcur, "Qcur_scaled", il);
  12333. Kcur = ggml_rope_ext(
  12334. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos, nullptr,
  12335. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12336. ext_factor, attn_factor, beta_fast, beta_slow);
  12337. cb(Kcur, "Kcur", il);
  12338. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12339. model.layers[il].wo, NULL,
  12340. Kcur, Vcur, Qcur, KQ_mask_l, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  12341. }
  12342. cur = llm_build_norm(ctx0, cur, hparams,
  12343. model.layers[il].attn_post_norm, NULL,
  12344. LLM_NORM_RMS, cb, il);
  12345. cb(cur, "attn_post_norm", il);
  12346. if (il == n_layer - 1) {
  12347. // skip computing output for unused tokens
  12348. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12349. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12350. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  12351. }
  12352. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  12353. cb(sa_out, "sa_out", il);
  12354. cur = llm_build_norm(ctx0, sa_out, hparams,
  12355. model.layers[il].ffn_norm, NULL,
  12356. LLM_NORM_RMS, cb, il);
  12357. cb(cur, "ffn_norm", il);
  12358. // feed-forward network
  12359. {
  12360. cur = llm_build_ffn(ctx0, lctx, cur,
  12361. model.layers[il].ffn_up, NULL, NULL,
  12362. model.layers[il].ffn_gate, NULL, NULL,
  12363. model.layers[il].ffn_down, NULL, NULL,
  12364. NULL,
  12365. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  12366. cb(cur, "ffn_out", il);
  12367. }
  12368. cur = llm_build_norm(ctx0, cur, hparams,
  12369. model.layers[il].ffn_post_norm, NULL,
  12370. LLM_NORM_RMS, cb, -1);
  12371. cb(cur, "ffn_post_norm", -1);
  12372. cur = ggml_add(ctx0, cur, sa_out);
  12373. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12374. cb(cur, "l_out", il);
  12375. // input for next layer
  12376. inpL = cur;
  12377. }
  12378. cur = inpL;
  12379. cur = llm_build_norm(ctx0, cur, hparams,
  12380. model.output_norm, NULL,
  12381. LLM_NORM_RMS, cb, -1);
  12382. cb(cur, "result_norm", -1);
  12383. // lm_head
  12384. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12385. // final logit soft-capping
  12386. cur = ggml_scale(ctx0, cur, 1.0f / hparams.f_final_logit_softcapping);
  12387. cur = ggml_tanh(ctx0, cur);
  12388. cur = ggml_scale(ctx0, cur, hparams.f_final_logit_softcapping);
  12389. cb(cur, "result_output", -1);
  12390. ggml_build_forward_expand(gf, cur);
  12391. return gf;
  12392. }
  12393. struct ggml_cgraph * build_starcoder2() {
  12394. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12395. const int64_t n_embd_head = hparams.n_embd_head_v;
  12396. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12397. GGML_ASSERT(n_embd_head == hparams.n_rot);
  12398. struct ggml_tensor * cur;
  12399. struct ggml_tensor * inpL;
  12400. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12401. // inp_pos - contains the positions
  12402. struct ggml_tensor * inp_pos = build_inp_pos();
  12403. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12404. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12405. for (int il = 0; il < n_layer; ++il) {
  12406. struct ggml_tensor * inpSA = inpL;
  12407. // norm
  12408. cur = llm_build_norm(ctx0, inpL, hparams,
  12409. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  12410. LLM_NORM, cb, il);
  12411. cb(cur, "attn_norm", il);
  12412. // self-attention
  12413. {
  12414. // compute Q and K and RoPE them
  12415. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12416. cb(Qcur, "Qcur", il);
  12417. if (model.layers[il].bq) {
  12418. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  12419. cb(Qcur, "Qcur", il);
  12420. }
  12421. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12422. cb(Kcur, "Kcur", il);
  12423. if (model.layers[il].bk) {
  12424. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  12425. cb(Kcur, "Kcur", il);
  12426. }
  12427. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12428. cb(Vcur, "Vcur", il);
  12429. if (model.layers[il].bv) {
  12430. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  12431. cb(Vcur, "Vcur", il);
  12432. }
  12433. Qcur = ggml_rope_ext(
  12434. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  12435. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12436. ext_factor, attn_factor, beta_fast, beta_slow
  12437. );
  12438. cb(Qcur, "Qcur", il);
  12439. Kcur = ggml_rope_ext(
  12440. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  12441. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12442. ext_factor, attn_factor, beta_fast, beta_slow
  12443. );
  12444. cb(Kcur, "Kcur", il);
  12445. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12446. model.layers[il].wo, model.layers[il].bo,
  12447. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12448. }
  12449. if (il == n_layer - 1) {
  12450. // skip computing output for unused tokens
  12451. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12452. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12453. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12454. }
  12455. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12456. cb(ffn_inp, "ffn_inp", il);
  12457. // feed-forward network
  12458. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12459. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  12460. LLM_NORM, cb, il);
  12461. cb(cur, "ffn_norm", il);
  12462. cur = llm_build_ffn(ctx0, lctx, cur,
  12463. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  12464. NULL, NULL, NULL,
  12465. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  12466. NULL,
  12467. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  12468. cb(cur, "ffn_out", il);
  12469. cur = ggml_add(ctx0, cur, ffn_inp);
  12470. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12471. cb(cur, "l_out", il);
  12472. // input for next layer
  12473. inpL = cur;
  12474. }
  12475. cur = inpL;
  12476. cur = llm_build_norm(ctx0, cur, hparams,
  12477. model.output_norm, model.output_norm_b,
  12478. LLM_NORM, cb, -1);
  12479. cb(cur, "result_norm", -1);
  12480. // lm_head
  12481. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12482. cb(cur, "result_output", -1);
  12483. ggml_build_forward_expand(gf, cur);
  12484. return gf;
  12485. }
  12486. struct ggml_cgraph * build_mamba() {
  12487. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12488. struct ggml_tensor * cur;
  12489. struct ggml_tensor * inpL;
  12490. // {n_embd, n_tokens}
  12491. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12492. struct ggml_tensor * state_copy = build_inp_s_copy();
  12493. struct ggml_tensor * state_mask = build_inp_s_mask();
  12494. for (int il = 0; il < n_layer; ++il) {
  12495. // norm
  12496. cur = llm_build_norm(ctx0, inpL, hparams,
  12497. model.layers[il].attn_norm, NULL,
  12498. LLM_NORM_RMS, cb, il);
  12499. cb(cur, "attn_norm", il);
  12500. cur = llm_build_mamba(ctx0, lctx, ubatch, gf, cur,
  12501. state_copy, state_mask,
  12502. kv_head, n_kv, cb, il);
  12503. if (il == n_layer - 1) {
  12504. // skip computing output for unused tokens
  12505. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12506. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12507. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  12508. }
  12509. // residual
  12510. cur = ggml_add(ctx0, cur, inpL);
  12511. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12512. cb(cur, "l_out", il);
  12513. // input for next layer
  12514. inpL = cur;
  12515. }
  12516. // final rmsnorm
  12517. cur = llm_build_norm(ctx0, inpL, hparams,
  12518. model.output_norm, NULL,
  12519. LLM_NORM_RMS, cb, -1);
  12520. cb(cur, "result_norm", -1);
  12521. // lm_head
  12522. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12523. cb(cur, "result_output", -1);
  12524. ggml_build_forward_expand(gf, cur);
  12525. return gf;
  12526. }
  12527. struct ggml_cgraph * build_command_r() {
  12528. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12529. const int64_t n_embd_head = hparams.n_embd_head_v;
  12530. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12531. const float f_logit_scale = hparams.f_logit_scale;
  12532. struct ggml_tensor * cur;
  12533. struct ggml_tensor * inpL;
  12534. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12535. // inp_pos - contains the positions
  12536. struct ggml_tensor * inp_pos = build_inp_pos();
  12537. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12538. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12539. for (int il = 0; il < n_layer; ++il) {
  12540. // norm
  12541. cur = llm_build_norm(ctx0, inpL, hparams,
  12542. model.layers[il].attn_norm, NULL,
  12543. LLM_NORM, cb, il);
  12544. cb(cur, "attn_norm", il);
  12545. struct ggml_tensor * ffn_inp = cur;
  12546. // self-attention
  12547. {
  12548. // compute Q and K and RoPE them
  12549. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12550. cb(Qcur, "Qcur", il);
  12551. if (model.layers[il].bq) {
  12552. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  12553. cb(Qcur, "Qcur", il);
  12554. }
  12555. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12556. cb(Kcur, "Kcur", il);
  12557. if (model.layers[il].bk) {
  12558. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  12559. cb(Kcur, "Kcur", il);
  12560. }
  12561. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12562. cb(Vcur, "Vcur", il);
  12563. if (model.layers[il].bv) {
  12564. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  12565. cb(Vcur, "Vcur", il);
  12566. }
  12567. if (model.layers[il].attn_q_norm) {
  12568. Qcur = ggml_view_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens,
  12569. ggml_element_size(Qcur) * n_embd_head,
  12570. ggml_element_size(Qcur) * n_embd_head * n_head,
  12571. 0);
  12572. cb(Qcur, "Qcur", il);
  12573. Kcur = ggml_view_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens,
  12574. ggml_element_size(Kcur) * n_embd_head,
  12575. ggml_element_size(Kcur) * n_embd_head * n_head_kv,
  12576. 0);
  12577. cb(Kcur, "Kcur", il);
  12578. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  12579. model.layers[il].attn_q_norm,
  12580. NULL,
  12581. LLM_NORM, cb, il);
  12582. cb(Qcur, "Qcur", il);
  12583. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  12584. model.layers[il].attn_k_norm,
  12585. NULL,
  12586. LLM_NORM, cb, il);
  12587. cb(Kcur, "Kcur", il);
  12588. }
  12589. Qcur = ggml_rope_ext(
  12590. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  12591. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12592. ext_factor, attn_factor, beta_fast, beta_slow
  12593. );
  12594. cb(Qcur, "Qcur", il);
  12595. Kcur = ggml_rope_ext(
  12596. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  12597. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12598. ext_factor, attn_factor, beta_fast, beta_slow
  12599. );
  12600. cb(Kcur, "Kcur", il);
  12601. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12602. model.layers[il].wo, model.layers[il].bo,
  12603. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12604. }
  12605. if (il == n_layer - 1) {
  12606. // skip computing output for unused tokens
  12607. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12608. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12609. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  12610. ffn_inp = ggml_get_rows(ctx0, ffn_inp, inp_out_ids);
  12611. }
  12612. struct ggml_tensor * attn_out = cur;
  12613. // feed-forward network
  12614. {
  12615. cur = llm_build_ffn(ctx0, lctx, ffn_inp,
  12616. model.layers[il].ffn_up, NULL, NULL,
  12617. model.layers[il].ffn_gate, NULL, NULL,
  12618. model.layers[il].ffn_down, NULL, NULL,
  12619. NULL,
  12620. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12621. cb(cur, "ffn_out", il);
  12622. }
  12623. // add together residual + FFN + self-attention
  12624. cur = ggml_add(ctx0, cur, inpL);
  12625. cur = ggml_add(ctx0, cur, attn_out);
  12626. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12627. cb(cur, "l_out", il);
  12628. // input for next layer
  12629. inpL = cur;
  12630. }
  12631. cur = inpL;
  12632. cur = llm_build_norm(ctx0, cur, hparams,
  12633. model.output_norm, NULL,
  12634. LLM_NORM, cb, -1);
  12635. cb(cur, "result_norm", -1);
  12636. // lm_head
  12637. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12638. if (f_logit_scale) {
  12639. cur = ggml_scale(ctx0, cur, f_logit_scale);
  12640. }
  12641. cb(cur, "result_output", -1);
  12642. ggml_build_forward_expand(gf, cur);
  12643. return gf;
  12644. }
  12645. // ref: https://allenai.org/olmo
  12646. // based on the original build_llama() function, changes:
  12647. // * non-parametric layer norm
  12648. // * clamp qkv
  12649. // * removed bias
  12650. // * removed MoE
  12651. struct ggml_cgraph * build_olmo() {
  12652. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12653. // mutable variable, needed during the last layer of the computation to skip unused tokens
  12654. int32_t n_tokens = this->n_tokens;
  12655. const int64_t n_embd_head = hparams.n_embd_head_v;
  12656. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12657. GGML_ASSERT(n_embd_head == hparams.n_rot);
  12658. struct ggml_tensor * cur;
  12659. struct ggml_tensor * inpL;
  12660. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12661. // inp_pos - contains the positions
  12662. struct ggml_tensor * inp_pos = build_inp_pos();
  12663. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12664. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12665. for (int il = 0; il < n_layer; ++il) {
  12666. struct ggml_tensor * inpSA = inpL;
  12667. // norm
  12668. cur = llm_build_norm(ctx0, inpL, hparams,
  12669. NULL, NULL,
  12670. LLM_NORM, cb, il);
  12671. cb(cur, "attn_norm", il);
  12672. // self-attention
  12673. {
  12674. // compute Q and K and RoPE them
  12675. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12676. cb(Qcur, "Qcur", il);
  12677. if (hparams.f_clamp_kqv > 0.0f) {
  12678. Qcur = ggml_clamp(ctx0, Qcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  12679. cb(Qcur, "Qcur", il);
  12680. }
  12681. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12682. cb(Kcur, "Kcur", il);
  12683. if (hparams.f_clamp_kqv > 0.0f) {
  12684. Kcur = ggml_clamp(ctx0, Kcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  12685. cb(Kcur, "Kcur", il);
  12686. }
  12687. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12688. cb(Vcur, "Vcur", il);
  12689. if (hparams.f_clamp_kqv > 0.0f) {
  12690. Vcur = ggml_clamp(ctx0, Vcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  12691. cb(Vcur, "Vcur", il);
  12692. }
  12693. Qcur = ggml_rope_ext(
  12694. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  12695. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12696. ext_factor, attn_factor, beta_fast, beta_slow
  12697. );
  12698. cb(Qcur, "Qcur", il);
  12699. Kcur = ggml_rope_ext(
  12700. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  12701. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12702. ext_factor, attn_factor, beta_fast, beta_slow
  12703. );
  12704. cb(Kcur, "Kcur", il);
  12705. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12706. model.layers[il].wo, nullptr,
  12707. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12708. }
  12709. if (il == n_layer - 1) {
  12710. // skip computing output for unused tokens
  12711. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12712. n_tokens = n_outputs;
  12713. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12714. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12715. }
  12716. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12717. cb(ffn_inp, "ffn_inp", il);
  12718. // feed-forward network
  12719. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12720. NULL, NULL,
  12721. LLM_NORM, cb, il);
  12722. cb(cur, "ffn_norm", il);
  12723. cur = llm_build_ffn(ctx0, lctx, cur,
  12724. model.layers[il].ffn_up, NULL, NULL,
  12725. model.layers[il].ffn_gate, NULL, NULL,
  12726. model.layers[il].ffn_down, NULL, NULL,
  12727. NULL,
  12728. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12729. cb(cur, "ffn_out", il);
  12730. cur = ggml_add(ctx0, cur, ffn_inp);
  12731. cb(cur, "ffn_out", il);
  12732. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12733. cb(cur, "l_out", il);
  12734. // input for next layer
  12735. inpL = cur;
  12736. }
  12737. cur = inpL;
  12738. cur = llm_build_norm(ctx0, cur, hparams,
  12739. NULL, NULL,
  12740. LLM_NORM, cb, -1);
  12741. cb(cur, "result_norm", -1);
  12742. // lm_head
  12743. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12744. cb(cur, "result_output", -1);
  12745. ggml_build_forward_expand(gf, cur);
  12746. return gf;
  12747. }
  12748. struct ggml_cgraph * build_olmo2() {
  12749. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12750. // mutable variable, needed during the last layer of the computation to skip unused tokens
  12751. int32_t n_tokens = this->n_tokens;
  12752. const int64_t n_embd_head = hparams.n_embd_head_v;
  12753. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12754. GGML_ASSERT(n_embd_head == hparams.n_rot);
  12755. struct ggml_tensor * cur;
  12756. struct ggml_tensor * inpL;
  12757. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12758. // inp_pos - contains the positions
  12759. struct ggml_tensor * inp_pos = build_inp_pos();
  12760. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12761. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12762. for (int il = 0; il < n_layer; ++il) {
  12763. struct ggml_tensor * inpSA = inpL;
  12764. cur = inpL;
  12765. // self_attention
  12766. {
  12767. // compute Q and K and RoPE them
  12768. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12769. cb(Qcur, "Qcur", il);
  12770. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12771. cb(Kcur, "Kcur", il);
  12772. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12773. cb(Vcur, "Vcur", il);
  12774. Qcur = llm_build_norm(ctx0, Qcur, hparams, model.layers[il].attn_q_norm, NULL,
  12775. LLM_NORM_RMS, cb, il);
  12776. cb(Qcur, "Qcur_normed", il);
  12777. Kcur = llm_build_norm(ctx0, Kcur, hparams, model.layers[il].attn_k_norm, NULL,
  12778. LLM_NORM_RMS, cb, il);
  12779. cb(Kcur, "Kcur_normed", il);
  12780. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  12781. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  12782. Qcur = ggml_rope_ext(
  12783. ctx0, Qcur, inp_pos, nullptr,
  12784. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12785. ext_factor, attn_factor, beta_fast, beta_slow
  12786. );
  12787. cb(Qcur, "Qcur_rope", il);
  12788. Kcur = ggml_rope_ext(
  12789. ctx0, Kcur, inp_pos, nullptr,
  12790. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12791. ext_factor, attn_factor, beta_fast, beta_slow
  12792. );
  12793. cb(Kcur, "Kcur_rope", il);
  12794. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12795. model.layers[il].wo, NULL,
  12796. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12797. }
  12798. cur = llm_build_norm(ctx0, cur, hparams,
  12799. model.layers[il].attn_post_norm, NULL,
  12800. LLM_NORM_RMS, cb, il);
  12801. cb(cur, "attn_post_norm", il);
  12802. if (il == n_layer - 1) {
  12803. // skip computing output for unused tokens
  12804. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12805. n_tokens = n_outputs;
  12806. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12807. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12808. }
  12809. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12810. cb(ffn_inp, "ffn_inp", il);
  12811. // feed-forward network
  12812. cur = llm_build_ffn(ctx0, lctx, ffn_inp,
  12813. model.layers[il].ffn_up, NULL, NULL,
  12814. model.layers[il].ffn_gate, NULL, NULL,
  12815. model.layers[il].ffn_down, NULL, NULL,
  12816. NULL,
  12817. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12818. cb(cur, "ffn_out", il);
  12819. cur = llm_build_norm(ctx0, cur, hparams,
  12820. model.layers[il].ffn_post_norm, NULL,
  12821. LLM_NORM_RMS, cb, -1);
  12822. cb(cur, "ffn_post_norm", -1);
  12823. cur = ggml_add(ctx0, cur, ffn_inp);
  12824. cb(cur, "ffn_out", il);
  12825. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12826. cb(cur, "l_out", il);
  12827. // input for next layer
  12828. inpL = cur;
  12829. }
  12830. cur = inpL;
  12831. cur = llm_build_norm(ctx0, cur, hparams,
  12832. model.output_norm, NULL,
  12833. LLM_NORM_RMS, cb, -1);
  12834. cb(cur, "result_norm", -1);
  12835. // lm_head
  12836. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12837. cb(cur, "result_output", -1);
  12838. ggml_build_forward_expand(gf, cur);
  12839. return gf;
  12840. }
  12841. // based on the build_qwen2moe() function, changes:
  12842. // * removed shared experts
  12843. // * removed bias
  12844. // * added q, k norm
  12845. struct ggml_cgraph * build_olmoe() {
  12846. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12847. // mutable variable, needed during the last layer of the computation to skip unused tokens
  12848. int32_t n_tokens = this->n_tokens;
  12849. const int64_t n_embd_head = hparams.n_embd_head_v;
  12850. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12851. GGML_ASSERT(n_embd_head == hparams.n_rot);
  12852. struct ggml_tensor * cur;
  12853. struct ggml_tensor * inpL;
  12854. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12855. // inp_pos - contains the positions
  12856. struct ggml_tensor * inp_pos = build_inp_pos();
  12857. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12858. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12859. for (int il = 0; il < n_layer; ++il) {
  12860. struct ggml_tensor * inpSA = inpL;
  12861. // norm
  12862. cur = llm_build_norm(ctx0, inpL, hparams,
  12863. model.layers[il].attn_norm, NULL,
  12864. LLM_NORM_RMS, cb, il);
  12865. cb(cur, "attn_norm", il);
  12866. // self_attention
  12867. {
  12868. // compute Q and K and RoPE them
  12869. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12870. cb(Qcur, "Qcur", il);
  12871. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12872. cb(Kcur, "Kcur", il);
  12873. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12874. cb(Vcur, "Vcur", il);
  12875. Qcur = llm_build_norm(ctx0, Qcur, hparams, model.layers[il].attn_q_norm, NULL,
  12876. LLM_NORM_RMS, cb, il);
  12877. cb(Qcur, "Qcur_normed", il);
  12878. Kcur = llm_build_norm(ctx0, Kcur, hparams, model.layers[il].attn_k_norm, NULL,
  12879. LLM_NORM_RMS, cb, il);
  12880. cb(Kcur, "Kcur_normed", il);
  12881. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  12882. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  12883. Qcur = ggml_rope_ext(
  12884. ctx0, Qcur, inp_pos, nullptr,
  12885. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12886. ext_factor, attn_factor, beta_fast, beta_slow
  12887. );
  12888. cb(Qcur, "Qcur_rope", il);
  12889. Kcur = ggml_rope_ext(
  12890. ctx0, Kcur, inp_pos, nullptr,
  12891. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12892. ext_factor, attn_factor, beta_fast, beta_slow
  12893. );
  12894. cb(Kcur, "Kcur_rope", il);
  12895. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12896. model.layers[il].wo, NULL,
  12897. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12898. }
  12899. if (il == n_layer - 1) {
  12900. // skip computing output for unused tokens
  12901. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12902. n_tokens = n_outputs;
  12903. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12904. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12905. }
  12906. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12907. cb(ffn_inp, "ffn_inp", il);
  12908. // MoE branch
  12909. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12910. model.layers[il].ffn_norm, NULL,
  12911. LLM_NORM_RMS, cb, il);
  12912. cb(cur, "ffn_norm", il);
  12913. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  12914. model.layers[il].ffn_gate_inp,
  12915. model.layers[il].ffn_up_exps,
  12916. model.layers[il].ffn_gate_exps,
  12917. model.layers[il].ffn_down_exps,
  12918. n_expert, n_expert_used,
  12919. LLM_FFN_SILU, false,
  12920. false, 0.0,
  12921. cb, il);
  12922. cb(cur, "ffn_moe_out", il);
  12923. cur = ggml_add(ctx0, cur, ffn_inp);
  12924. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12925. cb(cur, "l_out", il);
  12926. // input for next layer
  12927. inpL = cur;
  12928. }
  12929. cur = inpL;
  12930. cur = llm_build_norm(ctx0, cur, hparams,
  12931. model.output_norm, NULL,
  12932. LLM_NORM_RMS, cb, -1);
  12933. cb(cur, "result_norm", -1);
  12934. // lm_head
  12935. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12936. cb(cur, "result_output", -1);
  12937. ggml_build_forward_expand(gf, cur);
  12938. return gf;
  12939. }
  12940. struct ggml_cgraph * build_openelm() {
  12941. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12942. const int64_t n_embd_head = hparams.n_embd_head_v;
  12943. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12944. struct ggml_tensor * cur;
  12945. struct ggml_tensor * inpL;
  12946. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  12947. // inp_pos - contains the positions
  12948. struct ggml_tensor * inp_pos = build_inp_pos();
  12949. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12950. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12951. for (int il = 0; il < n_layer; ++il) {
  12952. const int64_t n_head = hparams.n_head(il);
  12953. const int64_t n_head_kv = hparams.n_head_kv(il);
  12954. const int64_t n_head_qkv = 2*n_head_kv + n_head;
  12955. cur = inpL;
  12956. struct ggml_tensor * residual = cur;
  12957. // norm
  12958. cur = llm_build_norm(ctx0, inpL, hparams,
  12959. model.layers[il].attn_norm, NULL,
  12960. LLM_NORM_RMS, cb, il);
  12961. cb(cur, "attn_norm", il);
  12962. // self-attention
  12963. {
  12964. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  12965. cb(cur, "wqkv", il);
  12966. cur = ggml_reshape_3d(ctx0, cur, n_embd_head_k, n_head_qkv, n_tokens);
  12967. 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));
  12968. cb(Qcur, "Qcur", il);
  12969. 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));
  12970. cb(Kcur, "Kcur", il);
  12971. 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)));
  12972. cb(Vcur, "Vcur", il);
  12973. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  12974. model.layers[il].attn_q_norm, NULL,
  12975. LLM_NORM_RMS, cb, il);
  12976. cb(Qcur, "Qcur", il);
  12977. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  12978. model.layers[il].attn_k_norm, NULL,
  12979. LLM_NORM_RMS, cb, il);
  12980. cb(Kcur, "Kcur", il);
  12981. Qcur = ggml_rope_ext(
  12982. ctx0, Qcur, inp_pos, NULL, n_rot, rope_type, n_ctx_orig,
  12983. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  12984. );
  12985. cb(Qcur, "Qcur", il);
  12986. Kcur = ggml_rope_ext(
  12987. ctx0, Kcur, inp_pos, NULL, n_rot, rope_type, n_ctx_orig,
  12988. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  12989. );
  12990. cb(Kcur, "Kcur", il);
  12991. Vcur = ggml_reshape_2d(ctx0, Vcur, n_embd_head * n_head_kv, n_tokens);
  12992. cb(Qcur, "Vcur", il);
  12993. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12994. model.layers[il].wo, NULL,
  12995. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12996. }
  12997. if (il == n_layer - 1) {
  12998. // skip computing output for unused tokens
  12999. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13000. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  13001. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13002. }
  13003. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  13004. cb(ffn_inp, "ffn_inp", il);
  13005. // feed-forward network
  13006. {
  13007. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13008. model.layers[il].ffn_norm, NULL,
  13009. LLM_NORM_RMS, cb, il);
  13010. cb(cur, "ffn_norm", il);
  13011. cur = llm_build_ffn(ctx0, lctx, cur,
  13012. model.layers[il].ffn_up, NULL, NULL,
  13013. model.layers[il].ffn_gate, NULL, NULL,
  13014. model.layers[il].ffn_down, NULL, NULL,
  13015. NULL,
  13016. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13017. cb(cur, "ffn_out", il);
  13018. }
  13019. cur = ggml_add(ctx0, cur, ffn_inp);
  13020. cur = lctx.cvec.apply_to(ctx0, cur, il);
  13021. cb(cur, "l_out", il);
  13022. inpL = cur;
  13023. }
  13024. cur = inpL;
  13025. // norm
  13026. cur = llm_build_norm(ctx0, cur, hparams,
  13027. model.output_norm, NULL,
  13028. LLM_NORM_RMS, cb, -1);
  13029. cb(cur, "result_norm", -1);
  13030. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13031. cb(cur, "result_output", -1);
  13032. ggml_build_forward_expand(gf, cur);
  13033. return gf;
  13034. }
  13035. struct ggml_cgraph * build_gptneox() {
  13036. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13037. const int64_t n_embd_head = hparams.n_embd_head_v;
  13038. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  13039. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13040. struct ggml_tensor * cur;
  13041. struct ggml_tensor * inpL;
  13042. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13043. // inp_pos - contains the positions
  13044. struct ggml_tensor * inp_pos = build_inp_pos();
  13045. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13046. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13047. for (int il = 0; il < n_layer; ++il) {
  13048. cur = llm_build_norm(ctx0, inpL, hparams,
  13049. model.layers[il].attn_norm,
  13050. model.layers[il].attn_norm_b,
  13051. LLM_NORM, cb, il);
  13052. cb(cur, "attn_norm", il);
  13053. // self-attention
  13054. {
  13055. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  13056. cb(cur, "wqkv", il);
  13057. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  13058. cb(cur, "bqkv", il);
  13059. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  13060. 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)));
  13061. 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)));
  13062. cb(Qcur, "Qcur", il);
  13063. cb(Kcur, "Kcur", il);
  13064. cb(Vcur, "Vcur", il);
  13065. Qcur = ggml_rope_ext(
  13066. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  13067. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13068. ext_factor, attn_factor, beta_fast, beta_slow
  13069. );
  13070. cb(Qcur, "Qcur", il);
  13071. Kcur = ggml_rope_ext(
  13072. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  13073. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13074. ext_factor, attn_factor, beta_fast, beta_slow
  13075. );
  13076. cb(Kcur, "Kcur", il);
  13077. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13078. model.layers[il].wo, model.layers[il].bo,
  13079. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13080. }
  13081. if (il == n_layer - 1) {
  13082. // skip computing output for unused tokens
  13083. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13084. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13085. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  13086. }
  13087. // ffn
  13088. if (hparams.use_par_res) {
  13089. // attention and ffn are computed in parallel
  13090. // x = x + attn(ln1(x)) + ffn(ln2(x))
  13091. struct ggml_tensor * attn_out = cur;
  13092. cur = llm_build_norm(ctx0, inpL, hparams,
  13093. model.layers[il].ffn_norm,
  13094. model.layers[il].ffn_norm_b,
  13095. LLM_NORM, cb, il);
  13096. cb(cur, "ffn_norm", il);
  13097. cur = llm_build_ffn(ctx0, lctx, cur,
  13098. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  13099. NULL, NULL, NULL,
  13100. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  13101. NULL,
  13102. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  13103. cb(cur, "ffn_out", il);
  13104. cur = ggml_add(ctx0, cur, inpL);
  13105. cb(cur, "ffn_out", il);
  13106. cur = ggml_add(ctx0, cur, attn_out);
  13107. cur = lctx.cvec.apply_to(ctx0, cur, il);
  13108. cb(cur, "l_out", il);
  13109. // input for next layer
  13110. inpL = cur;
  13111. } else {
  13112. // attention and ffn are computed sequentially
  13113. // x = x + attn(ln1(x))
  13114. // x = x + ffn(ln2(x))
  13115. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  13116. cb(ffn_inp, "ffn_inp", il);
  13117. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13118. model.layers[il].ffn_norm,
  13119. model.layers[il].ffn_norm_b,
  13120. LLM_NORM, cb, il);
  13121. cb(cur, "ffn_norm", il);
  13122. cur = llm_build_ffn(ctx0, lctx, cur,
  13123. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  13124. NULL, NULL, NULL,
  13125. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  13126. NULL,
  13127. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  13128. cb(cur, "ffn_out", il);
  13129. cur = ggml_add(ctx0, cur, ffn_inp);
  13130. cur = lctx.cvec.apply_to(ctx0, cur, il);
  13131. cb(cur, "l_out", il);
  13132. // input for next layer
  13133. inpL = cur;
  13134. }
  13135. }
  13136. cur = llm_build_norm(ctx0, inpL, hparams,
  13137. model.output_norm,
  13138. model.output_norm_b,
  13139. LLM_NORM, cb, -1);
  13140. cb(cur, "result_norm", -1);
  13141. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13142. cb(cur, "result_output", -1);
  13143. ggml_build_forward_expand(gf, cur);
  13144. return gf;
  13145. }
  13146. struct ggml_cgraph * build_arctic() {
  13147. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13148. // mutable variable, needed during the last layer of the computation to skip unused tokens
  13149. int32_t n_tokens = this->n_tokens;
  13150. const int64_t n_embd_head = hparams.n_embd_head_v;
  13151. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13152. GGML_ASSERT(n_embd_head == hparams.n_rot);
  13153. struct ggml_tensor * cur;
  13154. struct ggml_tensor * inpL;
  13155. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13156. // inp_pos - contains the positions
  13157. struct ggml_tensor * inp_pos = build_inp_pos();
  13158. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13159. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13160. for (int il = 0; il < n_layer; ++il) {
  13161. struct ggml_tensor * inpSA = inpL;
  13162. // norm
  13163. cur = llm_build_norm(ctx0, inpL, hparams,
  13164. model.layers[il].attn_norm, NULL,
  13165. LLM_NORM_RMS, cb, il);
  13166. cb(cur, "attn_norm", il);
  13167. // self-attention
  13168. {
  13169. // compute Q and K and RoPE them
  13170. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  13171. cb(Qcur, "Qcur", il);
  13172. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  13173. cb(Kcur, "Kcur", il);
  13174. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  13175. cb(Vcur, "Vcur", il);
  13176. Qcur = ggml_rope_ext(
  13177. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  13178. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13179. ext_factor, attn_factor, beta_fast, beta_slow
  13180. );
  13181. cb(Qcur, "Qcur", il);
  13182. Kcur = ggml_rope_ext(
  13183. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  13184. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13185. ext_factor, attn_factor, beta_fast, beta_slow
  13186. );
  13187. cb(Kcur, "Kcur", il);
  13188. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13189. model.layers[il].wo, NULL,
  13190. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13191. }
  13192. if (il == n_layer - 1) {
  13193. // skip computing output for unused tokens
  13194. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13195. n_tokens = n_outputs;
  13196. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13197. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13198. }
  13199. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13200. cb(ffn_inp, "ffn_inp", il);
  13201. // feed-forward network
  13202. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13203. model.layers[il].ffn_norm, NULL,
  13204. LLM_NORM_RMS, cb, il);
  13205. cb(cur, "ffn_norm", il);
  13206. cur = llm_build_ffn(ctx0, lctx, cur,
  13207. model.layers[il].ffn_up, NULL, NULL,
  13208. model.layers[il].ffn_gate, NULL, NULL,
  13209. model.layers[il].ffn_down, NULL, NULL,
  13210. NULL,
  13211. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13212. cb(cur, "ffn_out", il);
  13213. struct ggml_tensor * ffn_out = ggml_add(ctx0, cur, ffn_inp);
  13214. cb(ffn_out, "ffn_out", il);
  13215. // MoE
  13216. cur = llm_build_norm(ctx0, inpSA, hparams,
  13217. model.layers[il].ffn_norm_exps, NULL,
  13218. LLM_NORM_RMS, cb, il);
  13219. cb(cur, "ffn_norm_exps", il);
  13220. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  13221. model.layers[il].ffn_gate_inp,
  13222. model.layers[il].ffn_up_exps,
  13223. model.layers[il].ffn_gate_exps,
  13224. model.layers[il].ffn_down_exps,
  13225. n_expert, n_expert_used,
  13226. LLM_FFN_SILU, true,
  13227. false, 0.0,
  13228. cb, il);
  13229. cb(cur, "ffn_moe_out", il);
  13230. cur = ggml_add(ctx0, cur, ffn_out);
  13231. cb(cur, "ffn_out", il);
  13232. cur = lctx.cvec.apply_to(ctx0, cur, il);
  13233. cb(cur, "l_out", il);
  13234. // input for next layer
  13235. inpL = cur;
  13236. }
  13237. cur = inpL;
  13238. cur = llm_build_norm(ctx0, cur, hparams,
  13239. model.output_norm, NULL,
  13240. LLM_NORM_RMS, cb, -1);
  13241. cb(cur, "result_norm", -1);
  13242. // lm_head
  13243. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13244. cb(cur, "result_output", -1);
  13245. ggml_build_forward_expand(gf, cur);
  13246. return gf;
  13247. }
  13248. struct ggml_cgraph * build_deepseek2() {
  13249. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13250. // mutable variable, needed during the last layer of the computation to skip unused tokens
  13251. int32_t n_tokens = this->n_tokens;
  13252. bool is_lite = (hparams.n_layer == 27);
  13253. // We have to pre-scale kq_scale and attn_factor to make the YaRN RoPE work correctly.
  13254. // See https://github.com/ggerganov/llama.cpp/discussions/7416 for detailed explanation.
  13255. const float mscale = attn_factor * (1.0f + hparams.rope_yarn_log_mul * logf(1.0f / freq_scale));
  13256. const float kq_scale = 1.0f*mscale*mscale/sqrtf(float(hparams.n_embd_head_k));
  13257. const float attn_factor_scaled = 1.0f / (1.0f + 0.1f * logf(1.0f / freq_scale));
  13258. const uint32_t n_embd_head_qk_rope = hparams.n_rot;
  13259. const uint32_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  13260. const uint32_t kv_lora_rank = hparams.n_lora_kv;
  13261. struct ggml_tensor * cur;
  13262. struct ggml_tensor * inpL;
  13263. // {n_embd, n_tokens}
  13264. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13265. // inp_pos - contains the positions
  13266. struct ggml_tensor * inp_pos = build_inp_pos();
  13267. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13268. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13269. for (int il = 0; il < n_layer; ++il) {
  13270. struct ggml_tensor * inpSA = inpL;
  13271. // norm
  13272. cur = llm_build_norm(ctx0, inpL, hparams,
  13273. model.layers[il].attn_norm, NULL,
  13274. LLM_NORM_RMS, cb, il);
  13275. cb(cur, "attn_norm", il);
  13276. // self_attention
  13277. {
  13278. struct ggml_tensor * q = NULL;
  13279. if (!is_lite) {
  13280. // {n_embd, q_lora_rank} * {n_embd, n_tokens} -> {q_lora_rank, n_tokens}
  13281. q = ggml_mul_mat(ctx0, model.layers[il].wq_a, cur);
  13282. cb(q, "q", il);
  13283. q = llm_build_norm(ctx0, q, hparams,
  13284. model.layers[il].attn_q_a_norm, NULL,
  13285. LLM_NORM_RMS, cb, il);
  13286. cb(q, "q", il);
  13287. // {q_lora_rank, n_head * hparams.n_embd_head_k} * {q_lora_rank, n_tokens} -> {n_head * hparams.n_embd_head_k, n_tokens}
  13288. q = ggml_mul_mat(ctx0, model.layers[il].wq_b, q);
  13289. cb(q, "q", il);
  13290. } else {
  13291. q = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  13292. cb(q, "q", il);
  13293. }
  13294. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  13295. struct ggml_tensor * q_nope = ggml_view_3d(ctx0, q, n_embd_head_qk_nope, n_head, n_tokens,
  13296. ggml_row_size(q->type, hparams.n_embd_head_k),
  13297. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  13298. 0);
  13299. cb(q_nope, "q_nope", il);
  13300. // and {n_head * n_embd_head_qk_rope, n_tokens}
  13301. struct ggml_tensor * q_pe = ggml_view_3d(ctx0, q, n_embd_head_qk_rope, n_head, n_tokens,
  13302. ggml_row_size(q->type, hparams.n_embd_head_k),
  13303. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  13304. ggml_row_size(q->type, n_embd_head_qk_nope));
  13305. cb(q_pe, "q_pe", il);
  13306. // {n_embd, kv_lora_rank + n_embd_head_qk_rope} * {n_embd, n_tokens} -> {kv_lora_rank + n_embd_head_qk_rope, n_tokens}
  13307. struct ggml_tensor * kv_pe_compresseed = ggml_mul_mat(ctx0, model.layers[il].wkv_a_mqa, cur);
  13308. cb(kv_pe_compresseed, "kv_pe_compresseed", il);
  13309. // split into {kv_lora_rank, n_tokens}
  13310. struct ggml_tensor * kv_compressed = ggml_view_2d(ctx0, kv_pe_compresseed, kv_lora_rank, n_tokens,
  13311. kv_pe_compresseed->nb[1],
  13312. 0);
  13313. cb(kv_compressed, "kv_compressed", il);
  13314. // and {n_embd_head_qk_rope, n_tokens}
  13315. struct ggml_tensor * k_pe = ggml_view_3d(ctx0, kv_pe_compresseed, n_embd_head_qk_rope, 1, n_tokens,
  13316. kv_pe_compresseed->nb[1],
  13317. kv_pe_compresseed->nb[1],
  13318. ggml_row_size(kv_pe_compresseed->type, kv_lora_rank));
  13319. cb(k_pe, "k_pe", il);
  13320. kv_compressed = ggml_cont(ctx0, kv_compressed); // TODO: the CUDA backend does not support non-contiguous norm
  13321. kv_compressed = llm_build_norm(ctx0, kv_compressed, hparams,
  13322. model.layers[il].attn_kv_a_norm, NULL,
  13323. LLM_NORM_RMS, cb, il);
  13324. cb(kv_compressed, "kv_compressed", il);
  13325. // {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}
  13326. struct ggml_tensor * kv = ggml_mul_mat(ctx0, model.layers[il].wkv_b, kv_compressed);
  13327. cb(kv, "kv", il);
  13328. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  13329. struct ggml_tensor * k_nope = ggml_view_3d(ctx0, kv, n_embd_head_qk_nope, n_head, n_tokens,
  13330. ggml_row_size(kv->type, n_embd_head_qk_nope + hparams.n_embd_head_v),
  13331. ggml_row_size(kv->type, n_head * (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  13332. 0);
  13333. cb(k_nope, "k_nope", il);
  13334. // and {n_head * n_embd_head_v, n_tokens}
  13335. struct ggml_tensor * v_states = ggml_view_3d(ctx0, kv, hparams.n_embd_head_v, n_head, n_tokens,
  13336. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  13337. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)*n_head),
  13338. ggml_row_size(kv->type, (n_embd_head_qk_nope)));
  13339. cb(v_states, "v_states", il);
  13340. v_states = ggml_cont(ctx0, v_states);
  13341. cb(v_states, "v_states", il);
  13342. v_states = ggml_view_2d(ctx0, v_states, hparams.n_embd_head_v * n_head, n_tokens,
  13343. ggml_row_size(kv->type, hparams.n_embd_head_v * n_head),
  13344. 0);
  13345. cb(v_states, "v_states", il);
  13346. q_pe = ggml_cont(ctx0, q_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  13347. q_pe = ggml_rope_ext(
  13348. ctx0, q_pe, inp_pos, nullptr,
  13349. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13350. ext_factor, attn_factor_scaled, beta_fast, beta_slow
  13351. );
  13352. cb(q_pe, "q_pe", il);
  13353. // shared RoPE key
  13354. k_pe = ggml_cont(ctx0, k_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  13355. k_pe = ggml_rope_ext(
  13356. ctx0, k_pe, inp_pos, nullptr,
  13357. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13358. ext_factor, attn_factor_scaled, beta_fast, beta_slow
  13359. );
  13360. cb(k_pe, "k_pe", il);
  13361. struct ggml_tensor * q_states = ggml_concat(ctx0, q_nope, q_pe, 0);
  13362. cb(q_states, "q_states", il);
  13363. struct ggml_tensor * k_states = ggml_concat(ctx0, k_nope, ggml_repeat(ctx0, k_pe, q_pe), 0);
  13364. cb(k_states, "k_states", il);
  13365. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13366. model.layers[il].wo, NULL,
  13367. k_states, v_states, q_states, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  13368. }
  13369. if (il == n_layer - 1) {
  13370. // skip computing output for unused tokens
  13371. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13372. n_tokens = n_outputs;
  13373. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13374. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13375. }
  13376. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13377. cb(ffn_inp, "ffn_inp", il);
  13378. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13379. model.layers[il].ffn_norm, NULL,
  13380. LLM_NORM_RMS, cb, il);
  13381. cb(cur, "ffn_norm", il);
  13382. if ((uint32_t) il < hparams.n_layer_dense_lead) {
  13383. cur = llm_build_ffn(ctx0, lctx, cur,
  13384. model.layers[il].ffn_up, NULL, NULL,
  13385. model.layers[il].ffn_gate, NULL, NULL,
  13386. model.layers[il].ffn_down, NULL, NULL,
  13387. NULL,
  13388. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13389. cb(cur, "ffn_out", il);
  13390. } else {
  13391. // MoE branch
  13392. ggml_tensor * moe_out =
  13393. llm_build_moe_ffn(ctx0, lctx, cur,
  13394. model.layers[il].ffn_gate_inp,
  13395. model.layers[il].ffn_up_exps,
  13396. model.layers[il].ffn_gate_exps,
  13397. model.layers[il].ffn_down_exps,
  13398. n_expert, n_expert_used,
  13399. LLM_FFN_SILU, false,
  13400. true, hparams.expert_weights_scale,
  13401. cb, il);
  13402. cb(moe_out, "ffn_moe_out", il);
  13403. // FFN shared expert
  13404. {
  13405. ggml_tensor * ffn_shexp = llm_build_ffn(ctx0, lctx, cur,
  13406. model.layers[il].ffn_up_shexp, NULL, NULL,
  13407. model.layers[il].ffn_gate_shexp, NULL, NULL,
  13408. model.layers[il].ffn_down_shexp, NULL, NULL,
  13409. NULL,
  13410. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13411. cb(ffn_shexp, "ffn_shexp", il);
  13412. cur = ggml_add(ctx0, moe_out, ffn_shexp);
  13413. cb(cur, "ffn_out", il);
  13414. }
  13415. }
  13416. cur = ggml_add(ctx0, cur, ffn_inp);
  13417. cur = lctx.cvec.apply_to(ctx0, cur, il);
  13418. cb(cur, "l_out", il);
  13419. // input for next layer
  13420. inpL = cur;
  13421. }
  13422. cur = inpL;
  13423. cur = llm_build_norm(ctx0, cur, hparams,
  13424. model.output_norm, NULL,
  13425. LLM_NORM_RMS, cb, -1);
  13426. cb(cur, "result_norm", -1);
  13427. // lm_head
  13428. cur = ggml_mul_mat(ctx0, model.output, cur);
  13429. cb(cur, "result_output", -1);
  13430. ggml_build_forward_expand(gf, cur);
  13431. return gf;
  13432. }
  13433. struct ggml_cgraph * build_bitnet() {
  13434. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13435. const int64_t n_embd_head = hparams.n_embd_head_v;
  13436. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13437. struct ggml_tensor * cur;
  13438. struct ggml_tensor * inpL;
  13439. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13440. // inp_pos - contains the positions
  13441. struct ggml_tensor * inp_pos = build_inp_pos();
  13442. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13443. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13444. for (int il = 0; il < n_layer; ++il) {
  13445. struct ggml_tensor * inpSA = inpL;
  13446. cur = llm_build_norm(ctx0, inpL, hparams,
  13447. model.layers[il].attn_norm, NULL,
  13448. LLM_NORM_RMS, cb, il);
  13449. cb(cur, "attn_norm", il);
  13450. // self-attention
  13451. {
  13452. // compute Q and K and RoPE them
  13453. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  13454. if (model.layers[il].wq_scale) {
  13455. Qcur = ggml_mul(ctx0, Qcur, model.layers[il].wq_scale);
  13456. }
  13457. cb(Qcur, "Qcur", il);
  13458. if (model.layers[il].bq) {
  13459. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  13460. cb(Qcur, "Qcur", il);
  13461. }
  13462. // B1.K
  13463. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  13464. if (model.layers[il].wk_scale) {
  13465. Kcur = ggml_mul(ctx0, Kcur, model.layers[il].wk_scale);
  13466. }
  13467. cb(Kcur, "Kcur", il);
  13468. if (model.layers[il].bk) {
  13469. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  13470. cb(Kcur, "Kcur", il);
  13471. }
  13472. // B1.V
  13473. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  13474. if (model.layers[il].wv_scale) {
  13475. Vcur = ggml_mul(ctx0, Vcur, model.layers[il].wv_scale);
  13476. }
  13477. cb(Vcur, "Vcur", il);
  13478. if (model.layers[il].bv) {
  13479. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  13480. cb(Vcur, "Vcur", il);
  13481. }
  13482. Qcur = ggml_rope_ext(
  13483. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  13484. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13485. ext_factor, attn_factor, beta_fast, beta_slow
  13486. );
  13487. cb(Qcur, "Qcur", il);
  13488. Kcur = ggml_rope_ext(
  13489. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  13490. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13491. ext_factor, attn_factor, beta_fast, beta_slow
  13492. );
  13493. cb(Kcur, "Kcur", il);
  13494. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13495. NULL, NULL,
  13496. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13497. cur = llm_build_norm(ctx0, cur, hparams,
  13498. model.layers[il].attn_sub_norm, NULL,
  13499. LLM_NORM_RMS, cb, il);
  13500. cb(cur, "attn_sub_norm", il);
  13501. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  13502. if (model.layers[il].wo_scale) {
  13503. cur = ggml_mul(ctx0, cur, model.layers[il].wo_scale);
  13504. }
  13505. if (model.layers[il].bo) {
  13506. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  13507. }
  13508. cb(cur, "attn_o_out", il);
  13509. }
  13510. if (il == n_layer - 1) {
  13511. // skip computing output for unused tokens
  13512. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13513. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13514. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13515. }
  13516. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13517. cb(ffn_inp, "ffn_inp", il);
  13518. // feed-forward forward
  13519. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13520. model.layers[il].ffn_norm, NULL,
  13521. LLM_NORM_RMS, cb, il);
  13522. cb(cur, "ffn_norm", il);
  13523. cur = llm_build_ffn(ctx0, lctx, cur,
  13524. model.layers[il].ffn_up, NULL, model.layers[il].ffn_up_scale,
  13525. model.layers[il].ffn_gate, NULL, model.layers[il].ffn_gate_scale,
  13526. NULL, NULL, NULL,
  13527. NULL,
  13528. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13529. cb(cur, "ffn_sub_out", il);
  13530. cur = llm_build_norm(ctx0, cur, hparams,
  13531. model.layers[il].ffn_sub_norm, NULL,
  13532. LLM_NORM_RMS, cb, il);
  13533. cb(cur, "ffn_sub_norm", il);
  13534. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].ffn_down, cur);
  13535. if (model.layers[il].ffn_down_scale) {
  13536. cur = ggml_mul(ctx0, cur, model.layers[il].ffn_down_scale);
  13537. }
  13538. cb(cur, "ffn_down", il);
  13539. cur = ggml_add(ctx0, cur, ffn_inp);
  13540. cb(cur, "l_out", il);
  13541. // input for next layer
  13542. inpL = cur;
  13543. }
  13544. cur = inpL;
  13545. cur = llm_build_norm(ctx0, cur, hparams,
  13546. model.output_norm, NULL,
  13547. LLM_NORM_RMS, cb, -1);
  13548. cb(cur, "result_norm", -1);
  13549. // lm_head
  13550. // FIXME: do not use model.tok_embd directly, duplicate as model.output
  13551. cur = llm_build_lora_mm(lctx, ctx0, model.tok_embd, cur);
  13552. cb(cur, "result_output", -1);
  13553. ggml_build_forward_expand(gf, cur);
  13554. return gf;
  13555. }
  13556. struct ggml_cgraph * build_t5_encoder() {
  13557. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13558. // mutable variable, needed during the last layer of the computation to skip unused tokens
  13559. int32_t n_tokens = this->n_tokens;
  13560. const int64_t n_embd_head = hparams.n_embd_head_v;
  13561. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  13562. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13563. struct ggml_tensor * cur;
  13564. struct ggml_tensor * inpL;
  13565. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13566. GGML_ASSERT(lctx.is_encoding);
  13567. struct ggml_tensor * pos_bucket_enc = llm_build_pos_bucket(false);
  13568. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13569. struct ggml_tensor * KQ_mask_enc = build_inp_KQ_mask(false);
  13570. for (int il = 0; il < n_layer; ++il) {
  13571. struct ggml_tensor * inpSA = inpL;
  13572. // norm
  13573. cur = llm_build_norm(ctx0, inpL, hparams,
  13574. model.layers[il].attn_norm_enc, NULL,
  13575. LLM_NORM_RMS, cb, il);
  13576. cb(cur, "attn_norm", il);
  13577. // self-attention
  13578. {
  13579. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq_enc, cur);
  13580. cb(Qcur, "Qcur", il);
  13581. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk_enc, cur);
  13582. cb(Kcur, "Kcur", il);
  13583. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv_enc, cur);
  13584. cb(Vcur, "Vcur", il);
  13585. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  13586. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  13587. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  13588. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  13589. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  13590. cb(kq, "kq", il);
  13591. 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;
  13592. struct ggml_tensor * pos_bias = llm_build_pos_bias(pos_bucket_enc, attn_rel_b);
  13593. struct ggml_tensor * kq_b = ggml_add(ctx0, kq, pos_bias);
  13594. cb(kq_b, "kq_b", il);
  13595. kq = ggml_soft_max_ext(ctx0, kq_b, KQ_mask_enc, 1.0f, hparams.f_max_alibi_bias);
  13596. cb(kq, "kq_soft_max_ext", il);
  13597. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  13598. cb(v, "v", il);
  13599. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  13600. cb(kqv, "kqv", il);
  13601. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  13602. cb(kqv_merged, "kqv_merged", il);
  13603. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  13604. cb(cur, "kqv_merged_cont", il);
  13605. ggml_build_forward_expand(gf, cur);
  13606. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo_enc, cur);
  13607. cb(cur, "kqv_out", il);
  13608. }
  13609. if (il == n_layer - 1) {
  13610. // skip computing output for unused tokens
  13611. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13612. n_tokens = n_outputs;
  13613. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13614. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13615. }
  13616. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13617. cb(ffn_inp, "ffn_inp", il);
  13618. // feed-forward network
  13619. {
  13620. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13621. model.layers[il].ffn_norm_enc, NULL,
  13622. LLM_NORM_RMS, cb, il);
  13623. cb(cur, "ffn_norm", il);
  13624. // T5 uses relu, flan-T5 uses gelu-gated
  13625. cur = llm_build_ffn(ctx0, lctx, cur,
  13626. model.layers[il].ffn_up_enc, NULL, NULL,
  13627. model.layers[il].ffn_gate_enc, NULL, NULL,
  13628. model.layers[il].ffn_down_enc, NULL, NULL,
  13629. NULL,
  13630. model.layers[il].ffn_gate_enc ? LLM_FFN_GELU : LLM_FFN_RELU,
  13631. model.layers[il].ffn_gate_enc ? LLM_FFN_PAR : LLM_FFN_SEQ,
  13632. cb, il);
  13633. cb(cur, "ffn_out", il);
  13634. }
  13635. cur = ggml_add(ctx0, cur, ffn_inp);
  13636. cb(cur, "ffn_out", il);
  13637. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  13638. if (layer_dir != nullptr) {
  13639. cur = ggml_add(ctx0, cur, layer_dir);
  13640. }
  13641. cb(cur, "l_out", il);
  13642. // input for next layer
  13643. inpL = cur;
  13644. }
  13645. cur = inpL;
  13646. cb(cur, "result_embd", -1);
  13647. cur = llm_build_norm(ctx0, cur, hparams,
  13648. model.output_norm_enc, NULL,
  13649. LLM_NORM_RMS, cb, -1);
  13650. cb(cur, "result_norm", -1);
  13651. ggml_build_forward_expand(gf, cur);
  13652. return gf;
  13653. }
  13654. struct ggml_cgraph * build_t5_decoder() {
  13655. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13656. // mutable variable, needed during the last layer of the computation to skip unused tokens
  13657. int32_t n_tokens = this->n_tokens;
  13658. const int64_t n_embd_head = hparams.n_embd_head_v;
  13659. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  13660. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13661. struct ggml_tensor * cur;
  13662. struct ggml_tensor * inpL;
  13663. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13664. GGML_ASSERT(!lctx.is_encoding);
  13665. GGML_ASSERT(n_outputs_enc > 0 && "call llama_encode() first");
  13666. struct ggml_tensor * embd_enc = llm_build_inp_embd_enc();
  13667. struct ggml_tensor * pos_bucket_dec = llm_build_pos_bucket(true);
  13668. struct ggml_tensor * KQ_mask_dec = build_inp_KQ_mask();
  13669. struct ggml_tensor * KQ_mask_cross = llm_build_inp_KQ_mask_cross();
  13670. for (int il = 0; il < n_layer; ++il) {
  13671. struct ggml_tensor * inpSA = inpL;
  13672. // norm
  13673. cur = llm_build_norm(ctx0, inpL, hparams,
  13674. model.layers[il].attn_norm, NULL,
  13675. LLM_NORM_RMS, cb, il);
  13676. cb(cur, "attn_norm", il);
  13677. // self-attention
  13678. {
  13679. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  13680. cb(Qcur, "Qcur", il);
  13681. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  13682. cb(Kcur, "Kcur", il);
  13683. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  13684. cb(Vcur, "Vcur", il);
  13685. llm_build_kv_store(ctx0, hparams, cparams, kv_self, gf, Kcur, Vcur, n_tokens, kv_head, cb, il);
  13686. struct ggml_tensor * k =
  13687. ggml_view_3d(ctx0, kv_self.k_l[il],
  13688. n_embd_head_k, n_kv, n_head_kv,
  13689. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  13690. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  13691. 0);
  13692. cb(k, "k", il);
  13693. struct ggml_tensor * v =
  13694. ggml_view_3d(ctx0, kv_self.v_l[il],
  13695. n_kv, n_embd_head_v, n_head_kv,
  13696. ggml_element_size(kv_self.v_l[il])*n_ctx,
  13697. ggml_element_size(kv_self.v_l[il])*n_ctx*n_embd_head_v,
  13698. 0);
  13699. cb(v, "v", il);
  13700. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  13701. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  13702. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  13703. cb(kq, "kq", il);
  13704. struct ggml_tensor * attn_rel_b = model.layers[il].attn_rel_b ? model.layers[il].attn_rel_b : model.layers[0].attn_rel_b;
  13705. struct ggml_tensor * pos_bias = llm_build_pos_bias(pos_bucket_dec, attn_rel_b);
  13706. struct ggml_tensor * kq_b = ggml_add(ctx0, kq, pos_bias);
  13707. cb(kq_b, "kq_b", il);
  13708. kq = ggml_soft_max_ext(ctx0, kq_b, KQ_mask_dec, 1.0f, hparams.f_max_alibi_bias);
  13709. cb(kq, "kq_soft_max_ext", il);
  13710. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, v, kq);
  13711. cb(kqv, "kqv", il);
  13712. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  13713. cb(kqv_merged, "kqv_merged", il);
  13714. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  13715. cb(cur, "kqv_merged_cont", il);
  13716. ggml_build_forward_expand(gf, cur);
  13717. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  13718. cb(cur, "kqv_out", il);
  13719. }
  13720. cur = ggml_add(ctx0, cur, inpSA);
  13721. cb(cur, "cross_inp", il);
  13722. struct ggml_tensor * inpCA = cur;
  13723. // norm
  13724. cur = llm_build_norm(ctx0, cur, hparams,
  13725. model.layers[il].attn_norm_cross, NULL,
  13726. LLM_NORM_RMS, cb, il);
  13727. cb(cur, "attn_norm_cross", il);
  13728. // cross-attention
  13729. {
  13730. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq_cross, cur);
  13731. cb(Qcur, "Qcur", il);
  13732. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk_cross, embd_enc);
  13733. cb(Kcur, "Kcur", il);
  13734. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv_cross, embd_enc);
  13735. cb(Vcur, "Vcur", il);
  13736. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  13737. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_outputs_enc);
  13738. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  13739. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  13740. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  13741. cb(kq, "kq", il);
  13742. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask_cross, 1.0f, hparams.f_max_alibi_bias);
  13743. cb(kq, "kq_soft_max_ext", il);
  13744. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_outputs_enc)));
  13745. cb(v, "v", il);
  13746. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_outputs_enc, n_embd_head, n_head_kv), kq);
  13747. cb(kqv, "kqv", il);
  13748. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  13749. cb(kqv_merged, "kqv_merged", il);
  13750. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  13751. cb(cur, "kqv_merged_cont", il);
  13752. ggml_build_forward_expand(gf, cur);
  13753. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo_cross, cur);
  13754. cb(cur, "kqv_out", il);
  13755. }
  13756. if (il == n_layer - 1) {
  13757. // skip computing output for unused tokens
  13758. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13759. n_tokens = n_outputs;
  13760. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13761. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13762. inpCA = ggml_get_rows(ctx0, inpCA, inp_out_ids);
  13763. }
  13764. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpCA);
  13765. cb(ffn_inp, "ffn_inp", il);
  13766. // feed-forward network
  13767. {
  13768. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13769. model.layers[il].ffn_norm, NULL,
  13770. LLM_NORM_RMS, cb, il);
  13771. cb(cur, "ffn_norm", il);
  13772. // T5 uses relu, flan-T5 uses gelu-gated
  13773. cur = llm_build_ffn(ctx0, lctx, cur,
  13774. model.layers[il].ffn_up, NULL, NULL,
  13775. model.layers[il].ffn_gate, NULL, NULL,
  13776. model.layers[il].ffn_down, NULL, NULL,
  13777. NULL,
  13778. model.layers[il].ffn_gate_enc ? LLM_FFN_GELU : LLM_FFN_RELU,
  13779. model.layers[il].ffn_gate_enc ? LLM_FFN_PAR : LLM_FFN_SEQ,
  13780. cb, il);
  13781. cb(cur, "ffn_out", il);
  13782. }
  13783. cur = ggml_add(ctx0, cur, ffn_inp);
  13784. cb(cur, "ffn_out", il);
  13785. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  13786. if (layer_dir != nullptr) {
  13787. cur = ggml_add(ctx0, cur, layer_dir);
  13788. }
  13789. cb(cur, "l_out", il);
  13790. // input for next layer
  13791. inpL = cur;
  13792. }
  13793. cur = inpL;
  13794. cb(cur, "result_embd", -1);
  13795. cur = llm_build_norm(ctx0, cur, hparams,
  13796. model.output_norm, NULL,
  13797. LLM_NORM_RMS, cb, -1);
  13798. cb(cur, "result_norm", -1);
  13799. // lm_head
  13800. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13801. cb(cur, "result_output", -1);
  13802. ggml_build_forward_expand(gf, cur);
  13803. return gf;
  13804. }
  13805. struct ggml_cgraph * build_jais() {
  13806. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13807. const int64_t n_embd_head = hparams.n_embd_head_v;
  13808. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  13809. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13810. struct ggml_tensor * cur;
  13811. struct ggml_tensor * inpL;
  13812. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13813. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13814. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13815. for (int il = 0; il < n_layer; ++il) {
  13816. cur = llm_build_norm(ctx0, inpL, hparams,
  13817. model.layers[il].attn_norm,
  13818. model.layers[il].attn_norm_b,
  13819. LLM_NORM, cb, il);
  13820. cb(cur, "attn_norm", il);
  13821. // self-attention
  13822. {
  13823. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  13824. cb(cur, "wqkv", il);
  13825. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  13826. cb(cur, "bqkv", il);
  13827. 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)));
  13828. 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)));
  13829. 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)));
  13830. cb(Qcur, "Qcur", il);
  13831. cb(Kcur, "Kcur", il);
  13832. cb(Vcur, "Vcur", il);
  13833. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  13834. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13835. model.layers[il].wo, model.layers[il].bo,
  13836. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/float(n_embd_head), cb, il);
  13837. }
  13838. if (il == n_layer - 1) {
  13839. // skip computing output for unused tokens
  13840. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13841. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13842. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  13843. }
  13844. // add the input
  13845. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  13846. cb(ffn_inp, "ffn_inp", il);
  13847. // FF
  13848. {
  13849. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13850. model.layers[il].ffn_norm,
  13851. model.layers[il].ffn_norm_b,
  13852. LLM_NORM, cb, il);
  13853. cb(cur, "ffn_norm", il);
  13854. cur = llm_build_ffn(ctx0, lctx, cur,
  13855. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  13856. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  13857. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  13858. NULL,
  13859. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13860. cb(cur, "ffn_out", il);
  13861. }
  13862. inpL = ggml_add(ctx0, cur, ffn_inp);
  13863. cb(inpL, "l_out", il);
  13864. }
  13865. cur = llm_build_norm(ctx0, inpL, hparams,
  13866. model.output_norm,
  13867. model.output_norm_b,
  13868. LLM_NORM, cb, -1);
  13869. cb(cur, "result_norm", -1);
  13870. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13871. cb(cur, "result_output", -1);
  13872. ggml_build_forward_expand(gf, cur);
  13873. return gf;
  13874. }
  13875. struct ggml_cgraph * build_chatglm() {
  13876. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13877. const int64_t n_embd_head = hparams.n_embd_head_v;
  13878. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  13879. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13880. struct ggml_tensor * cur;
  13881. struct ggml_tensor * inpL;
  13882. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13883. // inp_pos - contains the positions
  13884. struct ggml_tensor * inp_pos = build_inp_pos();
  13885. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13886. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13887. for (int il = 0; il < n_layer; ++il) {
  13888. struct ggml_tensor * inpSA = inpL;
  13889. cur = llm_build_norm(ctx0, inpL, hparams,
  13890. model.layers[il].attn_norm,
  13891. NULL,
  13892. LLM_NORM_RMS, cb, il);
  13893. cb(cur, "attn_norm", il);
  13894. // self-attention
  13895. {
  13896. struct ggml_tensor * Qcur = nullptr;
  13897. struct ggml_tensor * Kcur = nullptr;
  13898. struct ggml_tensor * Vcur = nullptr;
  13899. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  13900. cb(cur, "wqkv", il);
  13901. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  13902. cb(cur, "bqkv", il);
  13903. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  13904. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  13905. 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)));
  13906. cb(Qcur, "Qcur", il);
  13907. cb(Kcur, "Kcur", il);
  13908. cb(Vcur, "Vcur", il);
  13909. //printf("freq_base: %f freq_scale: %f ext_factor: %f attn_factor: %f\n", freq_base, freq_scale, ext_factor, attn_factor);
  13910. Qcur = ggml_rope_ext(
  13911. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  13912. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13913. ext_factor, attn_factor, beta_fast, beta_slow
  13914. );
  13915. cb(Qcur, "Qcur_rope", il);
  13916. Kcur = ggml_rope_ext(
  13917. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  13918. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13919. ext_factor, attn_factor, beta_fast, beta_slow
  13920. );
  13921. cb(Kcur, "Kcur_rope", il);
  13922. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13923. model.layers[il].wo, NULL,
  13924. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13925. }
  13926. if (il == n_layer - 1) {
  13927. // skip computing output for unused tokens
  13928. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13929. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13930. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13931. }
  13932. // Add the input
  13933. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13934. cb(ffn_inp, "ffn_inp", il);
  13935. // FF
  13936. {
  13937. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13938. model.layers[il].ffn_norm,
  13939. NULL,
  13940. LLM_NORM_RMS, cb, il);
  13941. cb(cur, "ffn_norm", il);
  13942. cur = llm_build_ffn(ctx0, lctx, cur,
  13943. model.layers[il].ffn_up, NULL, NULL,
  13944. NULL, NULL, NULL,
  13945. model.layers[il].ffn_down, NULL, NULL,
  13946. NULL,
  13947. LLM_FFN_SWIGLU, LLM_FFN_SEQ, cb, il);
  13948. cb(cur, "ffn_out", il);
  13949. }
  13950. inpL = ggml_add(ctx0, cur, ffn_inp);
  13951. cb(inpL, "l_out", il);
  13952. }
  13953. cur = llm_build_norm(ctx0, inpL, hparams,
  13954. model.output_norm,
  13955. NULL,
  13956. LLM_NORM_RMS, cb, -1);
  13957. cb(cur, "result_norm", -1);
  13958. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13959. cb(cur, "result_output", -1);
  13960. ggml_build_forward_expand(gf, cur);
  13961. return gf;
  13962. }
  13963. struct ggml_cgraph * build_nemotron() {
  13964. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13965. const int64_t n_embd_head = hparams.n_embd_head_v;
  13966. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13967. //GGML_ASSERT(n_embd_head == hparams.n_rot);
  13968. struct ggml_tensor * cur;
  13969. struct ggml_tensor * inpL;
  13970. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  13971. // inp_pos - contains the positions
  13972. struct ggml_tensor * inp_pos = build_inp_pos();
  13973. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13974. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13975. for (int il = 0; il < n_layer; ++il) {
  13976. struct ggml_tensor * inpSA = inpL;
  13977. // norm
  13978. cur = llm_build_norm(ctx0, inpL, hparams,
  13979. model.layers[il].attn_norm,
  13980. model.layers[il].attn_norm_b,
  13981. LLM_NORM, cb, il);
  13982. cb(cur, "attn_norm", il);
  13983. // self-attention
  13984. {
  13985. // compute Q and K and RoPE them
  13986. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  13987. cb(Qcur, "Qcur", il);
  13988. if (model.layers[il].bq) {
  13989. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  13990. cb(Qcur, "Qcur", il);
  13991. }
  13992. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  13993. cb(Kcur, "Kcur", il);
  13994. if (model.layers[il].bk) {
  13995. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  13996. cb(Kcur, "Kcur", il);
  13997. }
  13998. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  13999. cb(Vcur, "Vcur", il);
  14000. if (model.layers[il].bv) {
  14001. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  14002. cb(Vcur, "Vcur", il);
  14003. }
  14004. Qcur = ggml_rope_ext(
  14005. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  14006. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  14007. ext_factor, attn_factor, beta_fast, beta_slow
  14008. );
  14009. cb(Qcur, "Qcur", il);
  14010. Kcur = ggml_rope_ext(
  14011. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  14012. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  14013. ext_factor, attn_factor, beta_fast, beta_slow
  14014. );
  14015. cb(Kcur, "Kcur", il);
  14016. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  14017. model.layers[il].wo, model.layers[il].bo,
  14018. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  14019. }
  14020. if (il == n_layer - 1) {
  14021. // skip computing output for unused tokens
  14022. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  14023. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  14024. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  14025. }
  14026. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  14027. cb(ffn_inp, "ffn_inp", il);
  14028. // feed-forward network
  14029. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  14030. model.layers[il].ffn_norm,
  14031. model.layers[il].ffn_norm_b,
  14032. LLM_NORM, cb, il);
  14033. cb(cur, "ffn_norm", il);
  14034. cur = llm_build_ffn(ctx0, lctx, cur,
  14035. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  14036. NULL, NULL, NULL,
  14037. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  14038. NULL,
  14039. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  14040. cur = ggml_add(ctx0, cur, ffn_inp);
  14041. cb(cur, "ffn_out", il);
  14042. cur = lctx.cvec.apply_to(ctx0, cur, il);
  14043. cb(cur, "l_out", il);
  14044. // input for next layer
  14045. inpL = cur;
  14046. }
  14047. cur = inpL;
  14048. cur = llm_build_norm(ctx0, cur, hparams,
  14049. model.output_norm, model.output_norm_b,
  14050. LLM_NORM, cb, -1);
  14051. cb(cur, "result_norm", -1);
  14052. // lm_head
  14053. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  14054. cb(cur, "result_output", -1);
  14055. ggml_build_forward_expand(gf, cur);
  14056. return gf;
  14057. }
  14058. struct ggml_cgraph * build_exaone() {
  14059. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  14060. // mutable variable, needed during the last layer of the computation to skip unused tokens
  14061. int32_t n_tokens = this->n_tokens;
  14062. const int64_t n_embd_head = hparams.n_embd_head_v;
  14063. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  14064. GGML_ASSERT(n_embd_head == hparams.n_rot);
  14065. struct ggml_tensor * cur;
  14066. struct ggml_tensor * inpL;
  14067. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  14068. // inp_pos - contains the positions
  14069. struct ggml_tensor * inp_pos = build_inp_pos();
  14070. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  14071. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  14072. for (int il = 0; il < n_layer; ++il) {
  14073. struct ggml_tensor * inpSA = inpL;
  14074. // norm
  14075. cur = llm_build_norm(ctx0, inpL, hparams,
  14076. model.layers[il].attn_norm, NULL,
  14077. LLM_NORM_RMS, cb, il);
  14078. cb(cur, "attn_norm", il);
  14079. // self-attention
  14080. {
  14081. // rope freq factors for llama3; may return nullptr for llama2 and other models
  14082. struct ggml_tensor * rope_factors = build_rope_factors(il);
  14083. // compute Q and K and RoPE them
  14084. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  14085. cb(Qcur, "Qcur", il);
  14086. if (model.layers[il].bq) {
  14087. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  14088. cb(Qcur, "Qcur", il);
  14089. }
  14090. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  14091. cb(Kcur, "Kcur", il);
  14092. if (model.layers[il].bk) {
  14093. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  14094. cb(Kcur, "Kcur", il);
  14095. }
  14096. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  14097. cb(Vcur, "Vcur", il);
  14098. if (model.layers[il].bv) {
  14099. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  14100. cb(Vcur, "Vcur", il);
  14101. }
  14102. Qcur = ggml_rope_ext(
  14103. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  14104. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  14105. ext_factor, attn_factor, beta_fast, beta_slow
  14106. );
  14107. cb(Qcur, "Qcur", il);
  14108. Kcur = ggml_rope_ext(
  14109. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  14110. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  14111. ext_factor, attn_factor, beta_fast, beta_slow
  14112. );
  14113. cb(Kcur, "Kcur", il);
  14114. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  14115. model.layers[il].wo, model.layers[il].bo,
  14116. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  14117. }
  14118. if (il == n_layer - 1) {
  14119. // skip computing output for unused tokens
  14120. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  14121. n_tokens = n_outputs;
  14122. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  14123. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  14124. }
  14125. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  14126. cb(ffn_inp, "ffn_inp", il);
  14127. // feed-forward network
  14128. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  14129. model.layers[il].ffn_norm, NULL,
  14130. LLM_NORM_RMS, cb, il);
  14131. cb(cur, "ffn_norm", il);
  14132. cur = llm_build_ffn(ctx0, lctx, cur,
  14133. model.layers[il].ffn_up, NULL, NULL,
  14134. model.layers[il].ffn_gate, NULL, NULL,
  14135. model.layers[il].ffn_down, NULL, NULL,
  14136. NULL,
  14137. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  14138. cb(cur, "ffn_out", il);
  14139. cur = ggml_add(ctx0, cur, ffn_inp);
  14140. cb(cur, "ffn_out", il);
  14141. cur = lctx.cvec.apply_to(ctx0, cur, il);
  14142. cb(cur, "l_out", il);
  14143. // input for next layer
  14144. inpL = cur;
  14145. }
  14146. cur = inpL;
  14147. cur = llm_build_norm(ctx0, cur, hparams,
  14148. model.output_norm, NULL,
  14149. LLM_NORM_RMS, cb, -1);
  14150. cb(cur, "result_norm", -1);
  14151. // lm_head
  14152. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  14153. cb(cur, "result_output", -1);
  14154. ggml_build_forward_expand(gf, cur);
  14155. return gf;
  14156. }
  14157. ggml_cgraph * build_rwkv6() {
  14158. ggml_cgraph *gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  14159. // Token shift state dimensions should be 2 * n_emb
  14160. GGML_ASSERT(n_embd == hparams.n_embd_k_s() / 2);
  14161. const int64_t n_seqs = ubatch.n_seqs;
  14162. const int64_t n_seq_tokens = ubatch.n_seq_tokens;
  14163. const int64_t n_tokens = ubatch.n_tokens;
  14164. GGML_ASSERT(n_seqs != 0);
  14165. GGML_ASSERT(ubatch.equal_seqs);
  14166. GGML_ASSERT(n_tokens == n_seq_tokens * n_seqs);
  14167. struct ggml_tensor * cur;
  14168. struct ggml_tensor * inpL;
  14169. struct ggml_tensor * state_copy = build_inp_s_copy();
  14170. struct ggml_tensor * state_mask = build_inp_s_mask();
  14171. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  14172. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  14173. for (int il = 0; il < n_layer; ++il) {
  14174. const llama_layer * layer = &model.layers[il];
  14175. // (ab)using the KV cache to store the states
  14176. struct ggml_tensor * token_shift = llm_build_copy_mask_state(ctx0,
  14177. gf, kv_self.k_l[il], state_copy, state_mask,
  14178. hparams.n_embd_k_s(), kv_self.size, kv_head, n_kv, n_seqs);
  14179. struct ggml_tensor * wkv_states = llm_build_copy_mask_state(ctx0,
  14180. gf, kv_self.v_l[il], state_copy, state_mask,
  14181. hparams.n_embd_v_s(), kv_self.size, kv_head, n_kv, n_seqs);
  14182. cur = ggml_reshape_3d(ctx0, inpL, n_embd, n_seq_tokens, n_seqs);
  14183. token_shift = ggml_reshape_3d(ctx0, token_shift, n_embd, 2, n_seqs);
  14184. 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);
  14185. 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));
  14186. struct ggml_tensor * x_norm_att = llm_build_norm(ctx0, cur, hparams, layer->attn_norm, layer->attn_norm_b, LLM_NORM, cb, il);
  14187. struct ggml_tensor * x_prev = ggml_concat(
  14188. ctx0,
  14189. att_shift,
  14190. 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),
  14191. 1
  14192. );
  14193. cur = ggml_add(ctx0, cur, llm_build_rwkv6_time_mix(lctx, ctx0, layer, x_norm_att, x_prev, &wkv_states));
  14194. ggml_build_forward_expand(gf, cur);
  14195. ggml_build_forward_expand(
  14196. gf,
  14197. ggml_cpy(
  14198. ctx0,
  14199. wkv_states,
  14200. ggml_view_1d(
  14201. ctx0,
  14202. kv_self.v_l[il],
  14203. hparams.n_embd_v_s() * n_seqs,
  14204. hparams.n_embd_v_s() * kv_head * ggml_element_size(kv_self.v_l[il])
  14205. )
  14206. )
  14207. );
  14208. 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);
  14209. x_prev = ggml_concat(
  14210. ctx0,
  14211. ffn_shift,
  14212. 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),
  14213. 1
  14214. );
  14215. cur = ggml_add(ctx0, cur, llm_build_rwkv6_channel_mix(lctx, ctx0, layer, x_norm_ffn, x_prev));
  14216. ggml_build_forward_expand(gf, cur);
  14217. 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));
  14218. 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));
  14219. token_shift = ggml_concat(ctx0, last_norm_att, last_norm_ffn, 1);
  14220. ggml_build_forward_expand(
  14221. gf,
  14222. ggml_cpy(
  14223. ctx0,
  14224. ggml_view_1d(ctx0, token_shift, n_embd * n_seqs * 2, 0),
  14225. 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]))
  14226. )
  14227. );
  14228. if (hparams.rescale_every_n_layers != 0 && (il + 1) % hparams.rescale_every_n_layers == 0) {
  14229. cur = ggml_scale(ctx0, cur, 0.5F);
  14230. }
  14231. cur = lctx.cvec.apply_to(ctx0, cur, il);
  14232. cb(cur, "l_out", il);
  14233. // input for next layer
  14234. inpL = cur;
  14235. }
  14236. cur = inpL;
  14237. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  14238. cur = ggml_reshape_2d(ctx0, cur, n_embd, n_tokens);
  14239. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  14240. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, model.output_norm_b, LLM_NORM, cb, -1);
  14241. cb(cur, "result_norm", -1);
  14242. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  14243. cb(cur, "result_output", -1);
  14244. ggml_build_forward_expand(gf, cur);
  14245. return gf;
  14246. }
  14247. // ref: https://github.com/facebookresearch/chameleon
  14248. // based on the original build_llama() function, changes:
  14249. // * qk-norm
  14250. // * swin-norm
  14251. // * removed bias
  14252. // * removed MoE
  14253. struct ggml_cgraph * build_chameleon() {
  14254. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  14255. // mutable variable, needed during the last layer of the computation to skip unused tokens
  14256. int32_t n_tokens = this->n_tokens;
  14257. const int64_t n_embd_head = hparams.n_embd_head_v;
  14258. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  14259. GGML_ASSERT(n_embd_head == hparams.n_rot);
  14260. struct ggml_tensor * cur;
  14261. struct ggml_tensor * inpL;
  14262. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  14263. // inp_pos - contains the positions
  14264. struct ggml_tensor * inp_pos = build_inp_pos();
  14265. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  14266. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  14267. for (int il = 0; il < n_layer; ++il) {
  14268. struct ggml_tensor * inpSA = inpL;
  14269. // norm
  14270. if (hparams.swin_norm) {
  14271. cur = inpL;
  14272. } else {
  14273. cur = llm_build_norm(ctx0, inpL, hparams,
  14274. model.layers[il].attn_norm, NULL,
  14275. LLM_NORM_RMS, cb, il);
  14276. cb(cur, "attn_norm", il);
  14277. }
  14278. // self-attention
  14279. {
  14280. // compute Q and K and RoPE them
  14281. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  14282. cb(Qcur, "Qcur", il);
  14283. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  14284. cb(Kcur, "Kcur", il);
  14285. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  14286. cb(Vcur, "Vcur", il);
  14287. if (model.layers[il].attn_q_norm) {
  14288. Qcur = ggml_view_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens,
  14289. ggml_element_size(Qcur) * n_embd_head,
  14290. ggml_element_size(Qcur) * n_embd_head * n_head,
  14291. 0);
  14292. cb(Qcur, "Qcur", il);
  14293. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  14294. model.layers[il].attn_q_norm,
  14295. model.layers[il].attn_q_norm_b,
  14296. LLM_NORM, cb, il);
  14297. cb(Qcur, "Qcur", il);
  14298. }
  14299. if (model.layers[il].attn_k_norm) {
  14300. Kcur = ggml_view_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens,
  14301. ggml_element_size(Kcur) * n_embd_head,
  14302. ggml_element_size(Kcur) * n_embd_head * n_head_kv,
  14303. 0);
  14304. cb(Kcur, "Kcur", il);
  14305. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  14306. model.layers[il].attn_k_norm,
  14307. model.layers[il].attn_k_norm_b,
  14308. LLM_NORM, cb, il);
  14309. cb(Kcur, "Kcur", il);
  14310. }
  14311. Qcur = ggml_rope_ext(
  14312. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  14313. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  14314. ext_factor, attn_factor, beta_fast, beta_slow
  14315. );
  14316. cb(Qcur, "Qcur", il);
  14317. Kcur = ggml_rope_ext(
  14318. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  14319. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  14320. ext_factor, attn_factor, beta_fast, beta_slow
  14321. );
  14322. cb(Kcur, "Kcur", il);
  14323. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  14324. model.layers[il].wo, nullptr,
  14325. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  14326. if (hparams.swin_norm) {
  14327. cur = llm_build_norm(ctx0, cur, hparams,
  14328. model.layers[il].attn_norm, NULL,
  14329. LLM_NORM_RMS, cb, il);
  14330. }
  14331. }
  14332. if (il == n_layer - 1) {
  14333. // skip computing output for unused tokens
  14334. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  14335. n_tokens = n_outputs;
  14336. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  14337. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  14338. }
  14339. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  14340. cb(ffn_inp, "ffn_inp", il);
  14341. // feed-forward network
  14342. if (!hparams.swin_norm) {
  14343. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  14344. model.layers[il].ffn_norm, NULL,
  14345. LLM_NORM_RMS, cb, il);
  14346. cb(cur, "ffn_norm", il);
  14347. }
  14348. cur = llm_build_ffn(ctx0, lctx, cur,
  14349. model.layers[il].ffn_up, NULL, NULL,
  14350. model.layers[il].ffn_gate, NULL, NULL,
  14351. model.layers[il].ffn_down, NULL, NULL,
  14352. NULL,
  14353. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  14354. cb(cur, "ffn_out", il);
  14355. if (hparams.swin_norm) {
  14356. cur = llm_build_norm(ctx0, cur, hparams,
  14357. model.layers[il].ffn_norm, NULL,
  14358. LLM_NORM_RMS, cb, il);
  14359. cb(cur, "ffn_norm", il);
  14360. }
  14361. cur = ggml_add(ctx0, cur, ffn_inp);
  14362. cb(cur, "ffn_out", il);
  14363. cur = lctx.cvec.apply_to(ctx0, cur, il);
  14364. cb(cur, "l_out", il);
  14365. // input for next layer
  14366. inpL = cur;
  14367. }
  14368. cur = inpL;
  14369. cur = llm_build_norm(ctx0, cur, hparams,
  14370. model.output_norm, NULL,
  14371. LLM_NORM_RMS, cb, -1);
  14372. cb(cur, "result_norm", -1);
  14373. // lm_head
  14374. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  14375. cb(cur, "result_output_with_img_logits", -1);
  14376. // TODO: this suppresses the output of image tokens, which is required to enable text-only outputs.
  14377. // Needs to be removed once image outputs are supported.
  14378. int img_token_end_idx = 8196;
  14379. int img_token_start_idx = 4;
  14380. int num_img_tokens = img_token_end_idx - img_token_start_idx;
  14381. // creates 1d tensor of size num_img_tokens and values -FLT_MAX,
  14382. // which ensures that text token values are always at least larger than image token values
  14383. struct ggml_tensor * img_logits = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, num_img_tokens);
  14384. img_logits = ggml_clamp(ctx0, img_logits, -FLT_MAX, -FLT_MAX);
  14385. cb(img_logits, "img_logits", -1);
  14386. cur = ggml_set_1d(ctx0, cur, img_logits, ggml_element_size(cur) * img_token_start_idx);
  14387. cb(cur, "result_output", -1);
  14388. ggml_build_forward_expand(gf, cur);
  14389. return gf;
  14390. }
  14391. ggml_cgraph * build_solar() {
  14392. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  14393. // mutable variable, needed during the last layer of the computation to skip unused tokens
  14394. int32_t n_tokens = this->n_tokens;
  14395. const int64_t n_embd_head = hparams.n_embd_head_v;
  14396. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  14397. GGML_ASSERT(n_embd_head == hparams.n_rot);
  14398. struct ggml_tensor * cur;
  14399. struct ggml_tensor * inpL;
  14400. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  14401. // inp_pos - contains the positions
  14402. struct ggml_tensor * inp_pos = build_inp_pos();
  14403. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  14404. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  14405. struct ggml_tensor * bskcn_1;
  14406. struct ggml_tensor * bskcn_2;
  14407. for (int il = 0; il < n_layer; ++il) {
  14408. struct ggml_tensor * inpSA = inpL;
  14409. if (hparams.n_bskcn(0, il)) {
  14410. bskcn_1 = inpSA;
  14411. }
  14412. if (hparams.n_bskcn(1, il)) {
  14413. bskcn_2 = inpSA;
  14414. }
  14415. if (hparams.n_bskcn(2, il)) {
  14416. inpSA = ggml_add(
  14417. ctx0,
  14418. ggml_mul(ctx0, bskcn_1, ggml_view_1d(ctx0, model.layers[il].bskcn_tv, 1, 0)),
  14419. ggml_mul(ctx0, inpSA, ggml_view_1d(ctx0, model.layers[il].bskcn_tv, 1, ggml_element_size(model.layers[il].bskcn_tv))));
  14420. }
  14421. if (hparams.n_bskcn(3, il)) {
  14422. inpSA = ggml_add(
  14423. ctx0,
  14424. ggml_mul(ctx0, bskcn_2, ggml_view_1d(ctx0, model.layers[il].bskcn_tv, 1, 0)),
  14425. ggml_mul(ctx0, inpSA, ggml_view_1d(ctx0, model.layers[il].bskcn_tv, 1, ggml_element_size(model.layers[il].bskcn_tv))));
  14426. }
  14427. // norm
  14428. cur = llm_build_norm(ctx0, inpL, hparams,
  14429. model.layers[il].attn_norm, NULL,
  14430. LLM_NORM_RMS, cb, il);
  14431. cb(cur, "attn_norm", il);
  14432. // self-attention
  14433. {
  14434. // rope freq factors for llama3; may return nullptr for llama2 and other models
  14435. struct ggml_tensor * rope_factors = build_rope_factors(il);
  14436. // compute Q and K and RoPE them
  14437. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  14438. cb(Qcur, "Qcur", il);
  14439. if (model.layers[il].bq) {
  14440. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  14441. cb(Qcur, "Qcur", il);
  14442. }
  14443. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  14444. cb(Kcur, "Kcur", il);
  14445. if (model.layers[il].bk) {
  14446. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  14447. cb(Kcur, "Kcur", il);
  14448. }
  14449. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  14450. cb(Vcur, "Vcur", il);
  14451. if (model.layers[il].bv) {
  14452. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  14453. cb(Vcur, "Vcur", il);
  14454. }
  14455. Qcur = ggml_rope_ext(
  14456. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  14457. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  14458. ext_factor, attn_factor, beta_fast, beta_slow
  14459. );
  14460. cb(Qcur, "Qcur", il);
  14461. Kcur = ggml_rope_ext(
  14462. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  14463. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  14464. ext_factor, attn_factor, beta_fast, beta_slow
  14465. );
  14466. cb(Kcur, "Kcur", il);
  14467. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  14468. model.layers[il].wo, model.layers[il].bo,
  14469. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  14470. }
  14471. if (il == n_layer - 1) {
  14472. // skip computing output for unused tokens
  14473. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  14474. n_tokens = n_outputs;
  14475. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  14476. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  14477. }
  14478. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  14479. cb(ffn_inp, "ffn_inp", il);
  14480. // feed-forward network
  14481. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  14482. model.layers[il].ffn_norm, NULL,
  14483. LLM_NORM_RMS, cb, il);
  14484. cb(cur, "ffn_norm", il);
  14485. cur = llm_build_ffn(ctx0, lctx, cur,
  14486. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  14487. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  14488. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  14489. NULL,
  14490. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  14491. cb(cur, "ffn_out", il);
  14492. cur = ggml_add(ctx0, cur, ffn_inp);
  14493. cb(cur, "ffn_out", il);
  14494. cur = lctx.cvec.apply_to(ctx0, cur, il);
  14495. cb(cur, "l_out", il);
  14496. // input for next layer
  14497. inpL = cur;
  14498. }
  14499. cur = inpL;
  14500. cur = llm_build_norm(ctx0, cur, hparams,
  14501. model.output_norm, NULL,
  14502. LLM_NORM_RMS, cb, -1);
  14503. cb(cur, "result_norm", -1);
  14504. // lm_head
  14505. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  14506. cb(cur, "result_output", -1);
  14507. ggml_build_forward_expand(gf, cur);
  14508. return gf;
  14509. }
  14510. };
  14511. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  14512. llama_ubatch dummy = {};
  14513. dummy.equal_seqs = true;
  14514. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  14515. struct llm_build_context llm(lctx, dummy, cb, false);
  14516. llm.init();
  14517. struct ggml_cgraph * result = llm.build_defrag(ids);
  14518. llm.free();
  14519. return result;
  14520. }
  14521. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  14522. llama_ubatch dummy = {};
  14523. dummy.equal_seqs = true;
  14524. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  14525. struct llm_build_context llm(lctx, dummy, cb, false);
  14526. llm.init();
  14527. struct ggml_cgraph * result = llm.build_k_shift();
  14528. llm.free();
  14529. return result;
  14530. }
  14531. static struct ggml_cgraph * llama_build_graph(
  14532. llama_context & lctx,
  14533. const llama_ubatch & ubatch,
  14534. bool worst_case) {
  14535. const auto & model = lctx.model;
  14536. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  14537. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  14538. if (il >= 0) {
  14539. ggml_format_name(cur, "%s-%d", name, il);
  14540. } else {
  14541. ggml_set_name(cur, name);
  14542. }
  14543. if (!lctx.cparams.offload_kqv) {
  14544. if (strcmp(name, "kqv_merged_cont") == 0) {
  14545. // all nodes between the KV store and the attention output are run on the CPU
  14546. ggml_backend_sched_set_tensor_backend(lctx.sched.get(), cur, lctx.backend_cpu);
  14547. }
  14548. }
  14549. // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
  14550. // FIXME: fix in ggml_backend_sched
  14551. const bool full_offload = lctx.model.n_gpu_layers > (int)lctx.model.hparams.n_layer;
  14552. if (ubatch.n_tokens < 32 || full_offload) {
  14553. if (il != -1 && strcmp(name, "norm") == 0) {
  14554. const auto & dev_layer = lctx.model.dev_layer.at(il);
  14555. for (auto & backend : lctx.backends) {
  14556. if (ggml_backend_get_device(backend.get()) == dev_layer.dev) {
  14557. if (ggml_backend_supports_op(backend.get(), cur)) {
  14558. ggml_backend_sched_set_tensor_backend(lctx.sched.get(), cur, backend.get());
  14559. }
  14560. }
  14561. }
  14562. }
  14563. }
  14564. };
  14565. struct ggml_cgraph * result = NULL;
  14566. struct llm_build_context llm(lctx, ubatch, cb, worst_case);
  14567. llm.init();
  14568. switch (model.arch) {
  14569. case LLM_ARCH_LLAMA:
  14570. case LLM_ARCH_MINICPM:
  14571. case LLM_ARCH_GRANITE:
  14572. case LLM_ARCH_GRANITE_MOE:
  14573. {
  14574. result = llm.build_llama();
  14575. } break;
  14576. case LLM_ARCH_MLLAMA:
  14577. {
  14578. result = llm.build_mllama();
  14579. } break;
  14580. case LLM_ARCH_BAICHUAN:
  14581. {
  14582. result = llm.build_baichuan();
  14583. } break;
  14584. case LLM_ARCH_FALCON:
  14585. {
  14586. result = llm.build_falcon();
  14587. } break;
  14588. case LLM_ARCH_GROK:
  14589. {
  14590. result = llm.build_grok();
  14591. } break;
  14592. case LLM_ARCH_STARCODER:
  14593. {
  14594. result = llm.build_starcoder();
  14595. } break;
  14596. case LLM_ARCH_REFACT:
  14597. {
  14598. result = llm.build_refact();
  14599. } break;
  14600. case LLM_ARCH_BERT:
  14601. case LLM_ARCH_JINA_BERT_V2:
  14602. case LLM_ARCH_NOMIC_BERT:
  14603. {
  14604. result = llm.build_bert();
  14605. } break;
  14606. case LLM_ARCH_BLOOM:
  14607. {
  14608. result = llm.build_bloom();
  14609. } break;
  14610. case LLM_ARCH_MPT:
  14611. {
  14612. result = llm.build_mpt();
  14613. } break;
  14614. case LLM_ARCH_STABLELM:
  14615. {
  14616. result = llm.build_stablelm();
  14617. } break;
  14618. case LLM_ARCH_QWEN:
  14619. {
  14620. result = llm.build_qwen();
  14621. } break;
  14622. case LLM_ARCH_QWEN2:
  14623. {
  14624. result = llm.build_qwen2();
  14625. } break;
  14626. case LLM_ARCH_QWEN2VL:
  14627. {
  14628. lctx.n_pos_per_token = 4;
  14629. result = llm.build_qwen2vl();
  14630. } break;
  14631. case LLM_ARCH_QWEN2MOE:
  14632. {
  14633. result = llm.build_qwen2moe();
  14634. } break;
  14635. case LLM_ARCH_PHI2:
  14636. {
  14637. result = llm.build_phi2();
  14638. } break;
  14639. case LLM_ARCH_PHI3:
  14640. {
  14641. result = llm.build_phi3();
  14642. } break;
  14643. case LLM_ARCH_PLAMO:
  14644. {
  14645. result = llm.build_plamo();
  14646. } break;
  14647. case LLM_ARCH_GPT2:
  14648. {
  14649. result = llm.build_gpt2();
  14650. } break;
  14651. case LLM_ARCH_CODESHELL:
  14652. {
  14653. result = llm.build_codeshell();
  14654. } break;
  14655. case LLM_ARCH_ORION:
  14656. {
  14657. result = llm.build_orion();
  14658. } break;
  14659. case LLM_ARCH_INTERNLM2:
  14660. {
  14661. result = llm.build_internlm2();
  14662. } break;
  14663. case LLM_ARCH_MINICPM3:
  14664. {
  14665. result = llm.build_minicpm3();
  14666. } break;
  14667. case LLM_ARCH_GEMMA:
  14668. {
  14669. result = llm.build_gemma();
  14670. } break;
  14671. case LLM_ARCH_GEMMA2:
  14672. {
  14673. result = llm.build_gemma2();
  14674. } break;
  14675. case LLM_ARCH_STARCODER2:
  14676. {
  14677. result = llm.build_starcoder2();
  14678. } break;
  14679. case LLM_ARCH_MAMBA:
  14680. {
  14681. result = llm.build_mamba();
  14682. } break;
  14683. case LLM_ARCH_XVERSE:
  14684. {
  14685. result = llm.build_xverse();
  14686. } break;
  14687. case LLM_ARCH_COMMAND_R:
  14688. {
  14689. result = llm.build_command_r();
  14690. } break;
  14691. case LLM_ARCH_DBRX:
  14692. {
  14693. result = llm.build_dbrx();
  14694. } break;
  14695. case LLM_ARCH_OLMO:
  14696. {
  14697. result = llm.build_olmo();
  14698. } break;
  14699. case LLM_ARCH_OLMO2:
  14700. {
  14701. result = llm.build_olmo2();
  14702. } break;
  14703. case LLM_ARCH_OLMOE:
  14704. {
  14705. result = llm.build_olmoe();
  14706. } break;
  14707. case LLM_ARCH_OPENELM:
  14708. {
  14709. result = llm.build_openelm();
  14710. } break;
  14711. case LLM_ARCH_GPTNEOX:
  14712. {
  14713. result = llm.build_gptneox();
  14714. } break;
  14715. case LLM_ARCH_ARCTIC:
  14716. {
  14717. result = llm.build_arctic();
  14718. } break;
  14719. case LLM_ARCH_DEEPSEEK2:
  14720. {
  14721. result = llm.build_deepseek2();
  14722. } break;
  14723. case LLM_ARCH_CHATGLM:
  14724. {
  14725. result = llm.build_chatglm();
  14726. } break;
  14727. case LLM_ARCH_BITNET:
  14728. {
  14729. result = llm.build_bitnet();
  14730. } break;
  14731. case LLM_ARCH_T5:
  14732. {
  14733. if (lctx.is_encoding) {
  14734. result = llm.build_t5_encoder();
  14735. } else {
  14736. result = llm.build_t5_decoder();
  14737. }
  14738. } break;
  14739. case LLM_ARCH_T5ENCODER:
  14740. {
  14741. result = llm.build_t5_encoder();
  14742. } break;
  14743. case LLM_ARCH_JAIS:
  14744. {
  14745. result = llm.build_jais();
  14746. } break;
  14747. case LLM_ARCH_NEMOTRON:
  14748. {
  14749. result = llm.build_nemotron();
  14750. } break;
  14751. case LLM_ARCH_EXAONE:
  14752. {
  14753. result = llm.build_exaone();
  14754. } break;
  14755. case LLM_ARCH_RWKV6:
  14756. {
  14757. result = llm.build_rwkv6();
  14758. } break;
  14759. case LLM_ARCH_CHAMELEON:
  14760. {
  14761. result = llm.build_chameleon();
  14762. } break;
  14763. case LLM_ARCH_SOLAR:
  14764. {
  14765. result = llm.build_solar();
  14766. } break;
  14767. default:
  14768. GGML_ABORT("fatal error");
  14769. }
  14770. // add on pooling layer
  14771. if (lctx.cparams.embeddings) {
  14772. result = llm.append_pooling(result);
  14773. }
  14774. llm.free();
  14775. return result;
  14776. }
  14777. static void llama_set_k_shift(llama_context & lctx) {
  14778. const int64_t kv_size = lctx.kv_self.size;
  14779. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  14780. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  14781. for (int i = 0; i < kv_size; ++i) {
  14782. data[i] = lctx.kv_self.cells[i].delta;
  14783. }
  14784. }
  14785. static void llama_set_s_copy(llama_context & lctx) {
  14786. const int64_t kv_size = lctx.kv_self.size;
  14787. assert(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  14788. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  14789. for (int i = 0; i < kv_size; ++i) {
  14790. data[i] = lctx.kv_self.cells[i].src;
  14791. }
  14792. }
  14793. static int32_t llama_relative_position_bucket(llama_pos x, llama_pos y, uint64_t n_buckets, bool bidirectional) {
  14794. // TODO move to hparams if a T5 variant appears that uses a different value
  14795. const int64_t max_distance = 128;
  14796. if (bidirectional) {
  14797. n_buckets >>= 1;
  14798. }
  14799. const int64_t max_exact = n_buckets >> 1;
  14800. int32_t relative_position = x - y;
  14801. int32_t relative_bucket = 0;
  14802. if (bidirectional) {
  14803. relative_bucket += (relative_position > 0) * n_buckets;
  14804. relative_position = abs(relative_position);
  14805. } else {
  14806. relative_position = -std::min<int32_t>(relative_position, 0);
  14807. }
  14808. 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));
  14809. relative_position_if_large = std::min<int32_t>(relative_position_if_large, n_buckets - 1);
  14810. relative_bucket += (relative_position < max_exact ? relative_position : relative_position_if_large);
  14811. return relative_bucket;
  14812. }
  14813. static void llama_set_inputs(llama_context & lctx, const llama_ubatch & ubatch) {
  14814. //
  14815. // set input data
  14816. //
  14817. const auto & hparams = lctx.model.hparams;
  14818. const auto & cparams = lctx.cparams;
  14819. const auto & kv_self = lctx.kv_self;
  14820. if (ubatch.token) {
  14821. const int64_t n_tokens = ubatch.n_tokens;
  14822. ggml_backend_tensor_set(lctx.inp_tokens, ubatch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  14823. }
  14824. if (ubatch.embd) {
  14825. if (lctx.inp_cross_attn_state && lctx.inp_cross_attn_state->buffer) {
  14826. ggml_backend_tensor_set(lctx.inp_cross_attn_state, ubatch.embd, 0, ggml_nbytes(lctx.inp_cross_attn_state));
  14827. // zero out inp_embd since it's not used
  14828. float * inp_embd_data = (float *)lctx.inp_embd->data;
  14829. for (int i = 0; i < ggml_nelements(lctx.inp_embd); ++i) {
  14830. inp_embd_data[i] = 0.0f;
  14831. }
  14832. } else {
  14833. const int64_t n_embd = hparams.n_embd;
  14834. const int64_t n_tokens = ubatch.n_tokens;
  14835. ggml_backend_tensor_set(lctx.inp_embd, ubatch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  14836. }
  14837. }
  14838. if (ubatch.pos && lctx.inp_pos) {
  14839. const int64_t n_tokens = ubatch.n_tokens;
  14840. auto n_pos = lctx.n_pos_per_token;
  14841. ggml_backend_tensor_set(lctx.inp_pos, ubatch.pos, 0, n_tokens*n_pos*ggml_element_size(lctx.inp_pos));
  14842. }
  14843. if (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE) {
  14844. GGML_ASSERT(lctx.inp_out_ids && "every model that can must skip unused outputs");
  14845. const int64_t n_tokens = ubatch.n_tokens;
  14846. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_out_ids->buffer));
  14847. int32_t * data = (int32_t *) lctx.inp_out_ids->data;
  14848. if (lctx.n_outputs == n_tokens) {
  14849. for (int i = 0; i < n_tokens; ++i) {
  14850. data[i] = i;
  14851. }
  14852. } else if (ubatch.output) {
  14853. int32_t n_outputs = 0;
  14854. for (int i = 0; i < n_tokens; ++i) {
  14855. if (ubatch.output[i]) {
  14856. data[n_outputs++] = i;
  14857. }
  14858. }
  14859. // the graph needs to have been passed the correct number of outputs
  14860. GGML_ASSERT(lctx.n_outputs == n_outputs);
  14861. } else if (lctx.n_outputs == 1) {
  14862. // only keep last output
  14863. data[0] = n_tokens - 1;
  14864. } else {
  14865. GGML_ASSERT(lctx.n_outputs == 0);
  14866. }
  14867. }
  14868. GGML_ASSERT(
  14869. // (!a || b) is a logical implication (a -> b)
  14870. // !hparams.causal_attn -> !cparams.causal_attn
  14871. (hparams.causal_attn || !cparams.causal_attn) &&
  14872. "causal attention is not supported by this model"
  14873. );
  14874. if (lctx.inp_KQ_mask || lctx.inp_KQ_mask_swa) {
  14875. // NOTE: hparams.causal_attn indicates the model is capable of generation and uses the kv cache.
  14876. if (cparams.causal_attn && !lctx.is_encoding) {
  14877. const int64_t n_kv = kv_self.n;
  14878. const int64_t n_tokens = ubatch.n_tokens;
  14879. const int64_t n_seq_tokens = ubatch.n_seq_tokens;
  14880. const int64_t n_seqs = ubatch.n_seqs;
  14881. float * data = nullptr;
  14882. float * data_swa = nullptr;
  14883. if (lctx.inp_KQ_mask) {
  14884. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  14885. data = (float *) lctx.inp_KQ_mask->data;
  14886. }
  14887. if (lctx.inp_KQ_mask_swa) {
  14888. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask_swa->buffer));
  14889. data_swa = (float *) lctx.inp_KQ_mask_swa->data;
  14890. }
  14891. // For causal attention, use only the previous KV cells
  14892. // of the correct sequence for each token of the ubatch.
  14893. // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
  14894. for (int h = 0; h < 1; ++h) {
  14895. for (int s = 0; s < n_seqs; ++s) {
  14896. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  14897. for (int j = 0; j < n_seq_tokens; ++j) {
  14898. const llama_pos pos = ubatch.pos[s*n_seq_tokens + j];
  14899. for (int i = 0; i < n_kv; ++i) {
  14900. float f;
  14901. if (!kv_self.cells[i].has_seq_id(seq_id) || kv_self.cells[i].pos > pos) {
  14902. f = -INFINITY;
  14903. } else {
  14904. if (hparams.use_alibi) {
  14905. f = -std::abs(kv_self.cells[i].pos - pos);
  14906. } else {
  14907. f = 0.0f;
  14908. }
  14909. }
  14910. if (data) {
  14911. data[h*(n_kv*n_tokens) + s*(n_kv*n_seq_tokens) + j*n_kv + i] = f;
  14912. }
  14913. // may need to cut off old tokens for sliding window
  14914. if (data_swa) {
  14915. if (pos - kv_self.cells[i].pos >= (int32_t)hparams.n_swa) {
  14916. f = -INFINITY;
  14917. }
  14918. data_swa[h*(n_kv*n_tokens) + s*(n_kv*n_seq_tokens) + j*n_kv + i] = f;
  14919. }
  14920. }
  14921. }
  14922. }
  14923. if (data) {
  14924. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  14925. for (int j = 0; j < n_kv; ++j) {
  14926. data[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
  14927. }
  14928. }
  14929. }
  14930. if (data_swa) {
  14931. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  14932. for (int j = 0; j < n_kv; ++j) {
  14933. data_swa[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
  14934. }
  14935. }
  14936. }
  14937. }
  14938. } else {
  14939. const int64_t n_tokens = ubatch.n_tokens;
  14940. const int64_t n_seq_tokens = ubatch.n_seq_tokens;
  14941. const int64_t n_seqs = ubatch.n_seqs;
  14942. // when using kv cache, the mask needs to match the kv cache size
  14943. const int64_t n_stride = hparams.causal_attn && !lctx.is_encoding ? kv_self.n : n_tokens;
  14944. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  14945. float * data = (float *) lctx.inp_KQ_mask->data;
  14946. for (int h = 0; h < 1; ++h) {
  14947. for (int s1 = 0; s1 < n_seqs; ++s1) {
  14948. const llama_seq_id seq_id = ubatch.seq_id[s1][0];
  14949. for (int j = 0; j < n_seq_tokens; ++j) {
  14950. const int32_t tj = s1*n_seq_tokens + j;
  14951. for (int s0 = 0; s0 < n_seqs; ++s0) {
  14952. for (int i = 0; i < n_seq_tokens; ++i) {
  14953. const int32_t ti = s0*n_seq_tokens + i;
  14954. float f = -INFINITY;
  14955. for (int s = 0; s < ubatch.n_seq_id[s0]; ++s) {
  14956. if (ubatch.seq_id[s0][s] == seq_id) {
  14957. if (hparams.use_alibi) {
  14958. f = -std::abs(ubatch.pos[ti] - ubatch.pos[tj]);
  14959. } else {
  14960. f = 0.0f;
  14961. }
  14962. break;
  14963. }
  14964. }
  14965. data[h*(n_tokens*n_tokens) + tj*n_stride + ti] = f;
  14966. }
  14967. }
  14968. for (int i = n_tokens; i < n_stride; ++i) {
  14969. data[h*(n_tokens*n_tokens) + tj*n_stride + i] = -INFINITY;
  14970. }
  14971. }
  14972. }
  14973. }
  14974. }
  14975. }
  14976. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  14977. const int64_t n_tokens = ubatch.n_tokens;
  14978. const int64_t n_seq_tokens = ubatch.n_seq_tokens;
  14979. const int64_t n_seqs = ubatch.n_seqs;
  14980. GGML_ASSERT(lctx.inp_mean);
  14981. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  14982. float * data = (float *) lctx.inp_mean->data;
  14983. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  14984. std::vector<uint64_t> sum(n_tokens, 0);
  14985. for (int s = 0; s < n_seqs; ++s) {
  14986. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  14987. // TODO: adapt limits to n_seqs when ubatch.equal_seqs is true
  14988. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
  14989. sum[seq_id] += ubatch.n_seq_tokens;
  14990. }
  14991. std::vector<float> div(n_tokens, 0.0f);
  14992. for (int i = 0; i < n_tokens; ++i) {
  14993. const uint64_t s = sum[i];
  14994. if (s > 0) {
  14995. div[i] = 1.0f/float(s);
  14996. }
  14997. }
  14998. for (int s = 0; s < n_seqs; ++s) {
  14999. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  15000. for (int i = 0; i < n_seq_tokens; ++i) {
  15001. data[seq_id*n_tokens + s*n_seq_tokens + i] = div[seq_id];
  15002. }
  15003. }
  15004. }
  15005. if (cparams.embeddings && (
  15006. cparams.pooling_type == LLAMA_POOLING_TYPE_CLS ||
  15007. cparams.pooling_type == LLAMA_POOLING_TYPE_RANK)) {
  15008. const int64_t n_tokens = ubatch.n_tokens;
  15009. const int64_t n_seq_tokens = ubatch.n_seq_tokens;
  15010. const int64_t n_seqs = ubatch.n_seqs;
  15011. GGML_ASSERT(lctx.inp_cls);
  15012. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  15013. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  15014. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  15015. for (int s = 0; s < n_seqs; ++s) {
  15016. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  15017. // TODO: adapt limits to n_seqs when ubatch.equal_seqs is true
  15018. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS or RANK");
  15019. for (int i = 0; i < n_seq_tokens; ++i) {
  15020. const llama_pos pos = ubatch.pos[s*n_seq_tokens + i];
  15021. if (pos == 0) {
  15022. data[seq_id] = s*n_seq_tokens + i;
  15023. }
  15024. }
  15025. }
  15026. }
  15027. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_LAST) {
  15028. const int64_t n_tokens = ubatch.n_tokens;
  15029. const int64_t n_seq_tokens = ubatch.n_seq_tokens;
  15030. const int64_t n_seqs = ubatch.n_seqs;
  15031. GGML_ASSERT(lctx.inp_cls);
  15032. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  15033. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  15034. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  15035. std::vector<int> last_pos(n_tokens, -1);
  15036. std::vector<int> last_row(n_tokens, -1);
  15037. for (int s = 0; s < n_seqs; ++s) {
  15038. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  15039. // TODO: adapt limits to n_seqs when ubatch.equal_seqs is true
  15040. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == LAST");
  15041. for (int i = 0; i < n_seq_tokens; ++i) {
  15042. const llama_pos pos = ubatch.pos[s*n_seq_tokens + i];
  15043. if (pos >= last_pos[seq_id]) {
  15044. last_pos[seq_id] = pos;
  15045. last_row[seq_id] = s*n_seq_tokens + i;
  15046. }
  15047. }
  15048. }
  15049. for (int i = 0; i < n_tokens; ++i) {
  15050. if (last_row[i] >= 0) {
  15051. data[i] = last_row[i];
  15052. }
  15053. }
  15054. }
  15055. if (kv_self.recurrent) {
  15056. const int64_t n_kv = kv_self.n;
  15057. if (lctx.inp_s_mask) {
  15058. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_mask->buffer));
  15059. float * data = (float *) lctx.inp_s_mask->data;
  15060. // clear unused states
  15061. for (int i = 0; i < n_kv; ++i) {
  15062. const uint32_t cell_id = i + kv_self.head;
  15063. llama_kv_cell & kv_cell = lctx.kv_self.cells[cell_id];
  15064. data[i] = (float) (kv_cell.src >= 0);
  15065. // only clear once
  15066. if (kv_cell.src < 0) {
  15067. kv_cell.src = cell_id;
  15068. }
  15069. }
  15070. }
  15071. if (lctx.inp_s_copy) {
  15072. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  15073. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  15074. // assuming copy destinations ALWAYS happen ONLY on the cells between head and head+n
  15075. for (uint32_t i = 0; i < n_kv; ++i) {
  15076. const uint32_t cell_id = i + kv_self.head;
  15077. llama_kv_cell & kv_cell = lctx.kv_self.cells[cell_id];
  15078. // prevent out-of-bound sources
  15079. if (kv_cell.src < 0 || (uint32_t) kv_cell.src >= kv_self.size) {
  15080. kv_cell.src = cell_id;
  15081. }
  15082. data[i] = kv_cell.src;
  15083. // ensure copy only happens once
  15084. if (kv_cell.src != (int32_t) cell_id) {
  15085. kv_cell.src = cell_id;
  15086. }
  15087. }
  15088. }
  15089. }
  15090. if (lctx.inp_pos_bucket) {
  15091. const int64_t n_tokens = ubatch.n_tokens;
  15092. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_pos_bucket->buffer));
  15093. GGML_ASSERT(!ubatch.equal_seqs); // TODO: use ubatch.n_seqs instead of failing
  15094. int32_t * data = (int32_t *) lctx.inp_pos_bucket->data;
  15095. if (!lctx.is_encoding) {
  15096. const int64_t n_kv = kv_self.n;
  15097. for (int h = 0; h < 1; ++h) {
  15098. for (int j = 0; j < n_tokens; ++j) {
  15099. for (int i = 0; i < n_kv; ++i) {
  15100. 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);
  15101. }
  15102. }
  15103. }
  15104. } else {
  15105. for (int h = 0; h < 1; ++h) {
  15106. for (int j = 0; j < n_tokens; ++j) {
  15107. for (int i = 0; i < n_tokens; ++i) {
  15108. 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);
  15109. }
  15110. }
  15111. }
  15112. }
  15113. }
  15114. if (!lctx.is_encoding && lctx.inp_embd_enc) {
  15115. assert(lctx.inp_embd_enc->type == GGML_TYPE_F32);
  15116. assert((size_t) ggml_nelements(lctx.inp_embd_enc) == lctx.embd_enc.size());
  15117. ggml_backend_tensor_set(lctx.inp_embd_enc, lctx.embd_enc.data(), 0, ggml_nbytes(lctx.inp_embd_enc));
  15118. }
  15119. if (!lctx.is_encoding && lctx.inp_KQ_mask_cross) {
  15120. const int64_t n_output_enc = lctx.embd_enc.size() / hparams.n_embd;
  15121. const int64_t n_tokens = ubatch.n_tokens;
  15122. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask_cross->buffer));
  15123. GGML_ASSERT(!ubatch.equal_seqs); // TODO: use ubatch.n_seqs instead of failing
  15124. float * data = (float *) lctx.inp_KQ_mask_cross->data;
  15125. for (int h = 0; h < 1; ++h) {
  15126. for (int j = 0; j < n_tokens; ++j) {
  15127. for (int i = 0; i < n_output_enc; ++i) {
  15128. float f = -INFINITY;
  15129. for (int s = 0; s < ubatch.n_seq_id[j]; ++s) {
  15130. const llama_seq_id seq_id = ubatch.seq_id[j][s];
  15131. if (lctx.seq_ids_enc[i].find(seq_id) != lctx.seq_ids_enc[i].end()) {
  15132. f = 0.0f;
  15133. }
  15134. }
  15135. data[h*(n_output_enc*n_tokens) + j*n_output_enc + i] = f;
  15136. }
  15137. }
  15138. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  15139. for (int j = 0; j < n_output_enc; ++j) {
  15140. data[h*(n_output_enc*n_tokens) + i*n_output_enc + j] = -INFINITY;
  15141. }
  15142. }
  15143. }
  15144. }
  15145. }
  15146. // Make sure enough space is available for outputs.
  15147. // Returns max number of outputs for which space was reserved.
  15148. static size_t llama_output_reserve(llama_context & lctx, size_t n_outputs) {
  15149. const auto & cparams = lctx.cparams;
  15150. const auto & hparams = lctx.model.hparams;
  15151. const size_t n_outputs_max = std::max(n_outputs, (size_t) cparams.n_seq_max);
  15152. const auto n_batch = cparams.n_batch;
  15153. const auto n_vocab = hparams.n_vocab;
  15154. const auto n_embd = hparams.n_embd;
  15155. // TODO: use a per-batch flag for logits presence instead
  15156. const bool has_logits = cparams.causal_attn;
  15157. const bool has_embd = cparams.embeddings && (cparams.pooling_type == LLAMA_POOLING_TYPE_NONE);
  15158. const size_t logits_size = has_logits ? n_vocab*n_outputs_max : 0;
  15159. const size_t embd_size = has_embd ? n_embd*n_outputs_max : 0;
  15160. if (lctx.output_ids.empty()) {
  15161. // init, never resized afterwards
  15162. lctx.output_ids.resize(n_batch);
  15163. }
  15164. const size_t prev_size = lctx.buf_output ? ggml_backend_buffer_get_size(lctx.buf_output.get()) : 0;
  15165. const size_t new_size = (logits_size + embd_size) * sizeof(float);
  15166. // alloc only when more than the current capacity is required
  15167. // TODO: also consider shrinking the buffer
  15168. if (!lctx.buf_output || prev_size < new_size) {
  15169. if (lctx.buf_output) {
  15170. #ifndef NDEBUG
  15171. // This doesn't happen often, but may be annoying in some cases (like the HellaSwag benchmark)
  15172. 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);
  15173. #endif
  15174. lctx.buf_output = nullptr;
  15175. lctx.logits = nullptr;
  15176. lctx.embd = nullptr;
  15177. }
  15178. auto * buft = ggml_backend_cpu_buffer_type();
  15179. // try to use the host buffer of the device where the output tensor is allocated for faster transfer to system memory
  15180. auto * output_dev = lctx.model.dev_output.dev;
  15181. auto * output_dev_host_buft = output_dev ? ggml_backend_dev_host_buffer_type(output_dev) : nullptr;
  15182. if (output_dev_host_buft) {
  15183. buft = output_dev_host_buft;
  15184. }
  15185. lctx.buf_output.reset(ggml_backend_buft_alloc_buffer(buft, new_size));
  15186. if (lctx.buf_output == nullptr) {
  15187. LLAMA_LOG_ERROR("%s: failed to allocate output buffer of size %.2f MiB\n", __func__, new_size / (1024.0 * 1024.0));
  15188. return 0;
  15189. }
  15190. }
  15191. float * output_base = (float *) ggml_backend_buffer_get_base(lctx.buf_output.get());
  15192. lctx.logits = has_logits ? output_base : nullptr;
  15193. lctx.embd = has_embd ? output_base + logits_size : nullptr;
  15194. lctx.output_size = n_outputs_max;
  15195. lctx.logits_size = logits_size;
  15196. lctx.embd_size = embd_size;
  15197. // set all ids as invalid (negative)
  15198. std::fill(lctx.output_ids.begin(), lctx.output_ids.end(), -1);
  15199. ggml_backend_buffer_clear(lctx.buf_output.get(), 0);
  15200. lctx.n_outputs = 0;
  15201. return n_outputs_max;
  15202. }
  15203. // make the outputs have the same order they had in the user-provided batch
  15204. static void llama_output_reorder(struct llama_context * ctx) {
  15205. std::vector<size_t> & out_ids = ctx->sbatch.out_ids;
  15206. if (!out_ids.empty()) {
  15207. uint32_t n_vocab = ctx->model.hparams.n_vocab;
  15208. uint32_t n_embd = ctx->model.hparams.n_embd;
  15209. int32_t n_outputs = ctx->n_outputs;
  15210. GGML_ASSERT((size_t) n_outputs == out_ids.size());
  15211. // TODO: is there something more efficient which also minimizes swaps?
  15212. // selection sort, to minimize swaps (from https://en.wikipedia.org/wiki/Selection_sort)
  15213. for (int32_t i = 0; i < n_outputs - 1; ++i) {
  15214. int32_t j_min = i;
  15215. for (int32_t j = i + 1; j < n_outputs; ++j) {
  15216. if (out_ids[j] < out_ids[j_min]) {
  15217. j_min = j;
  15218. }
  15219. }
  15220. if (j_min == i) { continue; }
  15221. std::swap(out_ids[i], out_ids[j_min]);
  15222. if (ctx->logits_size > 0) {
  15223. for (uint32_t k = 0; k < n_vocab; k++) {
  15224. std::swap(ctx->logits[i*n_vocab + k], ctx->logits[j_min*n_vocab + k]);
  15225. }
  15226. }
  15227. if (ctx->embd_size > 0) {
  15228. for (uint32_t k = 0; k < n_embd; k++) {
  15229. std::swap(ctx->embd[i*n_embd + k], ctx->embd[j_min*n_embd + k]);
  15230. }
  15231. }
  15232. }
  15233. std::fill(ctx->output_ids.begin(), ctx->output_ids.end(), -1);
  15234. for (int32_t i = 0; i < n_outputs; ++i) {
  15235. ctx->output_ids[out_ids[i]] = i;
  15236. }
  15237. out_ids.clear();
  15238. }
  15239. }
  15240. // returns the result of ggml_backend_sched_graph_compute_async execution
  15241. static enum ggml_status llama_graph_compute(
  15242. llama_context & lctx,
  15243. ggml_cgraph * gf,
  15244. int n_threads,
  15245. ggml_threadpool * threadpool) {
  15246. if (lctx.backend_cpu != nullptr) {
  15247. auto * reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(lctx.backend_cpu));
  15248. auto * set_threadpool_fn = (decltype(ggml_backend_cpu_set_threadpool) *) ggml_backend_reg_get_proc_address(reg, "ggml_backend_cpu_set_threadpool");
  15249. set_threadpool_fn(lctx.backend_cpu, threadpool);
  15250. }
  15251. // set the number of threads for all the backends
  15252. for (const auto & set_n_threads_fn : lctx.set_n_threads_fns) {
  15253. set_n_threads_fn.second(set_n_threads_fn.first, n_threads);
  15254. }
  15255. auto status = ggml_backend_sched_graph_compute_async(lctx.sched.get(), gf);
  15256. if (status != GGML_STATUS_SUCCESS) {
  15257. LLAMA_LOG_ERROR("%s: ggml_backend_sched_graph_compute_async failed with error %d\n", __func__, status);
  15258. }
  15259. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  15260. return status;
  15261. }
  15262. // decode a batch of tokens by evaluating the transformer
  15263. // in case of unsuccessful decoding (error or warning),
  15264. // the kv_cache state will be returned to its original state
  15265. // (for non-recurrent models) or cleaned (for recurrent models)
  15266. //
  15267. // - lctx: llama context
  15268. // - batch: batch to evaluate
  15269. //
  15270. // return 0 on success
  15271. // return positive int on warning
  15272. // return negative int on error
  15273. //
  15274. static int llama_decode_internal(
  15275. llama_context & lctx,
  15276. llama_batch inp_batch) {
  15277. lctx.is_encoding = false;
  15278. if (inp_batch.n_tokens == 0) {
  15279. LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__);
  15280. return -1;
  15281. }
  15282. // temporary allocate memory for the input batch if needed
  15283. llama_batch_allocr batch_allocr(lctx, inp_batch);
  15284. const llama_batch & batch = batch_allocr.batch;
  15285. const uint32_t n_tokens_all = batch.n_tokens;
  15286. const auto & model = lctx.model;
  15287. const auto & hparams = model.hparams;
  15288. const auto & cparams = lctx.cparams;
  15289. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  15290. if (batch.token) {
  15291. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  15292. if (batch.token[i] < 0 || (uint32_t)batch.token[i] >= model.vocab.n_vocab) {
  15293. LLAMA_LOG_ERROR("%s: invalid token[%d] = %d\n", __func__, i, batch.token[i]);
  15294. return -1;
  15295. }
  15296. }
  15297. }
  15298. GGML_ASSERT(n_tokens_all <= cparams.n_batch);
  15299. GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
  15300. if (lctx.t_compute_start_us == 0) {
  15301. lctx.t_compute_start_us = ggml_time_us();
  15302. }
  15303. lctx.n_queued_tokens += n_tokens_all;
  15304. auto & kv_self = lctx.kv_self;
  15305. llama_kv_slot_restorer kv_slot_restorer(kv_self);
  15306. const int64_t n_embd = hparams.n_embd;
  15307. const int64_t n_vocab = hparams.n_vocab;
  15308. uint32_t n_outputs = 0;
  15309. uint32_t n_outputs_prev = 0;
  15310. const auto n_ubatch = cparams.n_ubatch;
  15311. // this indicates we are doing pooled embedding, so we ignore batch.logits and output all tokens
  15312. const bool embd_pooled = cparams.embeddings && cparams.pooling_type != LLAMA_POOLING_TYPE_NONE;
  15313. lctx.embd_seq.clear();
  15314. // count outputs
  15315. if (batch.logits && !embd_pooled) {
  15316. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  15317. n_outputs += batch.logits[i] != 0;
  15318. }
  15319. } else if (lctx.logits_all || embd_pooled) {
  15320. n_outputs = n_tokens_all;
  15321. } else {
  15322. // keep last output only
  15323. n_outputs = 1;
  15324. }
  15325. lctx.sbatch.from_batch(batch, batch.n_embd,
  15326. /* simple_split */ !kv_self.recurrent,
  15327. /* logits_all */ n_outputs == n_tokens_all);
  15328. // reserve output buffer
  15329. if (llama_output_reserve(lctx, n_outputs) < n_outputs) {
  15330. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_outputs);
  15331. return -2;
  15332. };
  15333. while (lctx.sbatch.n_tokens > 0) {
  15334. llama_ubatch ubatch;
  15335. if (kv_self.recurrent) {
  15336. if (embd_pooled) {
  15337. // Pooled embeddings cannot be split across ubatches (yet)
  15338. ubatch = lctx.sbatch.split_seq(n_ubatch);
  15339. } else {
  15340. // recurrent model architectures are easier to implement
  15341. // with equal-length sequences
  15342. ubatch = lctx.sbatch.split_equal(n_ubatch);
  15343. }
  15344. } else {
  15345. ubatch = lctx.sbatch.split_simple(n_ubatch);
  15346. }
  15347. const uint32_t n_tokens = ubatch.n_tokens;
  15348. // count the outputs in this u_batch
  15349. {
  15350. int32_t n_outputs_new = 0;
  15351. if (n_outputs == n_tokens_all) {
  15352. n_outputs_new = n_tokens;
  15353. } else {
  15354. GGML_ASSERT(ubatch.output);
  15355. for (uint32_t i = 0; i < n_tokens; i++) {
  15356. n_outputs_new += (int32_t) (ubatch.output[i] != 0);
  15357. }
  15358. }
  15359. // needs to happen before the graph is built
  15360. lctx.n_outputs = n_outputs_new;
  15361. }
  15362. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  15363. ggml_threadpool_t threadpool = n_tokens == 1 ? lctx.threadpool : lctx.threadpool_batch;
  15364. GGML_ASSERT(n_threads > 0);
  15365. // non-causal masks do not use the KV cache
  15366. if (hparams.causal_attn) {
  15367. llama_kv_cache_update(&lctx);
  15368. // if we have enough unused cells before the current head ->
  15369. // better to start searching from the beginning of the cache, hoping to fill it
  15370. if (kv_self.head > kv_self.used + 2*n_tokens) {
  15371. kv_self.head = 0;
  15372. }
  15373. const auto slot = llama_kv_cache_find_slot(kv_self, ubatch);
  15374. if (!slot) {
  15375. return 1;
  15376. }
  15377. kv_slot_restorer.save(slot);
  15378. if (!kv_self.recurrent) {
  15379. // a heuristic, to avoid attending the full cache if it is not yet utilized
  15380. // after enough generations, the benefit from this heuristic disappears
  15381. // if we start defragmenting the cache, the benefit from this will be more important
  15382. const uint32_t pad = llama_kv_cache_get_padding(cparams);
  15383. kv_self.n = std::min(kv_self.size, std::max(pad, GGML_PAD(llama_kv_cache_cell_max(kv_self), pad)));
  15384. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  15385. }
  15386. }
  15387. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  15388. ggml_backend_sched_reset(lctx.sched.get());
  15389. ggml_backend_sched_set_eval_callback(lctx.sched.get(), lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  15390. ggml_cgraph * gf = llama_build_graph(lctx, ubatch, false);
  15391. // the output is always the last tensor in the graph
  15392. struct ggml_tensor * res = ggml_graph_node(gf, -1);
  15393. struct ggml_tensor * embd = ggml_graph_node(gf, -2);
  15394. if (lctx.n_outputs == 0) {
  15395. // no output
  15396. res = nullptr;
  15397. embd = nullptr;
  15398. } else if (cparams.embeddings) {
  15399. embd = nullptr;
  15400. for (int i = ggml_graph_n_nodes(gf) - 1; i >= 0; --i) {
  15401. if (strcmp(ggml_graph_node(gf, i)->name, "result_embd_pooled") == 0) {
  15402. embd = ggml_graph_node(gf, i);
  15403. break;
  15404. }
  15405. }
  15406. } else {
  15407. embd = nullptr; // do not extract embeddings when not needed
  15408. GGML_ASSERT(strcmp(res->name, "result_output") == 0 && "missing result_output tensor");
  15409. }
  15410. if (!cparams.causal_attn) {
  15411. res = nullptr; // do not extract logits when not needed
  15412. }
  15413. // 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);
  15414. ggml_backend_sched_alloc_graph(lctx.sched.get(), gf);
  15415. llama_set_inputs(lctx, ubatch);
  15416. const auto compute_status = llama_graph_compute(lctx, gf, n_threads, threadpool);
  15417. if (compute_status != GGML_STATUS_SUCCESS) {
  15418. kv_slot_restorer.restore(kv_self);
  15419. switch (compute_status) {
  15420. case GGML_STATUS_ABORTED:
  15421. return 2;
  15422. case GGML_STATUS_ALLOC_FAILED:
  15423. return -2;
  15424. case GGML_STATUS_FAILED:
  15425. default:
  15426. return -3;
  15427. }
  15428. }
  15429. // update the kv ring buffer
  15430. {
  15431. kv_self.head += n_tokens;
  15432. // Ensure kv cache head points to a valid index.
  15433. if (kv_self.head >= kv_self.size) {
  15434. kv_self.head = 0;
  15435. }
  15436. }
  15437. // plot the computation graph in dot format (for debugging purposes)
  15438. //if (n_past%100 == 0) {
  15439. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  15440. //}
  15441. // extract logits
  15442. if (res) {
  15443. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(lctx.sched.get(), res);
  15444. GGML_ASSERT(backend_res != nullptr);
  15445. GGML_ASSERT(lctx.logits != nullptr);
  15446. float * logits_out = lctx.logits + n_outputs_prev*n_vocab;
  15447. const int32_t n_outputs_new = lctx.n_outputs;
  15448. if (n_outputs_new) {
  15449. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  15450. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_vocab <= (int64_t) lctx.logits_size);
  15451. ggml_backend_tensor_get_async(backend_res, res, logits_out, 0, n_outputs_new*n_vocab*sizeof(float));
  15452. }
  15453. }
  15454. // extract embeddings
  15455. if (embd) {
  15456. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched.get(), embd);
  15457. GGML_ASSERT(backend_embd != nullptr);
  15458. switch (cparams.pooling_type) {
  15459. case LLAMA_POOLING_TYPE_NONE:
  15460. {
  15461. // extract token embeddings
  15462. GGML_ASSERT(lctx.embd != nullptr);
  15463. float * embd_out = lctx.embd + n_outputs_prev*n_embd;
  15464. const int32_t n_outputs_new = lctx.n_outputs;
  15465. if (n_outputs_new) {
  15466. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  15467. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_embd <= (int64_t) lctx.embd_size);
  15468. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_outputs_new*n_embd*sizeof(float));
  15469. }
  15470. } break;
  15471. case LLAMA_POOLING_TYPE_MEAN:
  15472. case LLAMA_POOLING_TYPE_CLS:
  15473. case LLAMA_POOLING_TYPE_LAST:
  15474. {
  15475. // extract sequence embeddings (cleared before processing each batch)
  15476. auto & embd_seq_out = lctx.embd_seq;
  15477. for (uint32_t s = 0; s < ubatch.n_seqs; ++s) {
  15478. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  15479. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  15480. continue;
  15481. }
  15482. embd_seq_out[seq_id].resize(n_embd);
  15483. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  15484. }
  15485. } break;
  15486. case LLAMA_POOLING_TYPE_RANK:
  15487. {
  15488. // extract the rerank score - a single float per sequence
  15489. auto & embd_seq_out = lctx.embd_seq;
  15490. for (uint32_t s = 0; s < ubatch.n_seqs; ++s) {
  15491. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  15492. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  15493. continue;
  15494. }
  15495. embd_seq_out[seq_id].resize(1);
  15496. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (seq_id)*sizeof(float), sizeof(float));
  15497. }
  15498. } break;
  15499. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  15500. {
  15501. GGML_ABORT("unknown pooling type");
  15502. }
  15503. }
  15504. }
  15505. n_outputs_prev += lctx.n_outputs;
  15506. }
  15507. // set output mappings
  15508. {
  15509. bool sorted_output = true;
  15510. GGML_ASSERT(lctx.sbatch.out_ids.size() == n_outputs);
  15511. for (size_t i = 0; i < n_outputs; ++i) {
  15512. size_t out_id = lctx.sbatch.out_ids[i];
  15513. lctx.output_ids[out_id] = i;
  15514. if (out_id != i) {
  15515. sorted_output = false;
  15516. }
  15517. }
  15518. if (sorted_output) {
  15519. lctx.sbatch.out_ids.clear();
  15520. }
  15521. }
  15522. // set to total number of outputs in the batch, for use in llama_get_logits_ith
  15523. lctx.n_outputs = n_outputs;
  15524. // wait for the computation to finish (automatically done when obtaining the model output)
  15525. //llama_synchronize(&lctx);
  15526. // decide if we need to defrag the kv cache
  15527. if (cparams.causal_attn && cparams.defrag_thold >= 0.0f) {
  15528. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used)/float(kv_self.n) : 0.0f;
  15529. // queue defragmentation for next llama_kv_cache_update
  15530. if (fragmentation > cparams.defrag_thold) {
  15531. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  15532. llama_kv_cache_defrag(kv_self);
  15533. }
  15534. }
  15535. // Reset state for the next token before backend sync, to allow the CPU activities in the reset to
  15536. // overlap with device computation.
  15537. ggml_backend_sched_reset(lctx.sched.get());
  15538. return 0;
  15539. }
  15540. // encode a batch of tokens by evaluating the encoder part of the transformer
  15541. //
  15542. // - lctx: llama context
  15543. // - batch: batch to evaluate
  15544. //
  15545. // return 0 on success
  15546. // return positive int on warning
  15547. // return negative int on error
  15548. //
  15549. static int llama_encode_internal(
  15550. llama_context & lctx,
  15551. llama_batch inp_batch) {
  15552. lctx.is_encoding = true;
  15553. if (inp_batch.n_tokens == 0) {
  15554. LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__);
  15555. return -1;
  15556. }
  15557. // temporary allocate memory for the input batch if needed
  15558. llama_batch_allocr batch_allocr(lctx, inp_batch);
  15559. const llama_batch & batch = batch_allocr.batch;
  15560. const uint32_t n_tokens = batch.n_tokens;
  15561. const auto & model = lctx.model;
  15562. const auto & hparams = model.hparams;
  15563. const auto & cparams = lctx.cparams;
  15564. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  15565. if (batch.token) {
  15566. for (uint32_t i = 0; i < n_tokens; ++i) {
  15567. if (batch.token[i] < 0 || (uint32_t)batch.token[i] >= model.vocab.n_vocab) {
  15568. LLAMA_LOG_ERROR("%s: invalid token[%d] = %d\n", __func__, i, batch.token[i]);
  15569. return -1;
  15570. }
  15571. }
  15572. }
  15573. // micro-batching is not possible for non-causal encoding, so we process the batch in a single shot
  15574. GGML_ASSERT(cparams.n_ubatch >= n_tokens && "encoder requires n_ubatch >= n_tokens");
  15575. if (lctx.t_compute_start_us == 0) {
  15576. lctx.t_compute_start_us = ggml_time_us();
  15577. }
  15578. lctx.n_queued_tokens += n_tokens;
  15579. const int64_t n_embd = hparams.n_embd;
  15580. lctx.sbatch.from_batch(batch, batch.n_embd, /* simple_split */ true, /* logits_all */ true);
  15581. const llama_ubatch ubatch = lctx.sbatch.split_simple(n_tokens);
  15582. // reserve output buffer
  15583. if (llama_output_reserve(lctx, n_tokens) < n_tokens) {
  15584. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_tokens);
  15585. return -2;
  15586. };
  15587. for (uint32_t i = 0; i < n_tokens; ++i) {
  15588. lctx.output_ids[i] = i;
  15589. }
  15590. lctx.inp_embd_enc = NULL;
  15591. lctx.n_outputs = n_tokens;
  15592. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  15593. ggml_threadpool_t threadpool = n_tokens == 1 ? lctx.threadpool : lctx.threadpool_batch;
  15594. GGML_ASSERT(n_threads > 0);
  15595. ggml_backend_sched_reset(lctx.sched.get());
  15596. ggml_backend_sched_set_eval_callback(lctx.sched.get(), lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  15597. ggml_cgraph * gf = llama_build_graph(lctx, ubatch, false);
  15598. // the output embeddings after the final encoder normalization
  15599. struct ggml_tensor * embd = nullptr;
  15600. // there are two cases here
  15601. if (llama_model_has_decoder(&lctx.model)) {
  15602. // first case is an encoder-decoder T5 model where embeddings are passed to decoder
  15603. embd = ggml_graph_node(gf, -1);
  15604. GGML_ASSERT(strcmp(embd->name, "result_norm") == 0 && "missing result_output tensor");
  15605. } else {
  15606. // second case is an encoder-only T5 model
  15607. if (cparams.embeddings) {
  15608. // only output embeddings if required
  15609. embd = ggml_graph_node(gf, -1);
  15610. if (strcmp(embd->name, "result_embd_pooled") != 0) {
  15611. embd = ggml_graph_node(gf, -2);
  15612. }
  15613. GGML_ASSERT(strcmp(embd->name, "result_embd_pooled") == 0 && "missing embeddings tensor");
  15614. }
  15615. }
  15616. ggml_backend_sched_alloc_graph(lctx.sched.get(), gf);
  15617. llama_set_inputs(lctx, ubatch);
  15618. const auto compute_status = llama_graph_compute(lctx, gf, n_threads, threadpool);
  15619. switch (compute_status) {
  15620. case GGML_STATUS_SUCCESS:
  15621. break;
  15622. case GGML_STATUS_ABORTED:
  15623. return 2;
  15624. case GGML_STATUS_ALLOC_FAILED:
  15625. return -2;
  15626. case GGML_STATUS_FAILED:
  15627. default:
  15628. return -3;
  15629. }
  15630. // extract embeddings
  15631. if (embd) {
  15632. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched.get(), embd);
  15633. GGML_ASSERT(backend_embd != nullptr);
  15634. if (llama_model_has_decoder(&lctx.model)) {
  15635. lctx.embd_enc.resize(n_tokens*n_embd);
  15636. float * embd_out = lctx.embd_enc.data();
  15637. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_tokens*n_embd*sizeof(float));
  15638. GGML_ASSERT(!ubatch.equal_seqs); // TODO: handle equal splits
  15639. // remember the sequence ids used during the encoding - needed for cross attention later
  15640. lctx.seq_ids_enc.resize(n_tokens);
  15641. for (uint32_t i = 0; i < n_tokens; i++) {
  15642. for (int s = 0; s < ubatch.n_seq_id[i]; s++) {
  15643. llama_seq_id seq_id = ubatch.seq_id[i][s];
  15644. lctx.seq_ids_enc[i].insert(seq_id);
  15645. }
  15646. }
  15647. } else {
  15648. GGML_ASSERT(lctx.embd != nullptr);
  15649. switch (cparams.pooling_type) {
  15650. case LLAMA_POOLING_TYPE_NONE:
  15651. {
  15652. // extract token embeddings
  15653. GGML_ASSERT(lctx.embd != nullptr);
  15654. float * embd_out = lctx.embd;
  15655. GGML_ASSERT(n_tokens*n_embd <= (int64_t) lctx.embd_size);
  15656. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_tokens*n_embd*sizeof(float));
  15657. } break;
  15658. case LLAMA_POOLING_TYPE_MEAN:
  15659. case LLAMA_POOLING_TYPE_CLS:
  15660. case LLAMA_POOLING_TYPE_LAST:
  15661. {
  15662. // extract sequence embeddings
  15663. auto & embd_seq_out = lctx.embd_seq;
  15664. embd_seq_out.clear();
  15665. GGML_ASSERT(!ubatch.equal_seqs); // TODO: handle equal splits
  15666. for (uint32_t i = 0; i < n_tokens; i++) {
  15667. const llama_seq_id seq_id = ubatch.seq_id[i][0];
  15668. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  15669. continue;
  15670. }
  15671. embd_seq_out[seq_id].resize(n_embd);
  15672. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  15673. }
  15674. } break;
  15675. case LLAMA_POOLING_TYPE_RANK:
  15676. {
  15677. // TODO: this likely should be the same logic as in llama_decoder_internal, but better to
  15678. // wait for an encoder model that requires this pooling type in order to test it
  15679. // https://github.com/ggerganov/llama.cpp/pull/9510
  15680. GGML_ABORT("RANK pooling not implemented yet");
  15681. }
  15682. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  15683. {
  15684. GGML_ABORT("unknown pooling type");
  15685. }
  15686. }
  15687. }
  15688. }
  15689. // Reset state for the next token before backend sync, to allow the CPU activities in the reset to
  15690. // overlap with device computation.
  15691. ggml_backend_sched_reset(lctx.sched.get());
  15692. return 0;
  15693. }
  15694. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  15695. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  15696. auto & kv_self = lctx.kv_self;
  15697. const auto & hparams = lctx.model.hparams;
  15698. const uint32_t n_layer = hparams.n_layer;
  15699. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  15700. const uint32_t n_used = kv_self.used;
  15701. assert(n_used <= n_kv);
  15702. //const int64_t t_start = ggml_time_us();
  15703. // number of cells moved
  15704. uint32_t n_moves = 0;
  15705. // each move requires 6*n_layer tensors (see build_defrag)
  15706. // - source view, destination view, copy operation
  15707. // - x2 for keys and values
  15708. //const uint32_t max_moves = llama_model_max_nodes(model)/(6*n_layer);
  15709. // TODO: tmp fix https://github.com/ggerganov/llama.cpp/issues/6685#issuecomment-2057579516
  15710. const uint32_t max_moves = (llama_model_max_nodes(lctx.model) - 2*n_layer)/(6*n_layer);
  15711. // determine which KV cells to move where
  15712. //
  15713. // cell i moves to ids[i]
  15714. //
  15715. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  15716. //
  15717. std::vector<uint32_t> ids(n_kv, n_kv);
  15718. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  15719. const auto & cell0 = kv_self.cells[i0];
  15720. if (!cell0.is_empty()) {
  15721. ids[i0] = i0;
  15722. continue;
  15723. }
  15724. // found a hole - fill it with data from the end of the cache
  15725. uint32_t nh = 1;
  15726. // determine the size of the hole
  15727. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  15728. nh++;
  15729. }
  15730. uint32_t nf = 0;
  15731. uint32_t is = n_kv - 1;
  15732. // starting from the end, find nh non-empty cells
  15733. for (; is > i0; --is) {
  15734. const auto & cell1 = kv_self.cells[is];
  15735. if (cell1.is_empty() || ids[is] != n_kv) {
  15736. continue;
  15737. }
  15738. // non-empty cell which is not yet moved
  15739. nf++;
  15740. if (nf == nh) {
  15741. break;
  15742. }
  15743. }
  15744. // this can only happen if `n_used` is not accurate, which would be a bug
  15745. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  15746. nf = 0;
  15747. uint32_t i1 = is;
  15748. // are we moving a continuous block of memory?
  15749. bool cont = false;
  15750. // should we stop searching for the next move?
  15751. bool stop = 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. if (n_moves == max_moves) {
  15757. stop = true;
  15758. break;
  15759. }
  15760. cont = false;
  15761. continue;
  15762. }
  15763. // this cell goes to (i0 + nf)
  15764. ids[i1] = i0 + nf;
  15765. // move the cell meta data
  15766. kv_self.cells[i0 + nf] = cell1;
  15767. // clear the old cell and move the head there
  15768. cell1 = llama_kv_cell();
  15769. kv_self.head = n_used;
  15770. if (!cont) {
  15771. n_moves++;
  15772. cont = true;
  15773. }
  15774. nf++;
  15775. if (nf == nh) {
  15776. break;
  15777. }
  15778. }
  15779. if (stop || n_moves == max_moves) {
  15780. break;
  15781. }
  15782. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  15783. i0 += nh - 1;
  15784. }
  15785. if (n_moves == 0) {
  15786. return;
  15787. }
  15788. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  15789. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  15790. #if 0
  15791. // CPU defrag
  15792. //
  15793. // TODO: optimizations are possible:
  15794. // - multiple threads
  15795. // - avoid copying to the host memory when already there
  15796. //
  15797. // likely not worth the effort, as we have ggml_graph based defrag
  15798. //
  15799. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  15800. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  15801. const uint32_t kv_size = kv_self.size;
  15802. std::vector<uint8_t> buf_k;
  15803. std::vector<uint8_t> buf_v;
  15804. for (uint32_t il = 0; il < n_layer; ++il) {
  15805. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  15806. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  15807. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  15808. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  15809. buf_k.resize(k_size);
  15810. buf_v.resize(v_size);
  15811. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  15812. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  15813. // batch move [i, i+nm) to [id, id+nm)
  15814. // note: cells can move only to a lower index
  15815. for (uint32_t i = 0; i < n_kv; ++i) {
  15816. const uint32_t id = ids[i];
  15817. if (i == id || id == n_kv) {
  15818. continue;
  15819. }
  15820. uint32_t nm = 1;
  15821. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  15822. nm++;
  15823. }
  15824. // move keys
  15825. {
  15826. const int64_t os = i*k_size_row;
  15827. const int64_t od = id*k_size_row;
  15828. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  15829. }
  15830. // move values (note: they are transposed)
  15831. {
  15832. const int64_t os = i;
  15833. const int64_t od = id;
  15834. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  15835. 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);
  15836. }
  15837. }
  15838. i += nm - 1;
  15839. }
  15840. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  15841. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  15842. }
  15843. #else
  15844. // ggml_graph defrag
  15845. ggml_backend_sched_reset(lctx.sched.get());
  15846. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  15847. llama_graph_compute(lctx, gf, lctx.cparams.n_threads, lctx.threadpool);
  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. }