llama.cpp 941 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507
  1. /**
  2. * llama.cpp - commit 3f1ae2e32cde00c39b96be6d01c2997c29bae555 - 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. #ifdef GGML_USE_RPC
  34. # include "ggml-rpc.h"
  35. #endif
  36. #ifdef GGML_USE_CUDA
  37. # include "ggml-cuda.h"
  38. #elif defined(GGML_USE_VULKAN)
  39. # include "ggml-vulkan.h"
  40. #elif defined(GGML_USE_SYCL)
  41. # include "ggml-sycl.h"
  42. #elif defined(GGML_USE_KOMPUTE)
  43. # include "ggml-kompute.h"
  44. #elif defined(GGML_USE_CANN)
  45. # include "ggml-cann.h"
  46. #endif
  47. #ifdef GGML_USE_BLAS
  48. # include "ggml-blas.h"
  49. #endif
  50. #ifdef GGML_USE_METAL
  51. # include "ggml-metal.h"
  52. #endif
  53. // TODO: replace with ggml API call
  54. #define QK_K 256
  55. #ifdef __has_include
  56. #if __has_include(<unistd.h>)
  57. #include <unistd.h>
  58. #if defined(_POSIX_MAPPED_FILES)
  59. #include <sys/mman.h>
  60. #include <fcntl.h>
  61. #endif
  62. #if defined(_POSIX_MEMLOCK_RANGE)
  63. #include <sys/resource.h>
  64. #endif
  65. #endif
  66. #endif
  67. #if defined(_WIN32)
  68. #define WIN32_LEAN_AND_MEAN
  69. #ifndef NOMINMAX
  70. #define NOMINMAX
  71. #endif
  72. #include <windows.h>
  73. #ifndef PATH_MAX
  74. #define PATH_MAX MAX_PATH
  75. #endif
  76. #include <io.h>
  77. #endif
  78. #if __cplusplus >= 202000L
  79. #define LU8(x) (const char*)(u8##x)
  80. #else
  81. #define LU8(x) u8##x
  82. #endif
  83. #include <algorithm>
  84. #include <array>
  85. #include <cassert>
  86. #include <cctype>
  87. #include <cfloat>
  88. #include <cinttypes>
  89. #include <climits>
  90. #include <cmath>
  91. #include <cstdarg>
  92. #include <cstddef>
  93. #include <cstdint>
  94. #include <cstdio>
  95. #include <cstring>
  96. #include <ctime>
  97. #include <fstream>
  98. #include <functional>
  99. #include <future>
  100. #include <initializer_list>
  101. #include <locale>
  102. #include <map>
  103. #include <memory>
  104. #include <mutex>
  105. #include <numeric>
  106. #include <set>
  107. #include <sstream>
  108. #include <thread>
  109. #include <type_traits>
  110. #include <unordered_map>
  111. #if defined(_MSC_VER)
  112. #pragma warning(disable: 4244 4267) // possible loss of data
  113. #endif
  114. // bump if necessary
  115. #define LLAMA_MAX_LAYERS 512
  116. #define LLAMA_MAX_EXPERTS 160 // DeepSeekV2
  117. //
  118. // helpers
  119. //
  120. // trim whitespace from the beginning and end of a string
  121. static std::string trim(const std::string & str) {
  122. size_t start = 0;
  123. size_t end = str.size();
  124. while (start < end && isspace(str[start])) {
  125. start += 1;
  126. }
  127. while (end > start && isspace(str[end - 1])) {
  128. end -= 1;
  129. }
  130. return str.substr(start, end - start);
  131. }
  132. static bool is_float_close(float a, float b, float abs_tol) {
  133. // Check for non-negative tolerance
  134. if (abs_tol < 0.0) {
  135. throw std::invalid_argument("Tolerance must be non-negative");
  136. }
  137. // Exact equality check
  138. if (a == b) {
  139. return true;
  140. }
  141. // Check for infinities
  142. if (std::isinf(a) || std::isinf(b)) {
  143. return false;
  144. }
  145. // Regular comparison using the provided absolute tolerance
  146. return std::fabs(b - a) <= abs_tol;
  147. }
  148. static void zeros(std::ofstream & file, size_t n) {
  149. char zero = 0;
  150. for (size_t i = 0; i < n; ++i) {
  151. file.write(&zero, 1);
  152. }
  153. }
  154. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  155. static std::string format(const char * fmt, ...) {
  156. va_list ap;
  157. va_list ap2;
  158. va_start(ap, fmt);
  159. va_copy(ap2, ap);
  160. int size = vsnprintf(NULL, 0, fmt, ap);
  161. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  162. std::vector<char> buf(size + 1);
  163. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  164. GGML_ASSERT(size2 == size);
  165. va_end(ap2);
  166. va_end(ap);
  167. return std::string(buf.data(), size);
  168. }
  169. //
  170. // gguf constants (sync with gguf.py)
  171. //
  172. enum llm_arch {
  173. LLM_ARCH_LLAMA,
  174. LLM_ARCH_MLLAMA,
  175. LLM_ARCH_FALCON,
  176. LLM_ARCH_BAICHUAN,
  177. LLM_ARCH_GROK,
  178. LLM_ARCH_GPT2,
  179. LLM_ARCH_GPTJ,
  180. LLM_ARCH_GPTNEOX,
  181. LLM_ARCH_MPT,
  182. LLM_ARCH_STARCODER,
  183. LLM_ARCH_REFACT,
  184. LLM_ARCH_BERT,
  185. LLM_ARCH_NOMIC_BERT,
  186. LLM_ARCH_JINA_BERT_V2,
  187. LLM_ARCH_BLOOM,
  188. LLM_ARCH_STABLELM,
  189. LLM_ARCH_QWEN,
  190. LLM_ARCH_QWEN2,
  191. LLM_ARCH_QWEN2MOE,
  192. LLM_ARCH_PHI2,
  193. LLM_ARCH_PHI3,
  194. LLM_ARCH_PLAMO,
  195. LLM_ARCH_CODESHELL,
  196. LLM_ARCH_ORION,
  197. LLM_ARCH_INTERNLM2,
  198. LLM_ARCH_MINICPM,
  199. LLM_ARCH_MINICPM3,
  200. LLM_ARCH_GEMMA,
  201. LLM_ARCH_GEMMA2,
  202. LLM_ARCH_STARCODER2,
  203. LLM_ARCH_MAMBA,
  204. LLM_ARCH_XVERSE,
  205. LLM_ARCH_COMMAND_R,
  206. LLM_ARCH_DBRX,
  207. LLM_ARCH_OLMO,
  208. LLM_ARCH_OLMOE,
  209. LLM_ARCH_OPENELM,
  210. LLM_ARCH_ARCTIC,
  211. LLM_ARCH_DEEPSEEK2,
  212. LLM_ARCH_CHATGLM,
  213. LLM_ARCH_BITNET,
  214. LLM_ARCH_T5,
  215. LLM_ARCH_T5ENCODER,
  216. LLM_ARCH_JAIS,
  217. LLM_ARCH_NEMOTRON,
  218. LLM_ARCH_EXAONE,
  219. LLM_ARCH_RWKV6,
  220. LLM_ARCH_GRANITE,
  221. LLM_ARCH_GRANITE_MOE,
  222. LLM_ARCH_CHAMELEON,
  223. LLM_ARCH_SOLAR,
  224. LLM_ARCH_UNKNOWN,
  225. };
  226. static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  227. { LLM_ARCH_LLAMA, "llama" },
  228. { LLM_ARCH_MLLAMA, "mllama" },
  229. { LLM_ARCH_FALCON, "falcon" },
  230. { LLM_ARCH_GROK, "grok" },
  231. { LLM_ARCH_GPT2, "gpt2" },
  232. { LLM_ARCH_GPTJ, "gptj" },
  233. { LLM_ARCH_GPTNEOX, "gptneox" },
  234. { LLM_ARCH_MPT, "mpt" },
  235. { LLM_ARCH_BAICHUAN, "baichuan" },
  236. { LLM_ARCH_STARCODER, "starcoder" },
  237. { LLM_ARCH_REFACT, "refact" },
  238. { LLM_ARCH_BERT, "bert" },
  239. { LLM_ARCH_NOMIC_BERT, "nomic-bert" },
  240. { LLM_ARCH_JINA_BERT_V2, "jina-bert-v2" },
  241. { LLM_ARCH_BLOOM, "bloom" },
  242. { LLM_ARCH_STABLELM, "stablelm" },
  243. { LLM_ARCH_QWEN, "qwen" },
  244. { LLM_ARCH_QWEN2, "qwen2" },
  245. { LLM_ARCH_QWEN2MOE, "qwen2moe" },
  246. { LLM_ARCH_PHI2, "phi2" },
  247. { LLM_ARCH_PHI3, "phi3" },
  248. { LLM_ARCH_PLAMO, "plamo" },
  249. { LLM_ARCH_CODESHELL, "codeshell" },
  250. { LLM_ARCH_ORION, "orion" },
  251. { LLM_ARCH_INTERNLM2, "internlm2" },
  252. { LLM_ARCH_MINICPM, "minicpm" },
  253. { LLM_ARCH_MINICPM3, "minicpm3" },
  254. { LLM_ARCH_GEMMA, "gemma" },
  255. { LLM_ARCH_GEMMA2, "gemma2" },
  256. { LLM_ARCH_STARCODER2, "starcoder2" },
  257. { LLM_ARCH_MAMBA, "mamba" },
  258. { LLM_ARCH_XVERSE, "xverse" },
  259. { LLM_ARCH_COMMAND_R, "command-r" },
  260. { LLM_ARCH_DBRX, "dbrx" },
  261. { LLM_ARCH_OLMO, "olmo" },
  262. { LLM_ARCH_OLMOE, "olmoe" },
  263. { LLM_ARCH_OPENELM, "openelm" },
  264. { LLM_ARCH_ARCTIC, "arctic" },
  265. { LLM_ARCH_DEEPSEEK2, "deepseek2" },
  266. { LLM_ARCH_CHATGLM, "chatglm" },
  267. { LLM_ARCH_BITNET, "bitnet" },
  268. { LLM_ARCH_T5, "t5" },
  269. { LLM_ARCH_T5ENCODER, "t5encoder" },
  270. { LLM_ARCH_JAIS, "jais" },
  271. { LLM_ARCH_NEMOTRON, "nemotron" },
  272. { LLM_ARCH_EXAONE, "exaone" },
  273. { LLM_ARCH_RWKV6, "rwkv6" },
  274. { LLM_ARCH_GRANITE, "granite" },
  275. { LLM_ARCH_GRANITE_MOE, "granitemoe" },
  276. { LLM_ARCH_CHAMELEON, "chameleon" },
  277. { LLM_ARCH_SOLAR, "solar" },
  278. { LLM_ARCH_UNKNOWN, "(unknown)" },
  279. };
  280. enum llm_kv {
  281. LLM_KV_GENERAL_TYPE,
  282. LLM_KV_GENERAL_ARCHITECTURE,
  283. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  284. LLM_KV_GENERAL_ALIGNMENT,
  285. LLM_KV_GENERAL_NAME,
  286. LLM_KV_GENERAL_AUTHOR,
  287. LLM_KV_GENERAL_VERSION,
  288. LLM_KV_GENERAL_URL,
  289. LLM_KV_GENERAL_DESCRIPTION,
  290. LLM_KV_GENERAL_LICENSE,
  291. LLM_KV_GENERAL_SOURCE_URL,
  292. LLM_KV_GENERAL_SOURCE_HF_REPO,
  293. LLM_KV_VOCAB_SIZE,
  294. LLM_KV_CONTEXT_LENGTH,
  295. LLM_KV_EMBEDDING_LENGTH,
  296. LLM_KV_BLOCK_COUNT,
  297. LLM_KV_LEADING_DENSE_BLOCK_COUNT,
  298. LLM_KV_FEED_FORWARD_LENGTH,
  299. LLM_KV_EXPERT_FEED_FORWARD_LENGTH,
  300. LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH,
  301. LLM_KV_USE_PARALLEL_RESIDUAL,
  302. LLM_KV_TENSOR_DATA_LAYOUT,
  303. LLM_KV_EXPERT_COUNT,
  304. LLM_KV_EXPERT_USED_COUNT,
  305. LLM_KV_EXPERT_SHARED_COUNT,
  306. LLM_KV_EXPERT_WEIGHTS_SCALE,
  307. LLM_KV_POOLING_TYPE,
  308. LLM_KV_LOGIT_SCALE,
  309. LLM_KV_DECODER_START_TOKEN_ID,
  310. LLM_KV_ATTN_LOGIT_SOFTCAPPING,
  311. LLM_KV_FINAL_LOGIT_SOFTCAPPING,
  312. LLM_KV_SWIN_NORM,
  313. LLM_KV_RESCALE_EVERY_N_LAYERS,
  314. LLM_KV_TIME_MIX_EXTRA_DIM,
  315. LLM_KV_TIME_DECAY_EXTRA_DIM,
  316. LLM_KV_RESIDUAL_SCALE,
  317. LLM_KV_EMBEDDING_SCALE,
  318. LLM_KV_ATTENTION_HEAD_COUNT,
  319. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  320. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  321. LLM_KV_ATTENTION_CLAMP_KQV,
  322. LLM_KV_ATTENTION_KEY_LENGTH,
  323. LLM_KV_ATTENTION_VALUE_LENGTH,
  324. LLM_KV_ATTENTION_LAYERNORM_EPS,
  325. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  326. LLM_KV_ATTENTION_CAUSAL,
  327. LLM_KV_ATTENTION_Q_LORA_RANK,
  328. LLM_KV_ATTENTION_KV_LORA_RANK,
  329. LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT,
  330. LLM_KV_ATTENTION_SLIDING_WINDOW,
  331. LLM_KV_ATTENTION_SCALE,
  332. LLM_KV_ATTENTION_BLOCK_SKIP_CONNECTION,
  333. LLM_KV_ATTENTION_CROSS_ATTENTION_LAYERS,
  334. LLM_KV_ROPE_DIMENSION_COUNT,
  335. LLM_KV_ROPE_FREQ_BASE,
  336. LLM_KV_ROPE_SCALE_LINEAR,
  337. LLM_KV_ROPE_SCALING_TYPE,
  338. LLM_KV_ROPE_SCALING_FACTOR,
  339. LLM_KV_ROPE_SCALING_ATTN_FACTOR,
  340. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  341. LLM_KV_ROPE_SCALING_FINETUNED,
  342. LLM_KV_ROPE_SCALING_YARN_LOG_MUL,
  343. LLM_KV_SPLIT_NO,
  344. LLM_KV_SPLIT_COUNT,
  345. LLM_KV_SPLIT_TENSORS_COUNT,
  346. LLM_KV_SSM_INNER_SIZE,
  347. LLM_KV_SSM_CONV_KERNEL,
  348. LLM_KV_SSM_STATE_SIZE,
  349. LLM_KV_SSM_TIME_STEP_RANK,
  350. LLM_KV_SSM_DT_B_C_RMS,
  351. LLM_KV_WKV_HEAD_SIZE,
  352. LLM_KV_TOKENIZER_MODEL,
  353. LLM_KV_TOKENIZER_PRE,
  354. LLM_KV_TOKENIZER_LIST,
  355. LLM_KV_TOKENIZER_TOKEN_TYPE,
  356. LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT,
  357. LLM_KV_TOKENIZER_SCORES,
  358. LLM_KV_TOKENIZER_MERGES,
  359. LLM_KV_TOKENIZER_BOS_ID,
  360. LLM_KV_TOKENIZER_EOS_ID,
  361. LLM_KV_TOKENIZER_UNK_ID,
  362. LLM_KV_TOKENIZER_SEP_ID,
  363. LLM_KV_TOKENIZER_PAD_ID,
  364. LLM_KV_TOKENIZER_CLS_ID,
  365. LLM_KV_TOKENIZER_MASK_ID,
  366. LLM_KV_TOKENIZER_ADD_BOS,
  367. LLM_KV_TOKENIZER_ADD_EOS,
  368. LLM_KV_TOKENIZER_ADD_PREFIX,
  369. LLM_KV_TOKENIZER_REMOVE_EXTRA_WS,
  370. LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP,
  371. LLM_KV_TOKENIZER_HF_JSON,
  372. LLM_KV_TOKENIZER_RWKV,
  373. LLM_KV_TOKENIZER_PREFIX_ID,
  374. LLM_KV_TOKENIZER_SUFFIX_ID,
  375. LLM_KV_TOKENIZER_MIDDLE_ID,
  376. LLM_KV_TOKENIZER_EOT_ID,
  377. LLM_KV_TOKENIZER_EOM_ID,
  378. LLM_KV_ADAPTER_TYPE,
  379. LLM_KV_ADAPTER_LORA_ALPHA,
  380. };
  381. static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
  382. { LLM_KV_GENERAL_TYPE, "general.type" },
  383. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  384. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  385. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  386. { LLM_KV_GENERAL_NAME, "general.name" },
  387. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  388. { LLM_KV_GENERAL_VERSION, "general.version" },
  389. { LLM_KV_GENERAL_URL, "general.url" },
  390. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  391. { LLM_KV_GENERAL_LICENSE, "general.license" },
  392. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  393. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  394. { LLM_KV_VOCAB_SIZE, "%s.vocab_size" },
  395. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  396. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  397. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  398. { LLM_KV_LEADING_DENSE_BLOCK_COUNT, "%s.leading_dense_block_count" },
  399. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  400. { LLM_KV_EXPERT_FEED_FORWARD_LENGTH, "%s.expert_feed_forward_length" },
  401. { LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, "%s.expert_shared_feed_forward_length" },
  402. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  403. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  404. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  405. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  406. { LLM_KV_EXPERT_SHARED_COUNT, "%s.expert_shared_count" },
  407. { LLM_KV_EXPERT_WEIGHTS_SCALE, "%s.expert_weights_scale" },
  408. { LLM_KV_POOLING_TYPE, "%s.pooling_type" },
  409. { LLM_KV_LOGIT_SCALE, "%s.logit_scale" },
  410. { LLM_KV_DECODER_START_TOKEN_ID, "%s.decoder_start_token_id" },
  411. { LLM_KV_ATTN_LOGIT_SOFTCAPPING, "%s.attn_logit_softcapping" },
  412. { LLM_KV_FINAL_LOGIT_SOFTCAPPING, "%s.final_logit_softcapping" },
  413. { LLM_KV_SWIN_NORM, "%s.swin_norm" },
  414. { LLM_KV_RESCALE_EVERY_N_LAYERS, "%s.rescale_every_n_layers" },
  415. { LLM_KV_TIME_MIX_EXTRA_DIM, "%s.time_mix_extra_dim" },
  416. { LLM_KV_TIME_DECAY_EXTRA_DIM, "%s.time_decay_extra_dim" },
  417. { LLM_KV_RESIDUAL_SCALE, "%s.residual_scale" },
  418. { LLM_KV_EMBEDDING_SCALE, "%s.embedding_scale" },
  419. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  420. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  421. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  422. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  423. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  424. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  425. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  426. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  427. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  428. { LLM_KV_ATTENTION_Q_LORA_RANK, "%s.attention.q_lora_rank" },
  429. { LLM_KV_ATTENTION_KV_LORA_RANK, "%s.attention.kv_lora_rank" },
  430. { LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, "%s.attention.relative_buckets_count" },
  431. { LLM_KV_ATTENTION_SLIDING_WINDOW, "%s.attention.sliding_window" },
  432. { LLM_KV_ATTENTION_SCALE, "%s.attention.scale" },
  433. { LLM_KV_ATTENTION_BLOCK_SKIP_CONNECTION, "%s.attention.block_skip_connection.%d" },
  434. { LLM_KV_ATTENTION_CROSS_ATTENTION_LAYERS, "%s.attention.cross_attention_layers" },
  435. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  436. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  437. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  438. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  439. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  440. { LLM_KV_ROPE_SCALING_ATTN_FACTOR, "%s.rope.scaling.attn_factor" },
  441. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  442. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  443. { LLM_KV_ROPE_SCALING_YARN_LOG_MUL, "%s.rope.scaling.yarn_log_multiplier" },
  444. { LLM_KV_SPLIT_NO, "split.no" },
  445. { LLM_KV_SPLIT_COUNT, "split.count" },
  446. { LLM_KV_SPLIT_TENSORS_COUNT, "split.tensors.count" },
  447. { LLM_KV_SSM_CONV_KERNEL, "%s.ssm.conv_kernel" },
  448. { LLM_KV_SSM_INNER_SIZE, "%s.ssm.inner_size" },
  449. { LLM_KV_SSM_STATE_SIZE, "%s.ssm.state_size" },
  450. { LLM_KV_SSM_TIME_STEP_RANK, "%s.ssm.time_step_rank" },
  451. { LLM_KV_SSM_DT_B_C_RMS, "%s.ssm.dt_b_c_rms" },
  452. { LLM_KV_WKV_HEAD_SIZE, "%s.wkv.head_size" },
  453. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  454. { LLM_KV_TOKENIZER_PRE, "tokenizer.ggml.pre" },
  455. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  456. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  457. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  458. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  459. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  460. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  461. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  462. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  463. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  464. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  465. { LLM_KV_TOKENIZER_CLS_ID, "tokenizer.ggml.cls_token_id" },
  466. { LLM_KV_TOKENIZER_MASK_ID, "tokenizer.ggml.mask_token_id" },
  467. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  468. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  469. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  470. { LLM_KV_TOKENIZER_REMOVE_EXTRA_WS, "tokenizer.ggml.remove_extra_whitespaces" },
  471. { LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP, "tokenizer.ggml.precompiled_charsmap" },
  472. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  473. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  474. { LLM_KV_TOKENIZER_PREFIX_ID, "tokenizer.ggml.prefix_token_id" },
  475. { LLM_KV_TOKENIZER_SUFFIX_ID, "tokenizer.ggml.suffix_token_id" },
  476. { LLM_KV_TOKENIZER_MIDDLE_ID, "tokenizer.ggml.middle_token_id" },
  477. { LLM_KV_TOKENIZER_EOT_ID, "tokenizer.ggml.eot_token_id" },
  478. { LLM_KV_TOKENIZER_EOM_ID, "tokenizer.ggml.eom_token_id" },
  479. { LLM_KV_ADAPTER_TYPE, "adapter.type" },
  480. { LLM_KV_ADAPTER_LORA_ALPHA, "adapter.lora.alpha" },
  481. };
  482. struct LLM_KV {
  483. LLM_KV(llm_arch arch) : arch(arch) {}
  484. llm_arch arch;
  485. std::string operator()(llm_kv kv) const {
  486. return ::format(LLM_KV_NAMES.at(kv), LLM_ARCH_NAMES.at(arch));
  487. }
  488. };
  489. enum llm_tensor {
  490. LLM_TENSOR_TOKEN_EMBD,
  491. LLM_TENSOR_TOKEN_EMBD_NORM,
  492. LLM_TENSOR_TOKEN_TYPES,
  493. LLM_TENSOR_POS_EMBD,
  494. LLM_TENSOR_OUTPUT,
  495. LLM_TENSOR_OUTPUT_NORM,
  496. LLM_TENSOR_ROPE_FREQS,
  497. LLM_TENSOR_ROPE_FACTORS_LONG,
  498. LLM_TENSOR_ROPE_FACTORS_SHORT,
  499. LLM_TENSOR_ATTN_Q,
  500. LLM_TENSOR_ATTN_K,
  501. LLM_TENSOR_ATTN_V,
  502. LLM_TENSOR_ATTN_QKV,
  503. LLM_TENSOR_ATTN_OUT,
  504. LLM_TENSOR_ATTN_NORM,
  505. LLM_TENSOR_ATTN_NORM_2,
  506. LLM_TENSOR_ATTN_OUT_NORM,
  507. LLM_TENSOR_ATTN_POST_NORM,
  508. LLM_TENSOR_ATTN_ROT_EMBD,
  509. LLM_TENSOR_FFN_GATE_INP,
  510. LLM_TENSOR_FFN_GATE_INP_SHEXP,
  511. LLM_TENSOR_FFN_NORM,
  512. LLM_TENSOR_FFN_POST_NORM,
  513. LLM_TENSOR_FFN_GATE,
  514. LLM_TENSOR_FFN_DOWN,
  515. LLM_TENSOR_FFN_UP,
  516. LLM_TENSOR_FFN_ACT,
  517. LLM_TENSOR_FFN_DOWN_EXP, // split experts for backward compatibility
  518. LLM_TENSOR_FFN_GATE_EXP,
  519. LLM_TENSOR_FFN_UP_EXP,
  520. LLM_TENSOR_FFN_NORM_EXPS,
  521. LLM_TENSOR_FFN_DOWN_EXPS, // merged experts
  522. LLM_TENSOR_FFN_GATE_EXPS,
  523. LLM_TENSOR_FFN_UP_EXPS,
  524. LLM_TENSOR_FFN_DOWN_SHEXP,
  525. LLM_TENSOR_FFN_GATE_SHEXP,
  526. LLM_TENSOR_FFN_UP_SHEXP,
  527. LLM_TENSOR_ATTN_Q_NORM,
  528. LLM_TENSOR_ATTN_K_NORM,
  529. LLM_TENSOR_LAYER_OUT_NORM,
  530. LLM_TENSOR_SSM_IN,
  531. LLM_TENSOR_SSM_CONV1D,
  532. LLM_TENSOR_SSM_X,
  533. LLM_TENSOR_SSM_DT,
  534. LLM_TENSOR_SSM_A,
  535. LLM_TENSOR_SSM_D,
  536. LLM_TENSOR_SSM_OUT,
  537. LLM_TENSOR_TIME_MIX_W1,
  538. LLM_TENSOR_TIME_MIX_W2,
  539. LLM_TENSOR_TIME_MIX_LERP_X,
  540. LLM_TENSOR_TIME_MIX_LERP_W,
  541. LLM_TENSOR_TIME_MIX_LERP_K,
  542. LLM_TENSOR_TIME_MIX_LERP_V,
  543. LLM_TENSOR_TIME_MIX_LERP_R,
  544. LLM_TENSOR_TIME_MIX_LERP_G,
  545. LLM_TENSOR_TIME_MIX_FIRST,
  546. LLM_TENSOR_TIME_MIX_DECAY,
  547. LLM_TENSOR_TIME_MIX_DECAY_W1,
  548. LLM_TENSOR_TIME_MIX_DECAY_W2,
  549. LLM_TENSOR_TIME_MIX_KEY,
  550. LLM_TENSOR_TIME_MIX_VALUE,
  551. LLM_TENSOR_TIME_MIX_RECEPTANCE,
  552. LLM_TENSOR_TIME_MIX_GATE,
  553. LLM_TENSOR_TIME_MIX_LN,
  554. LLM_TENSOR_TIME_MIX_OUTPUT,
  555. LLM_TENSOR_CHANNEL_MIX_LERP_K,
  556. LLM_TENSOR_CHANNEL_MIX_LERP_R,
  557. LLM_TENSOR_CHANNEL_MIX_KEY,
  558. LLM_TENSOR_CHANNEL_MIX_RECEPTANCE,
  559. LLM_TENSOR_CHANNEL_MIX_VALUE,
  560. LLM_TENSOR_ATTN_Q_A,
  561. LLM_TENSOR_ATTN_Q_B,
  562. LLM_TENSOR_ATTN_KV_A_MQA,
  563. LLM_TENSOR_ATTN_KV_B,
  564. LLM_TENSOR_ATTN_Q_A_NORM,
  565. LLM_TENSOR_ATTN_KV_A_NORM,
  566. LLM_TENSOR_ATTN_SUB_NORM,
  567. LLM_TENSOR_FFN_SUB_NORM,
  568. LLM_TENSOR_DEC_ATTN_NORM,
  569. LLM_TENSOR_DEC_ATTN_Q,
  570. LLM_TENSOR_DEC_ATTN_K,
  571. LLM_TENSOR_DEC_ATTN_V,
  572. LLM_TENSOR_DEC_ATTN_OUT,
  573. LLM_TENSOR_DEC_ATTN_REL_B,
  574. LLM_TENSOR_DEC_CROSS_ATTN_NORM,
  575. LLM_TENSOR_DEC_CROSS_ATTN_Q,
  576. LLM_TENSOR_DEC_CROSS_ATTN_K,
  577. LLM_TENSOR_DEC_CROSS_ATTN_V,
  578. LLM_TENSOR_DEC_CROSS_ATTN_OUT,
  579. LLM_TENSOR_DEC_CROSS_ATTN_REL_B,
  580. LLM_TENSOR_DEC_FFN_NORM,
  581. LLM_TENSOR_DEC_FFN_GATE,
  582. LLM_TENSOR_DEC_FFN_DOWN,
  583. LLM_TENSOR_DEC_FFN_UP,
  584. LLM_TENSOR_DEC_OUTPUT_NORM,
  585. LLM_TENSOR_ENC_ATTN_NORM,
  586. LLM_TENSOR_ENC_ATTN_Q,
  587. LLM_TENSOR_ENC_ATTN_K,
  588. LLM_TENSOR_ENC_ATTN_V,
  589. LLM_TENSOR_ENC_ATTN_OUT,
  590. LLM_TENSOR_ENC_ATTN_REL_B,
  591. LLM_TENSOR_ENC_FFN_NORM,
  592. LLM_TENSOR_ENC_FFN_GATE,
  593. LLM_TENSOR_ENC_FFN_DOWN,
  594. LLM_TENSOR_ENC_FFN_UP,
  595. LLM_TENSOR_ENC_OUTPUT_NORM,
  596. LLM_TENSOR_CLS,
  597. LLM_TENSOR_CLS_OUT,
  598. LLM_TENSOR_BSKCN_TV,
  599. LLM_TENSOR_CROSS_ATTN_K_NORM,
  600. LLM_TENSOR_CROSS_ATTN_K_PROJ,
  601. LLM_TENSOR_CROSS_ATTN_O_PROJ,
  602. LLM_TENSOR_CROSS_ATTN_Q_NORM,
  603. LLM_TENSOR_CROSS_ATTN_Q_PROJ,
  604. LLM_TENSOR_CROSS_ATTN_V_PROJ,
  605. LLM_TENSOR_CROSS_ATTN_ATTN_GATE,
  606. LLM_TENSOR_CROSS_ATTN_MLP_GATE,
  607. };
  608. static const std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  609. {
  610. LLM_ARCH_LLAMA,
  611. {
  612. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  613. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  614. { LLM_TENSOR_OUTPUT, "output" },
  615. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  616. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  617. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  618. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  619. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  620. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  621. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  622. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  623. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  624. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  625. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  626. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  627. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  628. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  629. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  630. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  631. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  632. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  633. },
  634. },
  635. {
  636. LLM_ARCH_MLLAMA,
  637. {
  638. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  639. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  640. { LLM_TENSOR_OUTPUT, "output" },
  641. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  642. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  643. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  644. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  645. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  646. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  647. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  648. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  649. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  650. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  651. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  652. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  653. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  654. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  655. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  656. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  657. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  658. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  659. { LLM_TENSOR_CROSS_ATTN_K_NORM, "blk.%d.cross_attn_k_norm" },
  660. { LLM_TENSOR_CROSS_ATTN_K_PROJ, "blk.%d.cross_attn_k_proj" },
  661. { LLM_TENSOR_CROSS_ATTN_O_PROJ, "blk.%d.cross_attn_o_proj" },
  662. { LLM_TENSOR_CROSS_ATTN_Q_NORM, "blk.%d.cross_attn_q_norm" },
  663. { LLM_TENSOR_CROSS_ATTN_Q_PROJ, "blk.%d.cross_attn_q_proj" },
  664. { LLM_TENSOR_CROSS_ATTN_V_PROJ, "blk.%d.cross_attn_v_proj" },
  665. { LLM_TENSOR_CROSS_ATTN_ATTN_GATE, "blk.%d.cross_attn_attn_gate" },
  666. { LLM_TENSOR_CROSS_ATTN_MLP_GATE, "blk.%d.cross_attn_mlp_gate" },
  667. },
  668. },
  669. {
  670. LLM_ARCH_BAICHUAN,
  671. {
  672. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  673. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  674. { LLM_TENSOR_OUTPUT, "output" },
  675. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  676. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  677. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  678. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  679. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  680. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  681. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  682. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  683. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  684. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  685. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  686. },
  687. },
  688. {
  689. LLM_ARCH_FALCON,
  690. {
  691. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  692. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  693. { LLM_TENSOR_OUTPUT, "output" },
  694. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  695. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  696. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  697. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  698. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  699. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  700. },
  701. },
  702. {
  703. LLM_ARCH_GROK,
  704. {
  705. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  706. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  707. { LLM_TENSOR_OUTPUT, "output" },
  708. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  709. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  710. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  711. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  712. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  713. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  714. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  715. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  716. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  717. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  718. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  719. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  720. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  721. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  722. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  723. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  724. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  725. },
  726. },
  727. {
  728. LLM_ARCH_GPT2,
  729. {
  730. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  731. { LLM_TENSOR_POS_EMBD, "position_embd" },
  732. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  733. { LLM_TENSOR_OUTPUT, "output" },
  734. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  735. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  736. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  737. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  738. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  739. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  740. },
  741. },
  742. {
  743. LLM_ARCH_GPTJ,
  744. {
  745. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  746. },
  747. },
  748. {
  749. LLM_ARCH_GPTNEOX,
  750. {
  751. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  752. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  753. { LLM_TENSOR_OUTPUT, "output" },
  754. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  755. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  756. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  757. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  758. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  759. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  760. },
  761. },
  762. {
  763. LLM_ARCH_MPT,
  764. {
  765. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  766. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  767. { LLM_TENSOR_OUTPUT, "output"},
  768. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  769. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  770. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  771. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  772. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  773. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  774. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  775. { LLM_TENSOR_POS_EMBD, "position_embd" },
  776. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  777. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  778. },
  779. },
  780. {
  781. LLM_ARCH_STARCODER,
  782. {
  783. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  784. { LLM_TENSOR_POS_EMBD, "position_embd" },
  785. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  786. { LLM_TENSOR_OUTPUT, "output" },
  787. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  788. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  789. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  790. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  791. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  792. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  793. },
  794. },
  795. {
  796. LLM_ARCH_REFACT,
  797. {
  798. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  799. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  800. { LLM_TENSOR_OUTPUT, "output" },
  801. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  802. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  803. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  804. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  805. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  806. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  807. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  808. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  809. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  810. },
  811. },
  812. {
  813. LLM_ARCH_BERT,
  814. {
  815. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  816. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  817. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  818. { LLM_TENSOR_POS_EMBD, "position_embd" },
  819. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  820. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  821. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  822. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  823. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  824. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  825. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  826. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  827. { LLM_TENSOR_CLS, "cls" },
  828. { LLM_TENSOR_CLS_OUT, "cls.output" },
  829. },
  830. },
  831. {
  832. LLM_ARCH_NOMIC_BERT,
  833. {
  834. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  835. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  836. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  837. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  838. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  839. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  840. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  841. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  842. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  843. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  844. },
  845. },
  846. {
  847. LLM_ARCH_JINA_BERT_V2,
  848. {
  849. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  850. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  851. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  852. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  853. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  854. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  855. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  856. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  857. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  858. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  859. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  860. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  861. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  862. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  863. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  864. { LLM_TENSOR_CLS, "cls" },
  865. },
  866. },
  867. {
  868. LLM_ARCH_BLOOM,
  869. {
  870. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  871. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  872. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  873. { LLM_TENSOR_OUTPUT, "output" },
  874. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  875. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  876. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  877. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  878. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  879. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  880. },
  881. },
  882. {
  883. LLM_ARCH_STABLELM,
  884. {
  885. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  886. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  887. { LLM_TENSOR_OUTPUT, "output" },
  888. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  889. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  890. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  891. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  892. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  893. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  894. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  895. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  896. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  897. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  898. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  899. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  900. },
  901. },
  902. {
  903. LLM_ARCH_QWEN,
  904. {
  905. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  906. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  907. { LLM_TENSOR_OUTPUT, "output" },
  908. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  909. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  910. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  911. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  912. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  913. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  914. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  915. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  916. },
  917. },
  918. {
  919. LLM_ARCH_QWEN2,
  920. {
  921. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  922. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  923. { LLM_TENSOR_OUTPUT, "output" },
  924. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  925. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  926. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  927. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  928. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  929. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  930. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  931. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  932. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  933. },
  934. },
  935. {
  936. LLM_ARCH_QWEN2MOE,
  937. {
  938. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  939. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  940. { LLM_TENSOR_OUTPUT, "output" },
  941. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  942. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  943. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  944. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  945. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  946. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  947. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  948. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  949. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  950. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  951. { LLM_TENSOR_FFN_GATE_INP_SHEXP, "blk.%d.ffn_gate_inp_shexp" },
  952. { LLM_TENSOR_FFN_GATE_SHEXP, "blk.%d.ffn_gate_shexp" },
  953. { LLM_TENSOR_FFN_DOWN_SHEXP, "blk.%d.ffn_down_shexp" },
  954. { LLM_TENSOR_FFN_UP_SHEXP, "blk.%d.ffn_up_shexp" },
  955. },
  956. },
  957. {
  958. LLM_ARCH_PHI2,
  959. {
  960. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  961. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  962. { LLM_TENSOR_OUTPUT, "output" },
  963. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  964. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  965. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  966. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  967. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  968. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  969. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  970. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  971. },
  972. },
  973. {
  974. LLM_ARCH_PHI3,
  975. {
  976. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  977. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  978. { LLM_TENSOR_OUTPUT, "output" },
  979. { LLM_TENSOR_ROPE_FACTORS_LONG, "rope_factors_long" },
  980. { LLM_TENSOR_ROPE_FACTORS_SHORT, "rope_factors_short" },
  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_NORM, "blk.%d.ffn_norm" },
  988. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  989. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  990. },
  991. },
  992. {
  993. LLM_ARCH_PLAMO,
  994. {
  995. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  996. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  997. { LLM_TENSOR_OUTPUT, "output" },
  998. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  999. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1000. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1001. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1002. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1003. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1004. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1005. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1006. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1007. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1008. },
  1009. },
  1010. {
  1011. LLM_ARCH_CODESHELL,
  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_QKV, "blk.%d.attn_qkv" },
  1022. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1023. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1024. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1025. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1026. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1027. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1028. },
  1029. },
  1030. {
  1031. LLM_ARCH_ORION,
  1032. {
  1033. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1034. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1035. { LLM_TENSOR_OUTPUT, "output" },
  1036. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1037. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1038. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1039. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1040. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1041. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1042. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1043. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1044. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1045. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1046. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1047. },
  1048. },
  1049. {
  1050. LLM_ARCH_INTERNLM2,
  1051. {
  1052. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1053. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1054. { LLM_TENSOR_OUTPUT, "output" },
  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_FFN_NORM, "blk.%d.ffn_norm" },
  1061. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1062. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1063. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1064. },
  1065. },
  1066. {
  1067. LLM_ARCH_MINICPM,
  1068. {
  1069. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1070. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1071. { LLM_TENSOR_OUTPUT, "output" },
  1072. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  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_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1079. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1080. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1081. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1082. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1083. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1084. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  1085. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  1086. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  1087. },
  1088. },
  1089. {
  1090. LLM_ARCH_MINICPM3,
  1091. {
  1092. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1093. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1094. { LLM_TENSOR_OUTPUT, "output" },
  1095. { LLM_TENSOR_ROPE_FACTORS_LONG, "rope_factors_long" },
  1096. { LLM_TENSOR_ROPE_FACTORS_SHORT, "rope_factors_short" },
  1097. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1098. { LLM_TENSOR_ATTN_Q_A_NORM, "blk.%d.attn_q_a_norm" },
  1099. { LLM_TENSOR_ATTN_KV_A_NORM, "blk.%d.attn_kv_a_norm" },
  1100. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1101. { LLM_TENSOR_ATTN_Q_A, "blk.%d.attn_q_a" },
  1102. { LLM_TENSOR_ATTN_Q_B, "blk.%d.attn_q_b" },
  1103. { LLM_TENSOR_ATTN_KV_A_MQA, "blk.%d.attn_kv_a_mqa" },
  1104. { LLM_TENSOR_ATTN_KV_B, "blk.%d.attn_kv_b" },
  1105. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1106. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1107. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1108. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1109. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1110. },
  1111. },
  1112. {
  1113. LLM_ARCH_GEMMA,
  1114. {
  1115. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1116. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1117. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1118. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1119. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1120. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1121. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1122. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1123. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1124. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1125. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1126. },
  1127. },
  1128. {
  1129. LLM_ARCH_GEMMA2,
  1130. {
  1131. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1132. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1133. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1134. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1135. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1136. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1137. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1138. { LLM_TENSOR_ATTN_POST_NORM, "blk.%d.post_attention_norm" },
  1139. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1140. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1141. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1142. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1143. { LLM_TENSOR_FFN_POST_NORM, "blk.%d.post_ffw_norm" },
  1144. },
  1145. },
  1146. {
  1147. LLM_ARCH_STARCODER2,
  1148. {
  1149. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1150. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1151. { LLM_TENSOR_OUTPUT, "output" },
  1152. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  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_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1159. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1160. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1161. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1162. },
  1163. },
  1164. {
  1165. LLM_ARCH_MAMBA,
  1166. {
  1167. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1168. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1169. { LLM_TENSOR_OUTPUT, "output" },
  1170. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1171. { LLM_TENSOR_SSM_IN, "blk.%d.ssm_in" },
  1172. { LLM_TENSOR_SSM_CONV1D, "blk.%d.ssm_conv1d" },
  1173. { LLM_TENSOR_SSM_X, "blk.%d.ssm_x" },
  1174. { LLM_TENSOR_SSM_DT, "blk.%d.ssm_dt" },
  1175. { LLM_TENSOR_SSM_A, "blk.%d.ssm_a" },
  1176. { LLM_TENSOR_SSM_D, "blk.%d.ssm_d" },
  1177. { LLM_TENSOR_SSM_OUT, "blk.%d.ssm_out" },
  1178. },
  1179. },
  1180. {
  1181. LLM_ARCH_XVERSE,
  1182. {
  1183. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1184. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1185. { LLM_TENSOR_OUTPUT, "output" },
  1186. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1187. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1188. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1189. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1190. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1191. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1192. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1193. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1194. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1195. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1196. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1197. },
  1198. },
  1199. {
  1200. LLM_ARCH_COMMAND_R,
  1201. {
  1202. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1203. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1204. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1205. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1206. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1207. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1208. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1209. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1210. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1211. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1212. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  1213. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  1214. },
  1215. },
  1216. {
  1217. LLM_ARCH_DBRX,
  1218. {
  1219. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1220. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1221. { LLM_TENSOR_OUTPUT, "output" },
  1222. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1223. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1224. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1225. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  1226. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1227. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1228. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1229. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1230. },
  1231. },
  1232. {
  1233. LLM_ARCH_OLMO,
  1234. {
  1235. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1236. { LLM_TENSOR_OUTPUT, "output" },
  1237. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1238. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1239. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1240. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1241. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1242. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1243. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1244. },
  1245. },
  1246. {
  1247. LLM_ARCH_OLMOE,
  1248. {
  1249. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1250. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1251. { LLM_TENSOR_OUTPUT, "output" },
  1252. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1253. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1254. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1255. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1256. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1257. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  1258. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  1259. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1260. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1261. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1262. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1263. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1264. },
  1265. },
  1266. {
  1267. LLM_ARCH_OPENELM,
  1268. {
  1269. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1270. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1271. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1272. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1273. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  1274. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  1275. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1276. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1277. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1278. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1279. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1280. },
  1281. },
  1282. {
  1283. LLM_ARCH_ARCTIC,
  1284. {
  1285. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1286. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1287. { LLM_TENSOR_OUTPUT, "output" },
  1288. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1289. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1290. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1291. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1292. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1293. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1294. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1295. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1296. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1297. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1298. { LLM_TENSOR_FFN_NORM_EXPS, "blk.%d.ffn_norm_exps" },
  1299. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1300. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1301. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1302. },
  1303. },
  1304. {
  1305. LLM_ARCH_DEEPSEEK2,
  1306. {
  1307. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1308. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1309. { LLM_TENSOR_OUTPUT, "output" },
  1310. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1311. { LLM_TENSOR_ATTN_Q_A_NORM, "blk.%d.attn_q_a_norm" },
  1312. { LLM_TENSOR_ATTN_KV_A_NORM, "blk.%d.attn_kv_a_norm" },
  1313. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1314. { LLM_TENSOR_ATTN_Q_A, "blk.%d.attn_q_a" },
  1315. { LLM_TENSOR_ATTN_Q_B, "blk.%d.attn_q_b" },
  1316. { LLM_TENSOR_ATTN_KV_A_MQA, "blk.%d.attn_kv_a_mqa" },
  1317. { LLM_TENSOR_ATTN_KV_B, "blk.%d.attn_kv_b" },
  1318. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1319. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1320. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1321. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1322. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1323. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1324. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1325. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1326. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1327. { LLM_TENSOR_FFN_GATE_INP_SHEXP, "blk.%d.ffn_gate_inp_shexp" },
  1328. { LLM_TENSOR_FFN_GATE_SHEXP, "blk.%d.ffn_gate_shexp" },
  1329. { LLM_TENSOR_FFN_DOWN_SHEXP, "blk.%d.ffn_down_shexp" },
  1330. { LLM_TENSOR_FFN_UP_SHEXP, "blk.%d.ffn_up_shexp" },
  1331. },
  1332. },
  1333. {
  1334. LLM_ARCH_CHATGLM,
  1335. {
  1336. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1337. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1338. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1339. { LLM_TENSOR_OUTPUT, "output" },
  1340. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1341. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1342. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1343. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1344. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1345. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1346. },
  1347. },
  1348. {
  1349. LLM_ARCH_BITNET,
  1350. {
  1351. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1352. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1353. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1354. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1355. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1356. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1357. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1358. { LLM_TENSOR_ATTN_SUB_NORM, "blk.%d.attn_sub_norm" },
  1359. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1360. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1361. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1362. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1363. { LLM_TENSOR_FFN_SUB_NORM, "blk.%d.ffn_sub_norm" },
  1364. },
  1365. },
  1366. {
  1367. LLM_ARCH_T5,
  1368. {
  1369. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1370. { LLM_TENSOR_OUTPUT, "output" },
  1371. { LLM_TENSOR_DEC_OUTPUT_NORM, "dec.output_norm" },
  1372. { LLM_TENSOR_DEC_ATTN_NORM, "dec.blk.%d.attn_norm" },
  1373. { LLM_TENSOR_DEC_ATTN_Q, "dec.blk.%d.attn_q" },
  1374. { LLM_TENSOR_DEC_ATTN_K, "dec.blk.%d.attn_k" },
  1375. { LLM_TENSOR_DEC_ATTN_V, "dec.blk.%d.attn_v" },
  1376. { LLM_TENSOR_DEC_ATTN_OUT, "dec.blk.%d.attn_o" },
  1377. { LLM_TENSOR_DEC_ATTN_REL_B, "dec.blk.%d.attn_rel_b" },
  1378. { LLM_TENSOR_DEC_CROSS_ATTN_NORM, "dec.blk.%d.cross_attn_norm" },
  1379. { LLM_TENSOR_DEC_CROSS_ATTN_Q, "dec.blk.%d.cross_attn_q" },
  1380. { LLM_TENSOR_DEC_CROSS_ATTN_K, "dec.blk.%d.cross_attn_k" },
  1381. { LLM_TENSOR_DEC_CROSS_ATTN_V, "dec.blk.%d.cross_attn_v" },
  1382. { LLM_TENSOR_DEC_CROSS_ATTN_OUT, "dec.blk.%d.cross_attn_o" },
  1383. { LLM_TENSOR_DEC_CROSS_ATTN_REL_B, "dec.blk.%d.cross_attn_rel_b" },
  1384. { LLM_TENSOR_DEC_FFN_NORM, "dec.blk.%d.ffn_norm" },
  1385. { LLM_TENSOR_DEC_FFN_GATE, "dec.blk.%d.ffn_gate" },
  1386. { LLM_TENSOR_DEC_FFN_DOWN, "dec.blk.%d.ffn_down" },
  1387. { LLM_TENSOR_DEC_FFN_UP, "dec.blk.%d.ffn_up" },
  1388. { LLM_TENSOR_ENC_OUTPUT_NORM, "enc.output_norm" },
  1389. { LLM_TENSOR_ENC_ATTN_NORM, "enc.blk.%d.attn_norm" },
  1390. { LLM_TENSOR_ENC_ATTN_Q, "enc.blk.%d.attn_q" },
  1391. { LLM_TENSOR_ENC_ATTN_K, "enc.blk.%d.attn_k" },
  1392. { LLM_TENSOR_ENC_ATTN_V, "enc.blk.%d.attn_v" },
  1393. { LLM_TENSOR_ENC_ATTN_OUT, "enc.blk.%d.attn_o" },
  1394. { LLM_TENSOR_ENC_ATTN_REL_B, "enc.blk.%d.attn_rel_b" },
  1395. { LLM_TENSOR_ENC_FFN_NORM, "enc.blk.%d.ffn_norm" },
  1396. { LLM_TENSOR_ENC_FFN_GATE, "enc.blk.%d.ffn_gate" },
  1397. { LLM_TENSOR_ENC_FFN_DOWN, "enc.blk.%d.ffn_down" },
  1398. { LLM_TENSOR_ENC_FFN_UP, "enc.blk.%d.ffn_up" },
  1399. },
  1400. },
  1401. {
  1402. LLM_ARCH_T5ENCODER,
  1403. {
  1404. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1405. { LLM_TENSOR_OUTPUT, "output" },
  1406. { LLM_TENSOR_ENC_OUTPUT_NORM, "enc.output_norm" },
  1407. { LLM_TENSOR_ENC_ATTN_NORM, "enc.blk.%d.attn_norm" },
  1408. { LLM_TENSOR_ENC_ATTN_Q, "enc.blk.%d.attn_q" },
  1409. { LLM_TENSOR_ENC_ATTN_K, "enc.blk.%d.attn_k" },
  1410. { LLM_TENSOR_ENC_ATTN_V, "enc.blk.%d.attn_v" },
  1411. { LLM_TENSOR_ENC_ATTN_OUT, "enc.blk.%d.attn_o" },
  1412. { LLM_TENSOR_ENC_ATTN_REL_B, "enc.blk.%d.attn_rel_b" },
  1413. { LLM_TENSOR_ENC_FFN_NORM, "enc.blk.%d.ffn_norm" },
  1414. { LLM_TENSOR_ENC_FFN_GATE, "enc.blk.%d.ffn_gate" },
  1415. { LLM_TENSOR_ENC_FFN_DOWN, "enc.blk.%d.ffn_down" },
  1416. { LLM_TENSOR_ENC_FFN_UP, "enc.blk.%d.ffn_up" },
  1417. },
  1418. },
  1419. {
  1420. LLM_ARCH_JAIS,
  1421. {
  1422. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1423. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1424. { LLM_TENSOR_OUTPUT, "output" },
  1425. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1426. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1427. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1428. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1429. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1430. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1431. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1432. },
  1433. },
  1434. {
  1435. LLM_ARCH_NEMOTRON,
  1436. {
  1437. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1438. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1439. { LLM_TENSOR_OUTPUT, "output" },
  1440. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1441. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1442. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1443. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1444. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1445. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1446. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1447. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1448. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1449. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1450. },
  1451. },
  1452. {
  1453. LLM_ARCH_EXAONE,
  1454. {
  1455. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1456. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1457. { LLM_TENSOR_OUTPUT, "output" },
  1458. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1459. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1460. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1461. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1462. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1463. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1464. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1465. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1466. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1467. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1468. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1469. },
  1470. },
  1471. {
  1472. LLM_ARCH_RWKV6,
  1473. {
  1474. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1475. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  1476. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1477. { LLM_TENSOR_OUTPUT, "output" },
  1478. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1479. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  1480. { LLM_TENSOR_TIME_MIX_W1, "blk.%d.time_mix_w1" },
  1481. { LLM_TENSOR_TIME_MIX_W2, "blk.%d.time_mix_w2" },
  1482. { LLM_TENSOR_TIME_MIX_LERP_X, "blk.%d.time_mix_lerp_x" },
  1483. { LLM_TENSOR_TIME_MIX_LERP_W, "blk.%d.time_mix_lerp_w" },
  1484. { LLM_TENSOR_TIME_MIX_LERP_K, "blk.%d.time_mix_lerp_k" },
  1485. { LLM_TENSOR_TIME_MIX_LERP_V, "blk.%d.time_mix_lerp_v" },
  1486. { LLM_TENSOR_TIME_MIX_LERP_R, "blk.%d.time_mix_lerp_r" },
  1487. { LLM_TENSOR_TIME_MIX_LERP_G, "blk.%d.time_mix_lerp_g" },
  1488. { LLM_TENSOR_TIME_MIX_FIRST, "blk.%d.time_mix_first" },
  1489. { LLM_TENSOR_TIME_MIX_DECAY, "blk.%d.time_mix_decay" },
  1490. { LLM_TENSOR_TIME_MIX_DECAY_W1, "blk.%d.time_mix_decay_w1" },
  1491. { LLM_TENSOR_TIME_MIX_DECAY_W2, "blk.%d.time_mix_decay_w2" },
  1492. { LLM_TENSOR_TIME_MIX_KEY, "blk.%d.time_mix_key" },
  1493. { LLM_TENSOR_TIME_MIX_VALUE, "blk.%d.time_mix_value" },
  1494. { LLM_TENSOR_TIME_MIX_RECEPTANCE, "blk.%d.time_mix_receptance" },
  1495. { LLM_TENSOR_TIME_MIX_GATE, "blk.%d.time_mix_gate" },
  1496. { LLM_TENSOR_TIME_MIX_LN, "blk.%d.time_mix_ln" },
  1497. { LLM_TENSOR_TIME_MIX_OUTPUT, "blk.%d.time_mix_output" },
  1498. { LLM_TENSOR_CHANNEL_MIX_LERP_K, "blk.%d.channel_mix_lerp_k" },
  1499. { LLM_TENSOR_CHANNEL_MIX_LERP_R, "blk.%d.channel_mix_lerp_r" },
  1500. { LLM_TENSOR_CHANNEL_MIX_KEY, "blk.%d.channel_mix_key" },
  1501. { LLM_TENSOR_CHANNEL_MIX_VALUE, "blk.%d.channel_mix_value" },
  1502. { LLM_TENSOR_CHANNEL_MIX_RECEPTANCE, "blk.%d.channel_mix_receptance" },
  1503. },
  1504. },
  1505. {
  1506. LLM_ARCH_GRANITE,
  1507. {
  1508. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1509. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1510. { LLM_TENSOR_OUTPUT, "output" },
  1511. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1512. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1513. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1514. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1515. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1516. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1517. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1518. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1519. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1520. },
  1521. },
  1522. {
  1523. LLM_ARCH_GRANITE_MOE,
  1524. {
  1525. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1526. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1527. { LLM_TENSOR_OUTPUT, "output" },
  1528. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1529. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1530. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1531. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1532. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1533. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1534. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1535. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1536. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1537. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1538. },
  1539. },
  1540. {
  1541. LLM_ARCH_CHAMELEON,
  1542. {
  1543. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1544. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1545. { LLM_TENSOR_OUTPUT, "output" },
  1546. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1547. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1548. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1549. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1550. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1551. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1552. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1553. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1554. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1555. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  1556. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  1557. },
  1558. },
  1559. {
  1560. LLM_ARCH_SOLAR,
  1561. {
  1562. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1563. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1564. { LLM_TENSOR_OUTPUT, "output" },
  1565. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1566. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1567. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1568. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1569. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1570. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1571. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1572. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1573. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1574. { LLM_TENSOR_BSKCN_TV, "bskcn_tv" },
  1575. },
  1576. },
  1577. {
  1578. LLM_ARCH_UNKNOWN,
  1579. {
  1580. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1581. },
  1582. },
  1583. };
  1584. static llm_arch llm_arch_from_string(const std::string & name) {
  1585. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  1586. if (kv.second == name) {
  1587. return kv.first;
  1588. }
  1589. }
  1590. return LLM_ARCH_UNKNOWN;
  1591. }
  1592. // helper to handle gguf constants
  1593. // usage:
  1594. //
  1595. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  1596. //
  1597. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  1598. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  1599. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  1600. //
  1601. struct LLM_TN {
  1602. LLM_TN(llm_arch arch) : arch(arch) {}
  1603. llm_arch arch;
  1604. std::string operator()(llm_tensor tensor) const {
  1605. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1606. return "__missing__";
  1607. }
  1608. return LLM_TENSOR_NAMES.at(arch).at(tensor);
  1609. }
  1610. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  1611. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1612. return "__missing__";
  1613. }
  1614. return LLM_TENSOR_NAMES.at(arch).at(tensor) + "." + suffix;
  1615. }
  1616. std::string operator()(llm_tensor tensor, int bid) const {
  1617. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1618. return "__missing__";
  1619. }
  1620. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid);
  1621. }
  1622. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  1623. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1624. return "__missing__";
  1625. }
  1626. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid) + "." + suffix;
  1627. }
  1628. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  1629. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1630. return "__missing__";
  1631. }
  1632. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid, xid) + "." + suffix;
  1633. }
  1634. };
  1635. //
  1636. // gguf helpers
  1637. //
  1638. static const std::map<llama_rope_scaling_type, const char *> LLAMA_ROPE_SCALING_TYPES = {
  1639. { LLAMA_ROPE_SCALING_TYPE_NONE, "none" },
  1640. { LLAMA_ROPE_SCALING_TYPE_LINEAR, "linear" },
  1641. { LLAMA_ROPE_SCALING_TYPE_YARN, "yarn" },
  1642. };
  1643. static llama_rope_scaling_type llama_rope_scaling_type_from_string(const std::string & name) {
  1644. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  1645. if (kv.second == name) {
  1646. return (llama_rope_scaling_type) kv.first;
  1647. }
  1648. }
  1649. return LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
  1650. }
  1651. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  1652. switch (type) {
  1653. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  1654. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  1655. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  1656. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  1657. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  1658. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  1659. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  1660. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  1661. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  1662. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  1663. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  1664. default: return format("unknown type %d", type);
  1665. }
  1666. }
  1667. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  1668. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  1669. switch (type) {
  1670. case GGUF_TYPE_STRING:
  1671. return gguf_get_val_str(ctx_gguf, i);
  1672. case GGUF_TYPE_ARRAY:
  1673. {
  1674. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  1675. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  1676. const void * data = gguf_get_arr_data(ctx_gguf, i);
  1677. std::stringstream ss;
  1678. ss << "[";
  1679. for (int j = 0; j < arr_n; j++) {
  1680. if (arr_type == GGUF_TYPE_STRING) {
  1681. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  1682. // escape quotes
  1683. replace_all(val, "\\", "\\\\");
  1684. replace_all(val, "\"", "\\\"");
  1685. ss << '"' << val << '"';
  1686. } else if (arr_type == GGUF_TYPE_ARRAY) {
  1687. ss << "???";
  1688. } else {
  1689. ss << gguf_data_to_str(arr_type, data, j);
  1690. }
  1691. if (j < arr_n - 1) {
  1692. ss << ", ";
  1693. }
  1694. }
  1695. ss << "]";
  1696. return ss.str();
  1697. }
  1698. default:
  1699. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  1700. }
  1701. }
  1702. //
  1703. // llama helpers
  1704. //
  1705. #if defined(_WIN32)
  1706. static std::string llama_format_win_err(DWORD err) {
  1707. LPSTR buf;
  1708. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1709. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  1710. if (!size) {
  1711. return "FormatMessageA failed";
  1712. }
  1713. std::string ret(buf, size);
  1714. LocalFree(buf);
  1715. return ret;
  1716. }
  1717. #endif
  1718. template <typename T>
  1719. struct no_init {
  1720. T value;
  1721. no_init() { /* do nothing */ }
  1722. };
  1723. struct llama_file {
  1724. #if defined(_WIN32)
  1725. // use FILE * so we don't have to re-open the file to mmap
  1726. FILE * fp;
  1727. HANDLE fp_win32;
  1728. size_t size;
  1729. private:
  1730. std::string GetErrorMessageWin32(DWORD error_code) const {
  1731. std::string ret;
  1732. LPSTR lpMsgBuf = NULL;
  1733. DWORD bufLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1734. NULL, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lpMsgBuf, 0, NULL);
  1735. if (!bufLen) {
  1736. ret = format("Win32 error code: %s", error_code);
  1737. } else {
  1738. ret = lpMsgBuf;
  1739. LocalFree(lpMsgBuf);
  1740. }
  1741. return ret;
  1742. }
  1743. public:
  1744. llama_file(const char * fname, const char * mode) {
  1745. fp = ggml_fopen(fname, mode);
  1746. if (fp == NULL) {
  1747. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  1748. }
  1749. fp_win32 = (HANDLE) _get_osfhandle(_fileno(fp));
  1750. seek(0, SEEK_END);
  1751. size = tell();
  1752. seek(0, SEEK_SET);
  1753. }
  1754. size_t tell() const {
  1755. // SetFilePointerEx returns the current position when seeking relative 0 bytes
  1756. LARGE_INTEGER li;
  1757. li.QuadPart = 0;
  1758. BOOL ret = SetFilePointerEx(fp_win32, li, &li, FILE_CURRENT);
  1759. if (!ret) {
  1760. throw std::runtime_error(format("read error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1761. }
  1762. return li.QuadPart;
  1763. }
  1764. void seek(size_t offset, int whence) const {
  1765. // no need to convert SEEK_* to FILE_*. The enums are the same.
  1766. // Still, keep static asserts to avoid failures in the future.
  1767. static_assert(SEEK_SET == FILE_BEGIN, "SEEK_SET != FILE_BEGIN");
  1768. static_assert(SEEK_CUR == FILE_CURRENT, "SEEK_CUR != FILE_CURRENT");
  1769. static_assert(SEEK_END == FILE_END, "SEEK_END != FILE_END");
  1770. LARGE_INTEGER li;
  1771. li.QuadPart = offset;
  1772. BOOL ret = SetFilePointerEx(fp_win32, li, NULL, whence);
  1773. if (!ret) {
  1774. throw std::runtime_error(format("read error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1775. }
  1776. }
  1777. void read_raw(void * ptr, size_t len) const {
  1778. // On Win32 ReadFile is significant faster than fread which is again significant faster than std::fstream. Thus
  1779. // use the Win32 API to do file io instead of the C/C++ library functions.
  1780. // There are conditions under which ReadFile cannot read chunks >64MB.
  1781. // Thus split the operation into smaller chunks if len exceeds this limit.
  1782. size_t bytes_read = 0;
  1783. while (bytes_read < len) {
  1784. size_t chunk_size = std::min<size_t>(len - bytes_read, 64*1024*1024);
  1785. DWORD chunk_read = 0;
  1786. BOOL result = ReadFile(fp_win32, reinterpret_cast<char*>(ptr) + bytes_read, chunk_size, &chunk_read, NULL);
  1787. if (!result) {
  1788. throw std::runtime_error(format("read error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1789. }
  1790. if (chunk_read < chunk_size || chunk_read == 0) {
  1791. throw std::runtime_error("unexpectedly reached end of file");
  1792. }
  1793. bytes_read += chunk_read;
  1794. } ;
  1795. }
  1796. uint32_t read_u32() const {
  1797. uint32_t val;
  1798. read_raw(&val, sizeof(val));
  1799. return val;
  1800. }
  1801. void write_raw(const void * ptr, size_t len) const {
  1802. // There are conditions under which WriteFile cannot write chunks >64MB.
  1803. // Thus split the operation into smaller chunks if len exceeds this limit.
  1804. size_t bytes_written = 0;
  1805. while (bytes_written < len) {
  1806. size_t chunk_size = std::min<size_t>(len - bytes_written, 64*1024*1024);
  1807. DWORD chunk_written = 0;
  1808. BOOL result = WriteFile(fp_win32, reinterpret_cast<char const*>(ptr) + bytes_written, chunk_size, &chunk_written, NULL);
  1809. if (!result) {
  1810. throw std::runtime_error(format("write error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1811. }
  1812. if (chunk_written < chunk_size || chunk_written == 0) {
  1813. throw std::runtime_error("unexpectedly failed to write bytes");
  1814. }
  1815. bytes_written += chunk_written;
  1816. }
  1817. }
  1818. void write_u32(std::uint32_t val) const {
  1819. write_raw(&val, sizeof(val));
  1820. }
  1821. ~llama_file() {
  1822. if (fp) {
  1823. std::fclose(fp);
  1824. }
  1825. }
  1826. #else
  1827. // use FILE * so we don't have to re-open the file to mmap
  1828. FILE * fp;
  1829. size_t size;
  1830. llama_file(const char * fname, const char * mode) {
  1831. fp = ggml_fopen(fname, mode);
  1832. if (fp == NULL) {
  1833. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  1834. }
  1835. seek(0, SEEK_END);
  1836. size = tell();
  1837. seek(0, SEEK_SET);
  1838. }
  1839. size_t tell() const {
  1840. #ifdef _WIN32
  1841. __int64 ret = _ftelli64(fp);
  1842. #else
  1843. long ret = std::ftell(fp);
  1844. #endif
  1845. if (ret == -1) {
  1846. throw std::runtime_error(format("ftell error: %s", strerror(errno)));
  1847. }
  1848. return (size_t) ret;
  1849. }
  1850. void seek(size_t offset, int whence) const {
  1851. #ifdef _WIN32
  1852. int ret = _fseeki64(fp, (__int64) offset, whence);
  1853. #else
  1854. int ret = std::fseek(fp, (long) offset, whence);
  1855. #endif
  1856. if (ret != 0) {
  1857. throw std::runtime_error(format("seek error: %s", strerror(errno)));
  1858. }
  1859. }
  1860. void read_raw(void * ptr, size_t len) const {
  1861. if (len == 0) {
  1862. return;
  1863. }
  1864. errno = 0;
  1865. std::size_t ret = std::fread(ptr, len, 1, fp);
  1866. if (ferror(fp)) {
  1867. throw std::runtime_error(format("read error: %s", strerror(errno)));
  1868. }
  1869. if (ret != 1) {
  1870. throw std::runtime_error("unexpectedly reached end of file");
  1871. }
  1872. }
  1873. uint32_t read_u32() const {
  1874. uint32_t ret;
  1875. read_raw(&ret, sizeof(ret));
  1876. return ret;
  1877. }
  1878. void write_raw(const void * ptr, size_t len) const {
  1879. if (len == 0) {
  1880. return;
  1881. }
  1882. errno = 0;
  1883. size_t ret = std::fwrite(ptr, len, 1, fp);
  1884. if (ret != 1) {
  1885. throw std::runtime_error(format("write error: %s", strerror(errno)));
  1886. }
  1887. }
  1888. void write_u32(std::uint32_t val) const {
  1889. write_raw(&val, sizeof(val));
  1890. }
  1891. ~llama_file() {
  1892. if (fp) {
  1893. std::fclose(fp);
  1894. }
  1895. }
  1896. #endif
  1897. };
  1898. using llama_files = std::vector<std::unique_ptr<llama_file>>;
  1899. struct llama_mmap {
  1900. void * addr;
  1901. size_t size;
  1902. llama_mmap(const llama_mmap &) = delete;
  1903. #ifdef _POSIX_MAPPED_FILES
  1904. static constexpr bool SUPPORTED = true;
  1905. // list of mapped fragments (first_offset, last_offset)
  1906. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  1907. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  1908. size = file->size;
  1909. int fd = fileno(file->fp);
  1910. int flags = MAP_SHARED;
  1911. // prefetch/readahead impairs performance on NUMA systems
  1912. if (numa) { prefetch = 0; }
  1913. #ifdef __linux__
  1914. // advise the kernel to read the file sequentially (increases readahead)
  1915. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  1916. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  1917. strerror(errno));
  1918. }
  1919. if (prefetch) { flags |= MAP_POPULATE; }
  1920. #endif
  1921. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  1922. if (addr == MAP_FAILED) { // NOLINT
  1923. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  1924. }
  1925. if (prefetch > 0) {
  1926. // advise the kernel to preload the mapped memory
  1927. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  1928. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  1929. strerror(errno));
  1930. }
  1931. }
  1932. if (numa) {
  1933. // advise the kernel not to use readahead
  1934. // (because the next page might not belong on the same node)
  1935. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  1936. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  1937. strerror(errno));
  1938. }
  1939. }
  1940. // initialize list of mapped_fragments
  1941. mapped_fragments.emplace_back(0, file->size);
  1942. }
  1943. static void align_range(size_t * first, size_t * last, size_t page_size) {
  1944. // align first to the next page
  1945. size_t offset_in_page = *first & (page_size - 1);
  1946. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  1947. *first += offset_to_page;
  1948. // align last to the previous page
  1949. *last = *last & ~(page_size - 1);
  1950. if (*last <= *first) {
  1951. *last = *first;
  1952. }
  1953. }
  1954. // partially unmap the file in the range [first, last)
  1955. void unmap_fragment(size_t first, size_t last) {
  1956. // note: this function must not be called multiple times with overlapping ranges
  1957. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  1958. int page_size = sysconf(_SC_PAGESIZE);
  1959. align_range(&first, &last, page_size);
  1960. size_t len = last - first;
  1961. if (len == 0) {
  1962. return;
  1963. }
  1964. GGML_ASSERT(first % page_size == 0);
  1965. GGML_ASSERT(last % page_size == 0);
  1966. GGML_ASSERT(last > first);
  1967. void * next_page_start = (uint8_t *) addr + first;
  1968. // unmap the range
  1969. if (munmap(next_page_start, len)) {
  1970. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1971. }
  1972. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  1973. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  1974. for (const auto & frag : mapped_fragments) {
  1975. if (frag.first < first && frag.second > last) {
  1976. // the range is in the middle of the fragment, split it
  1977. new_mapped_fragments.emplace_back(frag.first, first);
  1978. new_mapped_fragments.emplace_back(last, frag.second);
  1979. } else if (frag.first < first && frag.second > first) {
  1980. // the range starts in the middle of the fragment
  1981. new_mapped_fragments.emplace_back(frag.first, first);
  1982. } else if (frag.first < last && frag.second > last) {
  1983. // the range ends in the middle of the fragment
  1984. new_mapped_fragments.emplace_back(last, frag.second);
  1985. } else if (frag.first >= first && frag.second <= last) {
  1986. // the range covers the entire fragment
  1987. } else {
  1988. // the range is outside the fragment
  1989. new_mapped_fragments.push_back(frag);
  1990. }
  1991. }
  1992. mapped_fragments = std::move(new_mapped_fragments);
  1993. }
  1994. ~llama_mmap() {
  1995. for (const auto & frag : mapped_fragments) {
  1996. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  1997. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1998. }
  1999. }
  2000. }
  2001. #elif defined(_WIN32)
  2002. static constexpr bool SUPPORTED = true;
  2003. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  2004. GGML_UNUSED(numa);
  2005. size = file->size;
  2006. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  2007. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  2008. if (hMapping == NULL) {
  2009. DWORD error = GetLastError();
  2010. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  2011. }
  2012. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  2013. DWORD error = GetLastError();
  2014. CloseHandle(hMapping);
  2015. if (addr == NULL) {
  2016. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  2017. }
  2018. if (prefetch > 0) {
  2019. #if _WIN32_WINNT >= 0x602
  2020. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  2021. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  2022. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  2023. // may fail on pre-Windows 8 systems
  2024. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  2025. if (pPrefetchVirtualMemory) {
  2026. // advise the kernel to preload the mapped memory
  2027. WIN32_MEMORY_RANGE_ENTRY range;
  2028. range.VirtualAddress = addr;
  2029. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  2030. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  2031. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  2032. llama_format_win_err(GetLastError()).c_str());
  2033. }
  2034. }
  2035. #else
  2036. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  2037. #endif
  2038. }
  2039. }
  2040. void unmap_fragment(size_t first, size_t last) {
  2041. // not supported
  2042. GGML_UNUSED(first);
  2043. GGML_UNUSED(last);
  2044. }
  2045. ~llama_mmap() {
  2046. if (!UnmapViewOfFile(addr)) {
  2047. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  2048. llama_format_win_err(GetLastError()).c_str());
  2049. }
  2050. }
  2051. #else
  2052. static constexpr bool SUPPORTED = false;
  2053. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  2054. GGML_UNUSED(file);
  2055. GGML_UNUSED(prefetch);
  2056. GGML_UNUSED(numa);
  2057. throw std::runtime_error("mmap not supported");
  2058. }
  2059. void unmap_fragment(size_t first, size_t last) {
  2060. GGML_UNUSED(first);
  2061. GGML_UNUSED(last);
  2062. throw std::runtime_error("mmap not supported");
  2063. }
  2064. #endif
  2065. };
  2066. using llama_mmaps = std::vector<std::unique_ptr<llama_mmap>>;
  2067. // Represents some region of memory being locked using mlock or VirtualLock;
  2068. // will automatically unlock on destruction.
  2069. struct llama_mlock {
  2070. void * addr = NULL;
  2071. size_t size = 0;
  2072. bool failed_already = false;
  2073. llama_mlock() {}
  2074. llama_mlock(const llama_mlock &) = delete;
  2075. ~llama_mlock() {
  2076. if (size) {
  2077. raw_unlock(addr, size);
  2078. }
  2079. }
  2080. void init(void * ptr) {
  2081. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  2082. addr = ptr;
  2083. }
  2084. void grow_to(size_t target_size) {
  2085. GGML_ASSERT(addr);
  2086. if (failed_already) {
  2087. return;
  2088. }
  2089. size_t granularity = lock_granularity();
  2090. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  2091. if (target_size > size) {
  2092. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  2093. size = target_size;
  2094. } else {
  2095. failed_already = true;
  2096. }
  2097. }
  2098. }
  2099. #ifdef _POSIX_MEMLOCK_RANGE
  2100. static constexpr bool SUPPORTED = true;
  2101. static size_t lock_granularity() {
  2102. return (size_t) sysconf(_SC_PAGESIZE);
  2103. }
  2104. #ifdef __APPLE__
  2105. #define MLOCK_SUGGESTION \
  2106. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  2107. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  2108. #else
  2109. #define MLOCK_SUGGESTION \
  2110. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  2111. #endif
  2112. bool raw_lock(const void * addr, size_t size) const {
  2113. if (!mlock(addr, size)) {
  2114. return true;
  2115. }
  2116. char* errmsg = std::strerror(errno);
  2117. bool suggest = (errno == ENOMEM);
  2118. // Check if the resource limit is fine after all
  2119. struct rlimit lock_limit;
  2120. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  2121. suggest = false;
  2122. }
  2123. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  2124. suggest = false;
  2125. }
  2126. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  2127. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  2128. return false;
  2129. }
  2130. #undef MLOCK_SUGGESTION
  2131. static void raw_unlock(void * addr, size_t size) {
  2132. if (munlock(addr, size)) {
  2133. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  2134. }
  2135. }
  2136. #elif defined(_WIN32)
  2137. static constexpr bool SUPPORTED = true;
  2138. static size_t lock_granularity() {
  2139. SYSTEM_INFO si;
  2140. GetSystemInfo(&si);
  2141. return (size_t) si.dwPageSize;
  2142. }
  2143. bool raw_lock(void * ptr, size_t len) const {
  2144. for (int tries = 1; ; tries++) {
  2145. if (VirtualLock(ptr, len)) {
  2146. return true;
  2147. }
  2148. if (tries == 2) {
  2149. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  2150. len, size, llama_format_win_err(GetLastError()).c_str());
  2151. return false;
  2152. }
  2153. // It failed but this was only the first try; increase the working
  2154. // set size and try again.
  2155. SIZE_T min_ws_size, max_ws_size;
  2156. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  2157. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  2158. llama_format_win_err(GetLastError()).c_str());
  2159. return false;
  2160. }
  2161. // Per MSDN: "The maximum number of pages that a process can lock
  2162. // is equal to the number of pages in its minimum working set minus
  2163. // a small overhead."
  2164. // Hopefully a megabyte is enough overhead:
  2165. size_t increment = len + 1048576;
  2166. // The minimum must be <= the maximum, so we need to increase both:
  2167. min_ws_size += increment;
  2168. max_ws_size += increment;
  2169. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  2170. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  2171. llama_format_win_err(GetLastError()).c_str());
  2172. return false;
  2173. }
  2174. }
  2175. }
  2176. static void raw_unlock(void * ptr, size_t len) {
  2177. if (!VirtualUnlock(ptr, len)) {
  2178. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  2179. llama_format_win_err(GetLastError()).c_str());
  2180. }
  2181. }
  2182. #else
  2183. static constexpr bool SUPPORTED = false;
  2184. static size_t lock_granularity() {
  2185. return (size_t) 65536;
  2186. }
  2187. bool raw_lock(const void * addr, size_t len) const {
  2188. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  2189. return false;
  2190. }
  2191. static void raw_unlock(const void * addr, size_t len) {}
  2192. #endif
  2193. };
  2194. using llama_mlocks = std::vector<std::unique_ptr<llama_mlock>>;
  2195. // NOTE: avoid ever using this except for building the token_to_piece caches
  2196. static std::string llama_token_to_piece(const struct llama_model * model, llama_token token, bool special) {
  2197. std::string piece;
  2198. piece.resize(piece.capacity()); // using string internal cache
  2199. const int n_chars = llama_token_to_piece(model, token, &piece[0], piece.size(), 0, special);
  2200. if (n_chars < 0) {
  2201. piece.resize(-n_chars);
  2202. int check = llama_token_to_piece(model, token, &piece[0], piece.size(), 0, special);
  2203. GGML_ASSERT(check == -n_chars);
  2204. }
  2205. else {
  2206. piece.resize(n_chars);
  2207. }
  2208. return piece;
  2209. }
  2210. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  2211. ggml_backend_buffer_type_t buft = nullptr;
  2212. #if defined(GGML_USE_CUDA)
  2213. // host buffers should only be used when data is expected to be copied to/from the GPU
  2214. if (host_buffer) {
  2215. buft = ggml_backend_cuda_host_buffer_type();
  2216. }
  2217. #elif defined(GGML_USE_SYCL)
  2218. if (host_buffer) {
  2219. buft = ggml_backend_sycl_host_buffer_type();
  2220. }
  2221. #elif defined(GGML_USE_CANN)
  2222. if (host_buffer) {
  2223. buft = ggml_backend_cann_host_buffer_type();
  2224. }
  2225. #elif defined(GGML_USE_CPU_HBM)
  2226. buft = ggml_backend_cpu_hbm_buffer_type();
  2227. #elif defined(GGML_USE_VULKAN)
  2228. if (host_buffer) {
  2229. buft = ggml_backend_vk_host_buffer_type();
  2230. }
  2231. #endif
  2232. if (buft == nullptr) {
  2233. buft = ggml_backend_cpu_buffer_type();
  2234. }
  2235. return buft;
  2236. GGML_UNUSED(host_buffer);
  2237. }
  2238. //
  2239. // globals
  2240. //
  2241. struct llama_state {
  2242. llama_state() {
  2243. #ifdef GGML_USE_METAL
  2244. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  2245. #elif defined(GGML_USE_CUDA)
  2246. ggml_backend_cuda_log_set_callback(log_callback, log_callback_user_data);
  2247. #elif defined(GGML_USE_CANN)
  2248. ggml_backend_cann_log_set_callback(log_callback, log_callback_user_data);
  2249. #endif
  2250. }
  2251. // We save the log callback globally
  2252. ggml_log_callback log_callback = llama_log_callback_default;
  2253. void * log_callback_user_data = nullptr;
  2254. };
  2255. static llama_state g_state;
  2256. // available llama models
  2257. enum e_model {
  2258. MODEL_UNKNOWN,
  2259. MODEL_14M,
  2260. MODEL_17M,
  2261. MODEL_22M,
  2262. MODEL_33M,
  2263. MODEL_60M,
  2264. MODEL_70M,
  2265. MODEL_80M,
  2266. MODEL_109M,
  2267. MODEL_137M,
  2268. MODEL_160M,
  2269. MODEL_220M,
  2270. MODEL_250M,
  2271. MODEL_270M,
  2272. MODEL_335M,
  2273. MODEL_410M,
  2274. MODEL_450M,
  2275. MODEL_770M,
  2276. MODEL_780M,
  2277. MODEL_0_5B,
  2278. MODEL_1B,
  2279. MODEL_1_3B,
  2280. MODEL_1_4B,
  2281. MODEL_1_6B,
  2282. MODEL_2B,
  2283. MODEL_2_8B,
  2284. MODEL_3B,
  2285. MODEL_4B,
  2286. MODEL_6B,
  2287. MODEL_6_9B,
  2288. MODEL_7B,
  2289. MODEL_8B,
  2290. MODEL_9B,
  2291. MODEL_11B,
  2292. MODEL_12B,
  2293. MODEL_13B,
  2294. MODEL_14B,
  2295. MODEL_15B,
  2296. MODEL_16B,
  2297. MODEL_20B,
  2298. MODEL_22B,
  2299. MODEL_30B,
  2300. MODEL_34B,
  2301. MODEL_35B,
  2302. MODEL_40B,
  2303. MODEL_65B,
  2304. MODEL_70B,
  2305. MODEL_90B,
  2306. MODEL_236B,
  2307. MODEL_314B,
  2308. MODEL_SMALL,
  2309. MODEL_MEDIUM,
  2310. MODEL_LARGE,
  2311. MODEL_XL,
  2312. MODEL_A1_7B,
  2313. MODEL_A2_7B,
  2314. MODEL_8x7B,
  2315. MODEL_8x22B,
  2316. MODEL_16x12B,
  2317. MODEL_10B_128x3_66B,
  2318. MODEL_57B_A14B,
  2319. MODEL_27B,
  2320. };
  2321. static const size_t kiB = 1024;
  2322. static const size_t MiB = 1024*kiB;
  2323. static const size_t GiB = 1024*MiB;
  2324. struct llama_hparams {
  2325. bool vocab_only;
  2326. bool rope_finetuned;
  2327. bool use_par_res;
  2328. bool swin_norm;
  2329. uint32_t n_vocab;
  2330. uint32_t n_ctx_train; // context size the model was trained on
  2331. uint32_t n_embd;
  2332. uint32_t n_layer;
  2333. uint32_t n_rot;
  2334. uint32_t n_swa = 0; // sliding window attention (SWA)
  2335. 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
  2336. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  2337. uint32_t n_expert = 0;
  2338. uint32_t n_expert_used = 0;
  2339. uint32_t n_vocab_type = 0; // for BERT-style token types
  2340. uint32_t n_rel_attn_bkts = 0;
  2341. std::array<uint32_t, LLAMA_MAX_LAYERS> n_head_arr;
  2342. std::array<uint32_t, LLAMA_MAX_LAYERS> n_head_kv_arr;
  2343. std::array<uint32_t, LLAMA_MAX_LAYERS> n_ff_arr;
  2344. std::array<std::array<uint32_t, LLAMA_MAX_LAYERS>, 4> n_bskcn_arr;
  2345. std::array<uint32_t, LLAMA_MAX_LAYERS> cross_attn_layers;
  2346. uint32_t n_layer_dense_lead = 0;
  2347. uint32_t n_lora_q = 0;
  2348. uint32_t n_lora_kv = 0;
  2349. uint32_t n_ff_exp = 0;
  2350. uint32_t n_ff_shexp = 0;
  2351. uint32_t n_expert_shared = 0;
  2352. float expert_weights_scale = 0.0;
  2353. float f_norm_eps;
  2354. float f_norm_rms_eps;
  2355. float f_attn_logit_softcapping = 50.0f;
  2356. float f_final_logit_softcapping = 30.0f;
  2357. // for RWKV
  2358. uint32_t rescale_every_n_layers = 0;
  2359. uint32_t time_mix_extra_dim = 0;
  2360. uint32_t time_decay_extra_dim = 0;
  2361. uint32_t wkv_head_size = 0;
  2362. float rope_attn_factor = 1.0f;
  2363. float rope_freq_base_train;
  2364. float rope_freq_scale_train;
  2365. uint32_t n_ctx_orig_yarn;
  2366. float rope_yarn_log_mul;
  2367. // for State Space Models
  2368. uint32_t ssm_d_conv = 0;
  2369. uint32_t ssm_d_inner = 0;
  2370. uint32_t ssm_d_state = 0;
  2371. uint32_t ssm_dt_rank = 0;
  2372. bool ssm_dt_b_c_rms = false;
  2373. float f_clamp_kqv = 0.0f;
  2374. float f_max_alibi_bias = 0.0f;
  2375. float f_logit_scale = 0.0f;
  2376. // Additional scale factors (Granite/Granite MoE)
  2377. float f_residual_scale = 0.0f;
  2378. float f_embedding_scale = 0.0f;
  2379. float f_attention_scale = 0.0f;
  2380. bool causal_attn = true;
  2381. bool use_alibi = false;
  2382. bool attn_soft_cap = false;
  2383. // needed by encoder-decoder models (e.g. T5, FLAN-T5)
  2384. // ref: https://github.com/ggerganov/llama.cpp/pull/8141
  2385. llama_token dec_start_token_id = -1;
  2386. enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_NONE;
  2387. enum llama_rope_type rope_type = LLAMA_ROPE_TYPE_NONE;
  2388. enum llama_rope_scaling_type rope_scaling_type_train = LLAMA_ROPE_SCALING_TYPE_NONE;
  2389. bool operator!=(const llama_hparams & other) const {
  2390. if (this->vocab_only != other.vocab_only) return true;
  2391. if (this->n_vocab != other.n_vocab) return true;
  2392. if (this->n_ctx_train != other.n_ctx_train) return true;
  2393. if (this->n_embd != other.n_embd) return true;
  2394. if (this->n_layer != other.n_layer) return true;
  2395. if (this->n_rot != other.n_rot) return true;
  2396. if (this->n_swa != other.n_swa) return true;
  2397. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  2398. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  2399. if (this->n_expert != other.n_expert) return true;
  2400. if (this->n_expert_used != other.n_expert_used) return true;
  2401. if (this->n_head_arr != other.n_head_arr) return true;
  2402. if (this->n_head_kv_arr != other.n_head_kv_arr) return true;
  2403. if (this->n_ff_arr != other.n_ff_arr) return true;
  2404. if (this->n_bskcn_arr != other.n_bskcn_arr) return true;
  2405. if (this->cross_attn_layers != other.cross_attn_layers) return true;
  2406. if (this->n_rel_attn_bkts != other.n_rel_attn_bkts) return true;
  2407. if (this->n_layer_dense_lead != other.n_layer_dense_lead) return true;
  2408. if (this->n_lora_q != other.n_lora_q) return true;
  2409. if (this->n_lora_kv != other.n_lora_kv) return true;
  2410. if (this->n_ff_exp != other.n_ff_exp) return true;
  2411. if (this->n_ff_shexp != other.n_ff_shexp) return true;
  2412. if (this->n_expert_shared != other.n_expert_shared) return true;
  2413. if (this->rope_finetuned != other.rope_finetuned) return true;
  2414. if (this->n_ctx_orig_yarn != other.n_ctx_orig_yarn) return true;
  2415. if (this->ssm_d_conv != other.ssm_d_conv) return true;
  2416. if (this->ssm_d_inner != other.ssm_d_inner) return true;
  2417. if (this->ssm_d_state != other.ssm_d_state) return true;
  2418. if (this->ssm_dt_rank != other.ssm_dt_rank) return true;
  2419. if (this->ssm_dt_b_c_rms != other.ssm_dt_b_c_rms) return true;
  2420. if (this->rescale_every_n_layers != other.rescale_every_n_layers) return true;
  2421. if (this->time_mix_extra_dim != other.time_mix_extra_dim) return true;
  2422. if (this->time_decay_extra_dim != other.time_decay_extra_dim) return true;
  2423. if (this->wkv_head_size != other.wkv_head_size) return true;
  2424. if (this->dec_start_token_id != other.dec_start_token_id) return true;
  2425. const float EPSILON = 1e-9f;
  2426. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  2427. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  2428. if (!is_float_close(this->rope_attn_factor, other.rope_attn_factor, EPSILON)) return true;
  2429. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  2430. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  2431. if (!is_float_close(this->expert_weights_scale, other.expert_weights_scale, EPSILON)) return true;
  2432. if (!is_float_close(this->rope_yarn_log_mul, other.rope_yarn_log_mul, EPSILON)) return true;
  2433. if (!is_float_close(this->f_residual_scale, other.f_residual_scale, EPSILON)) return true;
  2434. if (!is_float_close(this->f_embedding_scale, other.f_embedding_scale, EPSILON)) return true;
  2435. if (!is_float_close(this->f_attention_scale, other.f_attention_scale, EPSILON)) return true;
  2436. return false;
  2437. }
  2438. uint32_t n_head(uint32_t il = 0) const {
  2439. if (il < n_layer) {
  2440. return n_head_arr[il];
  2441. }
  2442. GGML_ABORT("fatal error");
  2443. }
  2444. uint32_t n_head_kv(uint32_t il = 0) const {
  2445. if (il < n_layer) {
  2446. return n_head_kv_arr[il];
  2447. }
  2448. GGML_ABORT("fatal error");
  2449. }
  2450. uint32_t n_ff(uint32_t il = 0) const {
  2451. if (il < n_layer) {
  2452. return n_ff_arr[il];
  2453. }
  2454. GGML_ABORT("fatal error");
  2455. }
  2456. uint32_t n_gqa(uint32_t il = 0) const {
  2457. const uint32_t n_head = this->n_head(il);
  2458. const uint32_t n_head_kv = this->n_head_kv(il);
  2459. if (n_head_kv == 0) {
  2460. return 0;
  2461. }
  2462. return n_head/n_head_kv;
  2463. }
  2464. uint32_t n_embd_k_gqa(uint32_t il = 0) const { // dimension of key embeddings across all k-v heads
  2465. const uint32_t n_head_kv = this->n_head_kv(il);
  2466. return n_embd_head_k * n_head_kv;
  2467. }
  2468. uint32_t n_embd_v_gqa(uint32_t il = 0) const { // dimension of value embeddings across all k-v heads
  2469. const uint32_t n_head_kv = this->n_head_kv(il);
  2470. return n_embd_head_v * n_head_kv;
  2471. }
  2472. uint32_t n_embd_k_s() const { // dimension of the rolling state embeddings
  2473. // corresponds to Mamba's conv_states size or RWKV's token_shift states size
  2474. if (wkv_head_size != 0) {
  2475. // for RWKV models
  2476. return 2 * n_embd;
  2477. } else {
  2478. // TODO: maybe support other convolution strides than 1
  2479. // NOTE: since the first column of the conv_state is shifted out each time, it's not actually needed
  2480. return (ssm_d_conv > 0 ? ssm_d_conv - 1 : 0) * ssm_d_inner;
  2481. }
  2482. }
  2483. uint32_t n_embd_v_s() const { // dimension of the recurrent state embeddings
  2484. if (wkv_head_size != 0) {
  2485. // corresponds to RWKV's wkv_states size
  2486. return n_embd * wkv_head_size;
  2487. } else {
  2488. // corresponds to Mamba's ssm_states size
  2489. return ssm_d_state * ssm_d_inner;
  2490. }
  2491. }
  2492. bool n_bskcn(uint32_t n, uint32_t il = 0) const {
  2493. if (il < n_layer) {
  2494. return n_bskcn_arr[n][il] > 0;
  2495. }
  2496. GGML_ABORT("fatal error");
  2497. }
  2498. bool cross_attention_layer(uint32_t il) const {
  2499. return std::find(cross_attn_layers.begin(), cross_attn_layers.end(), il) != cross_attn_layers.end();
  2500. }
  2501. };
  2502. static_assert(std::is_trivially_copyable<llama_hparams>::value, "llama_hparams must be trivially copyable");
  2503. struct llama_cparams {
  2504. uint32_t n_ctx; // context size used during inference
  2505. uint32_t n_batch;
  2506. uint32_t n_ubatch;
  2507. uint32_t n_seq_max;
  2508. int n_threads; // number of threads to use for generation
  2509. int n_threads_batch; // number of threads to use for batch processing
  2510. float rope_freq_base;
  2511. float rope_freq_scale;
  2512. uint32_t n_ctx_orig_yarn;
  2513. // These hyperparameters are not exposed in GGUF, because all
  2514. // existing YaRN models use the same values for them.
  2515. float yarn_ext_factor;
  2516. float yarn_attn_factor;
  2517. float yarn_beta_fast;
  2518. float yarn_beta_slow;
  2519. float defrag_thold;
  2520. bool embeddings;
  2521. bool causal_attn;
  2522. bool offload_kqv;
  2523. bool flash_attn;
  2524. bool no_perf;
  2525. enum llama_pooling_type pooling_type;
  2526. ggml_backend_sched_eval_callback cb_eval;
  2527. void * cb_eval_user_data;
  2528. };
  2529. // TODO: separate into "llama_layer_enc" and "llama_layer_dec"
  2530. struct llama_layer {
  2531. // normalization
  2532. struct ggml_tensor * attn_norm;
  2533. struct ggml_tensor * attn_norm_b;
  2534. struct ggml_tensor * attn_norm_2;
  2535. struct ggml_tensor * attn_norm_2_b;
  2536. struct ggml_tensor * attn_q_norm;
  2537. struct ggml_tensor * attn_q_norm_b;
  2538. struct ggml_tensor * attn_k_norm;
  2539. struct ggml_tensor * attn_k_norm_b;
  2540. struct ggml_tensor * attn_out_norm;
  2541. struct ggml_tensor * attn_out_norm_b;
  2542. struct ggml_tensor * attn_q_a_norm;
  2543. struct ggml_tensor * attn_kv_a_norm;
  2544. struct ggml_tensor * attn_sub_norm;
  2545. struct ggml_tensor * attn_post_norm;
  2546. struct ggml_tensor * ffn_sub_norm;
  2547. struct ggml_tensor * attn_norm_cross;
  2548. struct ggml_tensor * attn_norm_enc;
  2549. // attention
  2550. struct ggml_tensor * wq;
  2551. struct ggml_tensor * wk;
  2552. struct ggml_tensor * wv;
  2553. struct ggml_tensor * wo;
  2554. struct ggml_tensor * wqkv;
  2555. struct ggml_tensor * wq_a;
  2556. struct ggml_tensor * wq_b;
  2557. struct ggml_tensor * wkv_a_mqa;
  2558. struct ggml_tensor * wkv_b;
  2559. struct ggml_tensor * wq_cross;
  2560. struct ggml_tensor * wk_cross;
  2561. struct ggml_tensor * wv_cross;
  2562. struct ggml_tensor * wo_cross;
  2563. struct ggml_tensor * wq_enc;
  2564. struct ggml_tensor * wk_enc;
  2565. struct ggml_tensor * wv_enc;
  2566. struct ggml_tensor * wo_enc;
  2567. // attention bias
  2568. struct ggml_tensor * bq;
  2569. struct ggml_tensor * bk;
  2570. struct ggml_tensor * bv;
  2571. struct ggml_tensor * bo;
  2572. struct ggml_tensor * bqkv;
  2573. // relative position bias
  2574. struct ggml_tensor * attn_rel_b;
  2575. struct ggml_tensor * attn_rel_b_enc;
  2576. struct ggml_tensor * attn_rel_b_cross;
  2577. // normalization
  2578. struct ggml_tensor * ffn_norm;
  2579. struct ggml_tensor * ffn_norm_b;
  2580. struct ggml_tensor * ffn_post_norm;
  2581. struct ggml_tensor * layer_out_norm;
  2582. struct ggml_tensor * layer_out_norm_b;
  2583. struct ggml_tensor * ffn_norm_exps;
  2584. struct ggml_tensor * ffn_norm_enc;
  2585. // ff
  2586. struct ggml_tensor * ffn_gate; // w1
  2587. struct ggml_tensor * ffn_down; // w2
  2588. struct ggml_tensor * ffn_up; // w3
  2589. struct ggml_tensor * ffn_gate_enc;
  2590. struct ggml_tensor * ffn_down_enc;
  2591. struct ggml_tensor * ffn_up_enc;
  2592. // ff MoE
  2593. struct ggml_tensor * ffn_gate_inp;
  2594. struct ggml_tensor * ffn_gate_exps;
  2595. struct ggml_tensor * ffn_down_exps;
  2596. struct ggml_tensor * ffn_up_exps ;
  2597. // ff shared expert (shexp)
  2598. struct ggml_tensor * ffn_gate_inp_shexp;
  2599. struct ggml_tensor * ffn_gate_shexp;
  2600. struct ggml_tensor * ffn_down_shexp;
  2601. struct ggml_tensor * ffn_up_shexp;
  2602. // ff bias
  2603. struct ggml_tensor * ffn_gate_b = nullptr;
  2604. struct ggml_tensor * ffn_down_b = nullptr; // b2
  2605. struct ggml_tensor * ffn_up_b = nullptr; // b3
  2606. struct ggml_tensor * ffn_act;
  2607. // mamba proj
  2608. struct ggml_tensor * ssm_in;
  2609. struct ggml_tensor * ssm_x;
  2610. struct ggml_tensor * ssm_dt;
  2611. struct ggml_tensor * ssm_out;
  2612. // mamba
  2613. struct ggml_tensor * ssm_conv1d;
  2614. struct ggml_tensor * ssm_a;
  2615. struct ggml_tensor * ssm_d;
  2616. // mamba bias
  2617. struct ggml_tensor * ssm_conv1d_b;
  2618. struct ggml_tensor * ssm_dt_b;
  2619. // rwkv
  2620. struct ggml_tensor * time_mix_w1;
  2621. struct ggml_tensor * time_mix_w2;
  2622. struct ggml_tensor * time_mix_lerp_x;
  2623. struct ggml_tensor * time_mix_lerp_w;
  2624. struct ggml_tensor * time_mix_lerp_k;
  2625. struct ggml_tensor * time_mix_lerp_v;
  2626. struct ggml_tensor * time_mix_lerp_r;
  2627. struct ggml_tensor * time_mix_lerp_g;
  2628. struct ggml_tensor * time_mix_first;
  2629. struct ggml_tensor * time_mix_decay;
  2630. struct ggml_tensor * time_mix_decay_w1;
  2631. struct ggml_tensor * time_mix_decay_w2;
  2632. struct ggml_tensor * time_mix_key;
  2633. struct ggml_tensor * time_mix_value;
  2634. struct ggml_tensor * time_mix_receptance;
  2635. struct ggml_tensor * time_mix_gate;
  2636. struct ggml_tensor * time_mix_ln;
  2637. struct ggml_tensor * time_mix_ln_b;
  2638. struct ggml_tensor * time_mix_output;
  2639. struct ggml_tensor * channel_mix_lerp_k;
  2640. struct ggml_tensor * channel_mix_lerp_r;
  2641. struct ggml_tensor * channel_mix_key;
  2642. struct ggml_tensor * channel_mix_receptance;
  2643. struct ggml_tensor * channel_mix_value;
  2644. // long rope factors
  2645. struct ggml_tensor * rope_long = nullptr;
  2646. struct ggml_tensor * rope_short = nullptr;
  2647. struct ggml_tensor * rope_freqs = nullptr;
  2648. // bitnet scale
  2649. struct ggml_tensor * wq_scale;
  2650. struct ggml_tensor * wk_scale;
  2651. struct ggml_tensor * wv_scale;
  2652. struct ggml_tensor * wo_scale;
  2653. struct ggml_tensor * ffn_gate_scale;
  2654. struct ggml_tensor * ffn_up_scale;
  2655. struct ggml_tensor * ffn_down_scale;
  2656. struct ggml_tensor * bskcn_tv;
  2657. // cross attention
  2658. struct ggml_tensor * cross_attn_k_norm;
  2659. struct ggml_tensor * cross_attn_k_proj;
  2660. struct ggml_tensor * cross_attn_o_proj;
  2661. struct ggml_tensor * cross_attn_q_norm;
  2662. struct ggml_tensor * cross_attn_q_proj;
  2663. struct ggml_tensor * cross_attn_v_proj;
  2664. struct ggml_tensor * cross_attn_attn_gate;
  2665. struct ggml_tensor * cross_attn_mlp_gate;
  2666. };
  2667. // very similar to llama_batch,
  2668. // but has more metadata about sequences
  2669. struct llama_ubatch {
  2670. bool equal_seqs;
  2671. // TODO: whole_seqs for embeddings?
  2672. uint32_t n_tokens; // total tokens (n_seq_tokens * n_seqs)
  2673. uint32_t n_seq_tokens; // tokens per sequence
  2674. uint32_t n_seqs;
  2675. llama_token * token; // [n_tokens]
  2676. float * embd; // [n_embd, n_tokens]
  2677. llama_pos * pos; // [n_tokens]
  2678. int32_t * n_seq_id; // [n_seqs]
  2679. llama_seq_id ** seq_id; // [n_seqs]
  2680. int8_t * output; // [n_tokens]
  2681. };
  2682. struct llama_kv_cell {
  2683. llama_pos pos = -1;
  2684. llama_pos delta = 0;
  2685. int32_t src = -1; // used by recurrent state models to copy states
  2686. int32_t tail = -1;
  2687. std::set<llama_seq_id> seq_id;
  2688. bool has_seq_id(const llama_seq_id & id) const {
  2689. return seq_id.find(id) != seq_id.end();
  2690. }
  2691. bool is_empty() const {
  2692. return seq_id.empty();
  2693. }
  2694. bool is_same_seq(const llama_kv_cell & other) const {
  2695. return seq_id == other.seq_id;
  2696. }
  2697. };
  2698. // ring-buffer of cached KV data
  2699. struct llama_kv_cache {
  2700. bool has_shift = false;
  2701. bool do_defrag = false;
  2702. bool recurrent = false; // with recurrent state models, a cell can hold the state for more than one past token
  2703. bool v_trans = true; // the value tensor is transposed
  2704. // Note: The value of head isn't only used to optimize searching
  2705. // for a free KV slot. llama_decode_internal also uses it, so it
  2706. // cannot be freely changed after a slot has been allocated.
  2707. uint32_t head = 0;
  2708. uint32_t size = 0;
  2709. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  2710. // computed before each graph build
  2711. uint32_t n = 0;
  2712. ggml_type type_k = GGML_TYPE_F16;
  2713. ggml_type type_v = GGML_TYPE_F16;
  2714. std::vector<llama_kv_cell> cells;
  2715. std::vector<struct ggml_tensor *> k_l; // per layer
  2716. std::vector<struct ggml_tensor *> v_l;
  2717. std::vector<struct ggml_context *> ctxs;
  2718. std::vector<ggml_backend_buffer_t> bufs;
  2719. size_t total_size() const {
  2720. size_t size = 0;
  2721. for (ggml_backend_buffer_t buf : bufs) {
  2722. size += ggml_backend_buffer_get_size(buf);
  2723. }
  2724. return size;
  2725. }
  2726. ~llama_kv_cache() {
  2727. for (struct ggml_context * ctx : ctxs) {
  2728. ggml_free(ctx);
  2729. }
  2730. for (ggml_backend_buffer_t buf : bufs) {
  2731. ggml_backend_buffer_free(buf);
  2732. }
  2733. }
  2734. };
  2735. struct llama_control_vector {
  2736. std::vector<struct ggml_tensor *> tensors; // per layer
  2737. std::vector<struct ggml_context *> ctxs;
  2738. std::vector<ggml_backend_buffer_t> bufs;
  2739. int32_t layer_start = -1;
  2740. int32_t layer_end = -1;
  2741. struct ggml_tensor * tensor_for(int il) const {
  2742. if (il < 0 || il < layer_start || il > layer_end || (size_t) il >= tensors.size()) {
  2743. return nullptr;
  2744. }
  2745. return tensors[il];
  2746. }
  2747. struct ggml_tensor * apply_to(struct ggml_context * ctx, struct ggml_tensor * cur, int il) const {
  2748. ggml_tensor * layer_dir = tensor_for(il);
  2749. if (layer_dir != nullptr) {
  2750. cur = ggml_add(ctx, cur, layer_dir);
  2751. }
  2752. return cur;
  2753. }
  2754. ~llama_control_vector() {
  2755. for (struct ggml_context * ctx : ctxs) {
  2756. ggml_free(ctx);
  2757. }
  2758. for (ggml_backend_buffer_t buf : bufs) {
  2759. ggml_backend_buffer_free(buf);
  2760. }
  2761. }
  2762. };
  2763. struct llama_model {
  2764. e_model type = MODEL_UNKNOWN;
  2765. llm_arch arch = LLM_ARCH_UNKNOWN;
  2766. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  2767. std::string name = "n/a";
  2768. llama_hparams hparams = {};
  2769. llama_vocab vocab;
  2770. // TODO: should init all tensors to nullptr
  2771. struct ggml_tensor * tok_embd;
  2772. struct ggml_tensor * type_embd;
  2773. struct ggml_tensor * pos_embd;
  2774. struct ggml_tensor * tok_norm;
  2775. struct ggml_tensor * tok_norm_b;
  2776. struct ggml_tensor * output_norm;
  2777. struct ggml_tensor * output_norm_b;
  2778. struct ggml_tensor * output;
  2779. struct ggml_tensor * output_b;
  2780. struct ggml_tensor * output_norm_enc;
  2781. // classifier
  2782. struct ggml_tensor * cls;
  2783. struct ggml_tensor * cls_b;
  2784. struct ggml_tensor * cls_out = nullptr;
  2785. struct ggml_tensor * cls_out_b = nullptr;
  2786. std::vector<llama_layer> layers;
  2787. llama_split_mode split_mode;
  2788. int main_gpu;
  2789. int n_gpu_layers;
  2790. std::vector<std::string> rpc_servers;
  2791. // gguf metadata
  2792. std::unordered_map<std::string, std::string> gguf_kv;
  2793. // layer -> buffer type mapping
  2794. struct layer_buft {
  2795. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  2796. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  2797. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  2798. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  2799. ggml_backend_buffer_type_t buft; // everything else
  2800. };
  2801. layer_buft buft_input;
  2802. layer_buft buft_output;
  2803. std::vector<layer_buft> buft_layer;
  2804. // contexts where the model tensors metadata is stored
  2805. std::vector<struct ggml_context *> ctxs;
  2806. // the model memory buffers for the tensor data
  2807. std::vector<ggml_backend_buffer_t> bufs;
  2808. // model memory mapped files
  2809. llama_mmaps mappings;
  2810. // objects representing data potentially being locked in memory
  2811. llama_mlocks mlock_bufs;
  2812. llama_mlocks mlock_mmaps;
  2813. // for quantize-stats only
  2814. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  2815. int64_t t_load_us = 0;
  2816. int64_t t_start_us = 0;
  2817. // keep track of loaded lora adapters
  2818. std::set<struct llama_lora_adapter *> lora_adapters;
  2819. ~llama_model() {
  2820. for (struct ggml_context * ctx : ctxs) {
  2821. ggml_free(ctx);
  2822. }
  2823. for (ggml_backend_buffer_t buf : bufs) {
  2824. #ifdef GGML_USE_CUDA
  2825. if (ggml_backend_buffer_get_type(buf) == ggml_backend_cpu_buffer_type()) {
  2826. ggml_backend_cuda_unregister_host_buffer(ggml_backend_buffer_get_base(buf));
  2827. }
  2828. #endif
  2829. ggml_backend_buffer_free(buf);
  2830. }
  2831. while (!lora_adapters.empty()) {
  2832. llama_lora_adapter_free(*lora_adapters.begin());
  2833. }
  2834. }
  2835. };
  2836. struct llama_sbatch_seq {
  2837. int32_t n_seq_id;
  2838. llama_seq_id * seq_id;
  2839. size_t offset;
  2840. size_t length;
  2841. // helper for smoother batch API transition -- can be deprecated in the future
  2842. llama_seq_id all_seq_id; // used if seq_id == NULL
  2843. };
  2844. // sequence-length-aware batch splitting
  2845. struct llama_sbatch {
  2846. // tokens left in this batch
  2847. size_t n_tokens;
  2848. size_t n_embd;
  2849. bool logits_all; // TODO: remove once lctx.logits_all is removed too
  2850. // sorted indices into the batch
  2851. std::vector<size_t> ids;
  2852. // batch indices of the output
  2853. std::vector<size_t> out_ids;
  2854. std::vector<llama_sbatch_seq> seq;
  2855. const llama_batch * batch = nullptr;
  2856. // buffers for the ubatch
  2857. std::vector<llama_token> ubatch_token;
  2858. std::vector<float> ubatch_embd;
  2859. std::vector<llama_pos> ubatch_pos;
  2860. std::vector<int32_t> ubatch_n_seq_id;
  2861. std::vector<llama_seq_id *> ubatch_seq_id;
  2862. std::vector<int8_t> ubatch_output;
  2863. llama_ubatch reserve_ubatch(size_t n_ubatch, bool has_embd = false) {
  2864. // clear empty sequences
  2865. // the previous ubatch is assumed to be gone,
  2866. // so nothing should refer to values in these sequences anymore.
  2867. for (size_t i = seq.size(); i-- > 0;) {
  2868. if (seq[i].length == 0) {
  2869. seq.pop_back();
  2870. } else {
  2871. break;
  2872. }
  2873. }
  2874. ubatch_token.resize(!has_embd ? n_ubatch : 0);
  2875. ubatch_embd.resize(has_embd ? n_embd * n_ubatch : 0);
  2876. ubatch_pos.resize(n_ubatch);
  2877. ubatch_n_seq_id.resize(n_ubatch);
  2878. ubatch_seq_id.resize(n_ubatch);
  2879. ubatch_output.resize(n_ubatch);
  2880. llama_ubatch ubatch = {
  2881. /*equal_seqs =*/ true,
  2882. /*n_tokens =*/ 0,
  2883. /*n_seq_tokens =*/ 0,
  2884. /*n_seqs =*/ 0,
  2885. /*token =*/ !has_embd ? ubatch_token.data() : nullptr,
  2886. /*embd =*/ has_embd ? ubatch_embd.data() : nullptr,
  2887. /*pos =*/ ubatch_pos.data(),
  2888. /*n_seq_id =*/ ubatch_n_seq_id.data(),
  2889. /*seq_id =*/ ubatch_seq_id.data(),
  2890. /*output =*/ ubatch_output.data(),
  2891. };
  2892. return ubatch;
  2893. }
  2894. void add_seq_to_ubatch(llama_ubatch & ubatch, llama_sbatch_seq & seq, size_t length) {
  2895. GGML_ASSERT(batch != nullptr);
  2896. GGML_ASSERT(length <= seq.length);
  2897. // Can only add sequences of equal lengths to a batch,
  2898. // otherwise it isn't clear to which sequence a token belongs
  2899. GGML_ASSERT(seq.n_seq_id == 0 || ubatch.n_seqs == 0 || length == (size_t) ubatch.n_tokens / ubatch.n_seqs);
  2900. GGML_ASSERT((seq.n_seq_id != 0) == ubatch.equal_seqs);
  2901. // NOTE: loops are separated for cache-friendliness
  2902. if (batch->token) {
  2903. if (ubatch.equal_seqs) {
  2904. for (size_t i = 0; i < length; ++i) {
  2905. ubatch.token[ubatch.n_tokens + i] = batch->token[ids[seq.offset + i]];
  2906. }
  2907. } else {
  2908. // simple split
  2909. ubatch.token = batch->token + seq.offset;
  2910. }
  2911. } else {
  2912. ubatch.token = nullptr;
  2913. }
  2914. if (batch->embd) {
  2915. if (ubatch.equal_seqs) {
  2916. for (size_t i = 0; i < length; ++i) {
  2917. memcpy(
  2918. ubatch.embd + n_embd * (ubatch.n_tokens + i),
  2919. batch->embd + n_embd * ids[seq.offset + i],
  2920. n_embd * sizeof(float)
  2921. );
  2922. }
  2923. } else {
  2924. // simple split
  2925. ubatch.embd = batch->embd + (n_embd * seq.offset);
  2926. }
  2927. } else {
  2928. ubatch.embd = nullptr;
  2929. }
  2930. // from here on, the else branches are deprecated;
  2931. // they are helpers for smoother batch API transition
  2932. if (batch->pos) {
  2933. if (ubatch.equal_seqs) {
  2934. for (size_t i = 0; i < length; ++i) {
  2935. ubatch.pos[ubatch.n_tokens + i] = batch->pos[ids[seq.offset + i]];
  2936. }
  2937. } else {
  2938. // simple split
  2939. ubatch.pos = batch->pos + seq.offset;
  2940. }
  2941. } else {
  2942. for (size_t i = 0; i < length; ++i) {
  2943. llama_pos bi = ids[seq.offset + i];
  2944. ubatch.pos[ubatch.n_tokens + i] = batch->all_pos_0 + (bi * batch->all_pos_1);
  2945. }
  2946. }
  2947. if (ubatch.equal_seqs) {
  2948. ubatch.n_seq_id[ubatch.n_seqs] = seq.n_seq_id;
  2949. if (seq.seq_id) {
  2950. ubatch.seq_id[ubatch.n_seqs] = seq.seq_id;
  2951. } else {
  2952. GGML_ASSERT(seq.n_seq_id == 1);
  2953. ubatch.seq_id[ubatch.n_seqs] = &seq.all_seq_id;
  2954. }
  2955. } else {
  2956. // simple split
  2957. if (batch->n_seq_id) {
  2958. ubatch.n_seq_id = batch->n_seq_id + seq.offset;
  2959. } else {
  2960. for (size_t i = 0; i < length; ++i) {
  2961. ubatch.n_seq_id[ubatch.n_seqs + i] = 1;
  2962. }
  2963. }
  2964. if (batch->seq_id) {
  2965. ubatch.seq_id = batch->seq_id + seq.offset;
  2966. } else {
  2967. for (size_t i = 0; i < length; ++i) {
  2968. ubatch.seq_id[ubatch.n_seqs + i] = &seq.all_seq_id;
  2969. }
  2970. }
  2971. }
  2972. if (logits_all) {
  2973. for (size_t i = 0; i < length; ++i) {
  2974. ubatch.output[ubatch.n_tokens + i] = 1;
  2975. out_ids.push_back(ids[seq.offset + i]);
  2976. }
  2977. } else if (batch->logits) {
  2978. if (ubatch.equal_seqs) {
  2979. for (size_t i = 0; i < length; ++i) {
  2980. size_t id = ids[seq.offset + i];
  2981. int8_t is_output = batch->logits[id];
  2982. ubatch.output[ubatch.n_tokens + i] = is_output;
  2983. if (is_output) { out_ids.push_back(id); }
  2984. }
  2985. } else {
  2986. // simple split
  2987. ubatch.output = batch->logits + seq.offset;
  2988. for (size_t i = 0; i < length; ++i) {
  2989. if (ubatch.output[i] != 0) { out_ids.push_back(seq.offset + i); }
  2990. }
  2991. }
  2992. } else {
  2993. // only get last output
  2994. for (size_t i = 0; i < length; ++i) {
  2995. size_t id = ids[seq.offset + i];
  2996. int8_t is_last = id == ids.size() - 1;
  2997. ubatch.output[ubatch.n_tokens + i] = is_last;
  2998. if (is_last) { out_ids.push_back(id); }
  2999. }
  3000. }
  3001. if (ubatch.n_tokens == 0 && ubatch.n_seqs == 0) {
  3002. ubatch.n_seq_tokens = ubatch.equal_seqs ? length : 1;
  3003. }
  3004. ubatch.n_tokens += length;
  3005. ubatch.n_seqs += ubatch.equal_seqs ? 1 : length; // virtual sequences for simple splits
  3006. seq.offset += length;
  3007. seq.length -= length;
  3008. n_tokens -= length;
  3009. GGML_ASSERT(ubatch.n_tokens == ubatch.n_seq_tokens * ubatch.n_seqs);
  3010. }
  3011. // simple split, unknown number of sequences of unequal lengths
  3012. llama_ubatch split_simple(size_t n_ubatch) {
  3013. n_ubatch = n_tokens < n_ubatch ? n_tokens : n_ubatch;
  3014. llama_ubatch ubatch = reserve_ubatch(n_ubatch, /* has_embd */ batch->embd != nullptr);
  3015. ubatch.equal_seqs = false;
  3016. if (!seq.empty()) {
  3017. llama_sbatch_seq & s = seq[0];
  3018. size_t length = s.length < n_ubatch ? s.length : n_ubatch;
  3019. GGML_ASSERT(seq.size() == 1 && s.n_seq_id == 0); // don't mix with other splits
  3020. add_seq_to_ubatch(ubatch, s, length);
  3021. }
  3022. return ubatch;
  3023. }
  3024. // make batches of equal-length sequences
  3025. llama_ubatch split_equal(size_t n_ubatch) {
  3026. n_ubatch = n_tokens < n_ubatch ? n_tokens : n_ubatch;
  3027. llama_ubatch ubatch = reserve_ubatch(n_ubatch, /* has_embd */ batch->embd != nullptr);
  3028. if (!seq.empty()) {
  3029. size_t length = 0;
  3030. size_t n_tokens_in_ubatch = 0;
  3031. GGML_ASSERT(seq[0].n_seq_id > 0); // should not be mixed with simple splits
  3032. // smallest first, because it's easier to split this way;
  3033. // starting from the end to pop in constant time.
  3034. for (size_t i = seq.size(); i-- > 0;) {
  3035. llama_sbatch_seq & s = seq[i];
  3036. GGML_ASSERT(s.length > 0);
  3037. if (length == 0) {
  3038. length = s.length < n_ubatch ? s.length : n_ubatch;
  3039. }
  3040. add_seq_to_ubatch(ubatch, s, length);
  3041. n_tokens_in_ubatch += length;
  3042. // shared prompts can't be mixed with any of their sequences,
  3043. // so it's safer to compute them in their own ubatch
  3044. if (s.n_seq_id > 1) { break; }
  3045. // stop when there isn't enough space for another sequence
  3046. if (length + n_tokens_in_ubatch > n_ubatch) { break; }
  3047. }
  3048. }
  3049. return ubatch;
  3050. }
  3051. // sequence-wise split
  3052. llama_ubatch split_seq(size_t n_ubatch) {
  3053. n_ubatch = n_tokens < n_ubatch ? n_tokens : n_ubatch;
  3054. llama_ubatch ubatch = reserve_ubatch(n_ubatch, /* has_embd */ batch->embd != nullptr);
  3055. if (!seq.empty()) {
  3056. llama_sbatch_seq & s = seq[seq.size() - 1];
  3057. size_t length = s.length < n_ubatch ? s.length : n_ubatch;
  3058. GGML_ASSERT(s.n_seq_id > 0); // should not be mixed with simple splits
  3059. add_seq_to_ubatch(ubatch, s, length);
  3060. }
  3061. return ubatch;
  3062. }
  3063. void from_batch(const llama_batch & batch, const size_t n_embd, const bool simple_split = false, const bool logits_all = false) {
  3064. GGML_ASSERT(batch.n_tokens >= 0);
  3065. this->batch = &batch;
  3066. this->n_embd = n_embd;
  3067. this->logits_all = logits_all;
  3068. n_tokens = batch.n_tokens;
  3069. ids.resize(n_tokens);
  3070. out_ids.clear();
  3071. // TODO: reserve out_ids and seq
  3072. for (size_t i = 0; i < n_tokens; ++i) {
  3073. ids[i] = i;
  3074. }
  3075. if (simple_split) {
  3076. seq.resize(1);
  3077. llama_sbatch_seq & s = seq[0];
  3078. s.n_seq_id = 0;
  3079. s.seq_id = nullptr;
  3080. s.offset = 0;
  3081. s.length = n_tokens;
  3082. s.all_seq_id = batch.all_seq_id;
  3083. return;
  3084. }
  3085. std::sort(ids.begin(), ids.end(),
  3086. [&batch](size_t a, size_t b) {
  3087. int32_t n_seq_a = batch.n_seq_id ? batch.n_seq_id[a] : 1;
  3088. int32_t n_seq_b = batch.n_seq_id ? batch.n_seq_id[b] : 1;
  3089. // sort by seq_id, then by pos
  3090. if (n_seq_a == n_seq_b) {
  3091. if (batch.seq_id) {
  3092. for (int32_t i = 0; i < n_seq_a; ++i) {
  3093. llama_seq_id seq_id_a = batch.seq_id[a][i];
  3094. llama_seq_id seq_id_b = batch.seq_id[b][i];
  3095. // smaller seq_ids go first
  3096. if (seq_id_a != seq_id_b) {
  3097. return seq_id_a < seq_id_b;
  3098. }
  3099. }
  3100. }
  3101. // when all else is equal, sort by pos
  3102. if (batch.pos) {
  3103. return batch.pos[a] < batch.pos[b];
  3104. }
  3105. // no pos, sort by id (assuming batch.all_pos_1 is positive)
  3106. return a < b;
  3107. }
  3108. // shared prompts go first
  3109. return n_seq_a > n_seq_b;
  3110. }
  3111. );
  3112. // init seq
  3113. llama_sbatch_seq * last_seq = nullptr;
  3114. if (batch.n_seq_id != nullptr && batch.seq_id != nullptr) {
  3115. for (size_t i = 0; i < n_tokens; ++i) {
  3116. const size_t bi = ids[i];
  3117. const int32_t n_seqs = batch.n_seq_id[bi];
  3118. llama_seq_id * seq_ids = batch.seq_id[bi];
  3119. if (last_seq != nullptr) {
  3120. bool same = n_seqs == last_seq->n_seq_id;
  3121. for (int32_t j = 0; same && j < n_seqs; ++j) {
  3122. if (seq_ids[j] != last_seq->seq_id[j]) {
  3123. same = false;
  3124. }
  3125. }
  3126. if (same) {
  3127. last_seq->length += 1;
  3128. continue;
  3129. }
  3130. }
  3131. llama_sbatch_seq new_seq = {n_seqs, seq_ids, i, 1, batch.all_seq_id};
  3132. seq.push_back(new_seq);
  3133. last_seq = &seq.back();
  3134. }
  3135. } else {
  3136. llama_sbatch_seq new_seq = {1, nullptr, 0, n_tokens, batch.all_seq_id};
  3137. seq.push_back(new_seq);
  3138. }
  3139. // keep shared prompts first at the end, then sort by length descending.
  3140. std::sort(seq.begin(), seq.end(),
  3141. [](llama_sbatch_seq & a, llama_sbatch_seq & b) {
  3142. if (a.n_seq_id == b.n_seq_id) {
  3143. return a.length > b.length;
  3144. }
  3145. return a.n_seq_id < b.n_seq_id;
  3146. }
  3147. );
  3148. }
  3149. };
  3150. struct llama_context {
  3151. llama_context(const llama_model & model)
  3152. : model(model)
  3153. , t_start_us(model.t_start_us)
  3154. , t_load_us(model.t_load_us) {}
  3155. ~llama_context() {
  3156. ggml_backend_sched_free(sched);
  3157. for (ggml_backend_t backend : backends) {
  3158. ggml_backend_free(backend);
  3159. }
  3160. ggml_backend_buffer_free(buf_output);
  3161. }
  3162. const struct llama_model & model;
  3163. struct llama_cparams cparams;
  3164. struct llama_sbatch sbatch;
  3165. struct llama_kv_cache kv_self;
  3166. struct llama_control_vector cvec;
  3167. std::unordered_map<struct llama_lora_adapter *, float> lora_adapters;
  3168. std::vector<ggml_backend_t> backends;
  3169. #ifdef GGML_USE_METAL
  3170. ggml_backend_t backend_metal = nullptr;
  3171. #endif
  3172. #ifdef GGML_USE_BLAS
  3173. ggml_backend_t backend_blas = nullptr;
  3174. #endif
  3175. ggml_backend_t backend_cpu = nullptr;
  3176. ggml_threadpool_t threadpool = nullptr;
  3177. ggml_threadpool_t threadpool_batch = nullptr;
  3178. bool has_evaluated_once = false;
  3179. mutable int64_t t_start_us;
  3180. mutable int64_t t_load_us;
  3181. mutable int64_t t_p_eval_us = 0;
  3182. mutable int64_t t_eval_us = 0;
  3183. mutable int64_t t_compute_start_us = 0;
  3184. mutable int64_t n_queued_tokens = 0;
  3185. mutable int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  3186. mutable int32_t n_eval = 0; // number of eval calls
  3187. // host buffer for the model output (logits and embeddings)
  3188. ggml_backend_buffer_t buf_output = nullptr;
  3189. // decode output (2-dimensional array: [n_outputs][n_vocab])
  3190. size_t logits_size = 0; // capacity (of floats) for logits
  3191. float * logits = nullptr;
  3192. std::vector<int32_t> output_ids; // map batch token positions to ids of the logits and embd buffers
  3193. size_t output_size = 0; // capacity (of tokens positions) for the output buffers
  3194. int32_t n_outputs = 0; // number of actually-used outputs in the current ubatch or last logical batch
  3195. bool logits_all = false;
  3196. // embeddings output (2-dimensional array: [n_outputs][n_embd])
  3197. // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE
  3198. size_t embd_size = 0; // capacity (of floats) for embeddings
  3199. float * embd = nullptr;
  3200. // sequence embeddings output (map of [n_embd] vectors)
  3201. // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE
  3202. std::map<llama_seq_id, std::vector<float>> embd_seq;
  3203. // whether we are computing encoder output or decoder output
  3204. bool is_encoding = false;
  3205. // output of the encoder part of the encoder-decoder models
  3206. std::vector<float> embd_enc;
  3207. std::vector<std::set<llama_seq_id>> seq_ids_enc;
  3208. // memory buffers used to evaluate the model
  3209. std::vector<uint8_t> buf_compute_meta;
  3210. ggml_backend_sched_t sched = nullptr;
  3211. ggml_abort_callback abort_callback = nullptr;
  3212. void * abort_callback_data = nullptr;
  3213. // input tensors
  3214. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  3215. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  3216. struct ggml_tensor * inp_pos; // I32 [n_batch]
  3217. struct ggml_tensor * inp_out_ids; // I32 [n_outputs]
  3218. struct ggml_tensor * inp_KQ_mask; // F32 [kv_size, n_batch]
  3219. struct ggml_tensor * inp_KQ_mask_swa; // F32 [kv_size, n_batch]
  3220. struct ggml_tensor * inp_K_shift; // I32 [kv_size]
  3221. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  3222. struct ggml_tensor * inp_cls; // I32 [n_batch]
  3223. struct ggml_tensor * inp_s_copy; // I32 [kv_size]
  3224. struct ggml_tensor * inp_s_mask; // F32 [1, n_kv]
  3225. struct ggml_tensor * inp_s_seq; // I32 [n_kv, n_batch]
  3226. struct ggml_tensor * inp_pos_bucket; // I32 [n_batch|n_kv, n_batch]
  3227. struct ggml_tensor * inp_embd_enc; // F32 [n_embd, n_outputs_enc]
  3228. struct ggml_tensor * inp_KQ_mask_cross; // F32 [n_outputs_enc, n_batch]
  3229. // TODO (jmorganca): this should most likely be passed in as part of a batch
  3230. // and not set on the context for all batches.
  3231. float * cross_attn_state = nullptr;
  3232. bool cross_attn_state_first_pass = true;
  3233. struct ggml_tensor * inp_cross_attn_state; // F32 [4, n_embd, 1061]
  3234. };
  3235. struct llama_lora_weight {
  3236. struct ggml_tensor * a = nullptr;
  3237. struct ggml_tensor * b = nullptr;
  3238. llama_lora_weight() = default;
  3239. llama_lora_weight(struct ggml_tensor * a, struct ggml_tensor * b): a(a), b(b) {}
  3240. };
  3241. struct llama_lora_adapter {
  3242. struct llama_model * base_model;
  3243. // map tensor name to lora_a_b
  3244. std::unordered_map<std::string, struct llama_lora_weight> ab_map;
  3245. std::vector<struct ggml_context *> ctxs;
  3246. std::vector<ggml_backend_buffer_t> bufs;
  3247. float alpha;
  3248. llama_lora_adapter(struct llama_model * base_model): base_model(base_model) {
  3249. base_model->lora_adapters.insert(this);
  3250. }
  3251. llama_lora_weight * get_weight(struct ggml_tensor * w) {
  3252. std::string name(w->name);
  3253. auto pos = ab_map.find(name);
  3254. if (ab_map.find(name) != ab_map.end()) {
  3255. return &pos->second;
  3256. }
  3257. return nullptr;
  3258. }
  3259. ~llama_lora_adapter() {
  3260. for (struct ggml_context * ctx : ctxs) {
  3261. ggml_free(ctx);
  3262. }
  3263. for (ggml_backend_buffer_t buf : bufs) {
  3264. ggml_backend_buffer_free(buf);
  3265. }
  3266. auto pos = base_model->lora_adapters.find(this);
  3267. if (pos != base_model->lora_adapters.end()) {
  3268. base_model->lora_adapters.erase(pos);
  3269. }
  3270. }
  3271. };
  3272. static size_t llama_get_device_count(const llama_model & model) {
  3273. size_t count = 1;
  3274. #if defined(GGML_USE_CUDA)
  3275. count = ggml_backend_cuda_get_device_count();
  3276. #elif defined(GGML_USE_SYCL)
  3277. count = ggml_backend_sycl_get_device_count();
  3278. #elif defined(GGML_USE_VULKAN)
  3279. count = ggml_backend_vk_get_device_count();
  3280. #elif defined(GGML_USE_CANN)
  3281. return ggml_backend_cann_get_device_count();
  3282. #endif
  3283. #if defined(GGML_USE_RPC)
  3284. count += model.rpc_servers.size();
  3285. #endif
  3286. return count;
  3287. GGML_UNUSED(model);
  3288. }
  3289. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(const llama_model & model, int gpu) {
  3290. ggml_backend_buffer_type_t buft = nullptr;
  3291. #ifdef GGML_USE_RPC
  3292. int rpc_count = (int)model.rpc_servers.size();
  3293. #else
  3294. int rpc_count = 0;
  3295. #endif
  3296. int local_gpu = gpu - rpc_count;
  3297. #if defined(GGML_USE_RPC)
  3298. if (gpu < rpc_count) {
  3299. const char * endpoint = model.rpc_servers[gpu].c_str();
  3300. return ggml_backend_rpc_buffer_type(endpoint);
  3301. }
  3302. #endif
  3303. #if defined(GGML_USE_METAL)
  3304. buft = ggml_backend_metal_buffer_type();
  3305. #elif defined(GGML_USE_CUDA)
  3306. buft = ggml_backend_cuda_buffer_type(local_gpu);
  3307. #elif defined(GGML_USE_VULKAN)
  3308. buft = ggml_backend_vk_buffer_type(local_gpu);
  3309. #elif defined(GGML_USE_SYCL)
  3310. buft = ggml_backend_sycl_buffer_type(local_gpu);
  3311. #elif defined(GGML_USE_KOMPUTE)
  3312. buft = ggml_backend_kompute_buffer_type(local_gpu);
  3313. if (buft == nullptr) {
  3314. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, local_gpu);
  3315. }
  3316. #elif defined(GGML_USE_CANN)
  3317. buft = ggml_backend_cann_buffer_type(local_gpu);
  3318. #endif
  3319. if (buft == nullptr) {
  3320. buft = llama_default_buffer_type_cpu(true);
  3321. }
  3322. return buft;
  3323. GGML_UNUSED(model);
  3324. GGML_UNUSED(local_gpu);
  3325. }
  3326. static ggml_backend_buffer_type_t llama_default_buffer_type_split(const llama_model & model, int fallback_gpu, const float * tensor_split) {
  3327. ggml_backend_buffer_type_t buft = nullptr;
  3328. #ifdef GGML_USE_CUDA
  3329. if (ggml_backend_cuda_get_device_count() > 1) {
  3330. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  3331. }
  3332. #endif
  3333. #ifdef GGML_USE_SYCL
  3334. if (ggml_backend_sycl_get_device_count() > 1) {
  3335. buft = ggml_backend_sycl_split_buffer_type(tensor_split);
  3336. }
  3337. #endif
  3338. if (buft == nullptr) {
  3339. buft = llama_default_buffer_type_offload(model, fallback_gpu);
  3340. }
  3341. return buft;
  3342. GGML_UNUSED(tensor_split);
  3343. }
  3344. static size_t llama_get_device_memory(const llama_model & model, int device) {
  3345. #ifdef GGML_USE_RPC
  3346. int rpc_count = (int)model.rpc_servers.size();
  3347. #else
  3348. int rpc_count = 0;
  3349. #endif
  3350. int local_device = device - rpc_count;
  3351. #if defined(GGML_USE_RPC)
  3352. if (device < rpc_count) {
  3353. size_t total;
  3354. size_t free;
  3355. const char * endpoint = model.rpc_servers[device].c_str();
  3356. ggml_backend_rpc_get_device_memory(endpoint, &free, &total);
  3357. return free;
  3358. }
  3359. #endif
  3360. #if defined(GGML_USE_CUDA)
  3361. size_t total;
  3362. size_t free;
  3363. ggml_backend_cuda_get_device_memory(local_device, &free, &total);
  3364. return free;
  3365. #elif defined(GGML_USE_SYCL)
  3366. size_t total;
  3367. size_t free;
  3368. ggml_backend_sycl_get_device_memory(local_device, &free, &total);
  3369. return free;
  3370. #elif defined(GGML_USE_VULKAN)
  3371. size_t total;
  3372. size_t free;
  3373. ggml_backend_vk_get_device_memory(local_device, &free, &total);
  3374. return free;
  3375. #elif defined(GGML_USE_CANN)
  3376. size_t total;
  3377. size_t free;
  3378. ggml_backend_cann_get_device_memory(local_device, &free, &total);
  3379. return free;
  3380. #else
  3381. return 1;
  3382. #endif
  3383. GGML_UNUSED(model);
  3384. GGML_UNUSED(local_device);
  3385. }
  3386. //
  3387. // kv cache helpers
  3388. //
  3389. static bool llama_kv_cache_init(
  3390. struct llama_kv_cache & cache,
  3391. const llama_context * ctx,
  3392. ggml_type type_k,
  3393. ggml_type type_v,
  3394. uint32_t kv_size,
  3395. bool offload) {
  3396. const llama_model & model = ctx->model;
  3397. const llama_cparams & cparams = ctx->cparams;
  3398. const struct llama_hparams & hparams = model.hparams;
  3399. const int64_t n_layer = hparams.n_layer;
  3400. cache.has_shift = false;
  3401. cache.recurrent = llama_model_is_recurrent(&model);
  3402. cache.v_trans = !cache.recurrent && !cparams.flash_attn;
  3403. cache.head = 0;
  3404. cache.size = kv_size;
  3405. cache.used = 0;
  3406. cache.type_k = type_k;
  3407. cache.type_v = type_v;
  3408. cache.cells.clear();
  3409. cache.cells.resize(kv_size);
  3410. // count used buffer types
  3411. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  3412. if (offload) {
  3413. for (int64_t i = 0; i < n_layer; ++i) {
  3414. buft_layer_count[model.buft_layer[i].buft]++;
  3415. }
  3416. } else {
  3417. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  3418. }
  3419. // create a context for each buffer type
  3420. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3421. for (auto & it : buft_layer_count) {
  3422. int n_layers = it.second;
  3423. struct ggml_init_params params = {
  3424. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  3425. /*.mem_buffer =*/ NULL,
  3426. /*.no_alloc =*/ true,
  3427. };
  3428. ggml_context * ctx = ggml_init(params);
  3429. if (!ctx) {
  3430. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  3431. return false;
  3432. }
  3433. ctx_map[it.first] = ctx;
  3434. cache.ctxs.push_back(ctx);
  3435. }
  3436. cache.k_l.reserve(n_layer);
  3437. cache.v_l.reserve(n_layer);
  3438. for (int i = 0; i < (int) n_layer; i++) {
  3439. // for cross attention layers
  3440. if (model.arch == LLM_ARCH_MLLAMA && hparams.cross_attention_layer(i)) {
  3441. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  3442. ggml_tensor * k = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, hparams.n_embd_head_k, 6404, hparams.n_head_kv(i));
  3443. ggml_tensor * v = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, hparams.n_embd_head_v, 6404, hparams.n_head_kv(i));
  3444. ggml_format_name(k, "cache_k_l%d", i);
  3445. ggml_format_name(v, "cache_v_l%d", i);
  3446. cache.k_l.push_back(k);
  3447. cache.v_l.push_back(v);
  3448. continue;
  3449. }
  3450. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(i) + hparams.n_embd_k_s();
  3451. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(i) + hparams.n_embd_v_s();
  3452. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  3453. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  3454. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*kv_size);
  3455. ggml_format_name(k, "cache_k_l%d", i);
  3456. ggml_format_name(v, "cache_v_l%d", i);
  3457. cache.k_l.push_back(k);
  3458. cache.v_l.push_back(v);
  3459. }
  3460. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  3461. for (auto it : ctx_map) {
  3462. ggml_backend_buffer_type_t buft = it.first;
  3463. ggml_context * ctx = it.second;
  3464. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  3465. if (!buf) {
  3466. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  3467. return false;
  3468. }
  3469. ggml_backend_buffer_clear(buf, 0);
  3470. 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);
  3471. cache.bufs.push_back(buf);
  3472. }
  3473. return true;
  3474. }
  3475. // find an empty slot of size "n_tokens" in the cache
  3476. // updates the cache head
  3477. // Note: On success, it's important that cache.head points
  3478. // to the first cell of the slot.
  3479. static bool llama_kv_cache_find_slot(
  3480. struct llama_kv_cache & cache,
  3481. const struct llama_ubatch & batch) {
  3482. const uint32_t n_tokens = batch.n_tokens;
  3483. const uint32_t n_seqs = batch.n_seqs;
  3484. const uint32_t n_seq_tokens = batch.n_seq_tokens;
  3485. if (cache.recurrent) {
  3486. // For recurrent state architectures (like Mamba or RWKV),
  3487. // each cache cell can store the state for a whole sequence.
  3488. // A slot should be always be contiguous.
  3489. // can only process batches with an equal number of new tokens in each sequence
  3490. GGML_ASSERT(batch.equal_seqs);
  3491. int32_t min = cache.size - 1;
  3492. int32_t max = 0;
  3493. // everything should fit if all seq_ids are smaller than the max
  3494. for (uint32_t s = 0; s < n_seqs; ++s) {
  3495. const uint32_t n_seq_id = batch.n_seq_id[s];
  3496. for (uint32_t j = 0; j < n_seq_id; ++j) {
  3497. const llama_seq_id seq_id = batch.seq_id[s][j];
  3498. if (seq_id < 0 || (uint32_t) seq_id >= cache.size) {
  3499. // too big seq_id
  3500. // TODO: would it be possible to resize the cache instead?
  3501. LLAMA_LOG_ERROR("%s: seq_id=%d >= n_seq_max=%d Try using a bigger --parallel value\n", __func__, seq_id, cache.size);
  3502. return false;
  3503. }
  3504. if (j > 0) {
  3505. llama_kv_cell & seq = cache.cells[seq_id];
  3506. if (seq.tail >= 0) {
  3507. llama_kv_cell & cell = cache.cells[seq.tail];
  3508. // clear cells from seq_ids that become shared
  3509. // (should not normally happen, but let's handle it anyway)
  3510. cell.seq_id.erase(seq_id);
  3511. seq.tail = -1;
  3512. if (cell.seq_id.empty()) {
  3513. cell.pos = -1;
  3514. cell.src = -1;
  3515. cache.used -= 1;
  3516. }
  3517. }
  3518. }
  3519. }
  3520. }
  3521. #ifndef NDEBUG
  3522. {
  3523. std::vector<int32_t> tails_verif;
  3524. tails_verif.assign(cache.size, -1);
  3525. for (uint32_t i = 0; i < cache.size; ++i) {
  3526. llama_kv_cell & cell = cache.cells[i];
  3527. for (llama_seq_id seq_id : cell.seq_id) {
  3528. if (tails_verif[seq_id] != -1) {
  3529. LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tails_verif[seq_id]);
  3530. }
  3531. tails_verif[seq_id] = i;
  3532. }
  3533. }
  3534. for (uint32_t i = 0; i < cache.size; ++i) {
  3535. if (tails_verif[i] != cache.cells[i].tail) {
  3536. LLAMA_LOG_ERROR("%s: wrong tail for seq_id %d, (%d instead of %d)\n", __func__, i, cache.cells[i].tail, tails_verif[i]);
  3537. }
  3538. }
  3539. }
  3540. #endif
  3541. // find next empty cell
  3542. uint32_t next_empty_cell = cache.head;
  3543. for (uint32_t i = 0; i < cache.size; ++i) {
  3544. if (next_empty_cell >= cache.size) { next_empty_cell -= cache.size; }
  3545. llama_kv_cell & cell = cache.cells[next_empty_cell];
  3546. if (cell.is_empty()) { break; }
  3547. next_empty_cell += 1;
  3548. }
  3549. // find usable cell range
  3550. for (uint32_t s = 0; s < n_seqs; ++s) {
  3551. const llama_seq_id seq_id = batch.seq_id[s][0];
  3552. llama_kv_cell & seq_meta = cache.cells[seq_id];
  3553. bool has_cell = false;
  3554. if (seq_meta.tail >= 0) {
  3555. llama_kv_cell & cell = cache.cells[seq_meta.tail];
  3556. GGML_ASSERT(cell.has_seq_id(seq_id));
  3557. // does this seq_id "own" the cell?
  3558. if (cell.seq_id.size() == 1) { has_cell = true; }
  3559. }
  3560. if (!has_cell) {
  3561. llama_kv_cell & empty_cell = cache.cells[next_empty_cell];
  3562. GGML_ASSERT(empty_cell.is_empty());
  3563. // copy old tail into the empty cell
  3564. if (seq_meta.tail >= 0) {
  3565. llama_kv_cell & orig_cell = cache.cells[seq_meta.tail];
  3566. empty_cell.pos = orig_cell.pos;
  3567. empty_cell.src = orig_cell.src;
  3568. orig_cell.seq_id.erase(seq_id);
  3569. empty_cell.seq_id.insert(seq_id); // will be overwritten
  3570. }
  3571. seq_meta.tail = next_empty_cell;
  3572. // find next empty cell
  3573. if (s + 1 < n_seqs) {
  3574. next_empty_cell += 1;
  3575. for (uint32_t i = 0; i < cache.size; ++i) {
  3576. if (next_empty_cell >= cache.size) { next_empty_cell -= cache.size; }
  3577. llama_kv_cell & cell = cache.cells[next_empty_cell];
  3578. if (cell.is_empty()) { break; }
  3579. next_empty_cell += 1;
  3580. }
  3581. }
  3582. }
  3583. if (min > seq_meta.tail) { min = seq_meta.tail; }
  3584. if (max < seq_meta.tail) { max = seq_meta.tail; }
  3585. }
  3586. // gather and re-order
  3587. for (uint32_t s = 0; s < n_seqs; ++s) {
  3588. int32_t dst_id = s + min;
  3589. int32_t src_id = cache.cells[batch.seq_id[s][0]].tail;
  3590. if (dst_id != src_id) {
  3591. llama_kv_cell & dst_cell = cache.cells[dst_id];
  3592. llama_kv_cell & src_cell = cache.cells[src_id];
  3593. std::swap(dst_cell.pos, src_cell.pos);
  3594. std::swap(dst_cell.src, src_cell.src);
  3595. std::swap(dst_cell.seq_id, src_cell.seq_id);
  3596. // swap tails (assuming they NEVER overlap)
  3597. for (const llama_seq_id seq_id : src_cell.seq_id) {
  3598. cache.cells[seq_id].tail = src_id;
  3599. }
  3600. for (const llama_seq_id seq_id : dst_cell.seq_id) {
  3601. cache.cells[seq_id].tail = dst_id;
  3602. }
  3603. }
  3604. }
  3605. // update the pos of the used seqs
  3606. for (uint32_t s = 0; s < n_seqs; ++s) {
  3607. const llama_pos last_pos = batch.pos[n_seq_tokens * s + n_seq_tokens - 1];
  3608. int32_t cell_id = s + min;
  3609. llama_kv_cell & cell = cache.cells[cell_id];
  3610. if (cell.pos >= 0 && last_pos != cell.pos + (llama_pos) n_seq_tokens) {
  3611. // What should happen when the pos backtracks or skips a value?
  3612. // Clearing the state mid-batch would require special-casing which isn't done.
  3613. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d with %u new tokens\n",
  3614. __func__, last_pos, cell.pos, batch.seq_id[s][0], n_seq_tokens);
  3615. }
  3616. cell.pos = last_pos;
  3617. cell.seq_id.clear();
  3618. for (int32_t j = 0; j < batch.n_seq_id[s]; ++j) {
  3619. const llama_seq_id seq_id = batch.seq_id[s][j];
  3620. cell.seq_id.insert(seq_id);
  3621. cache.cells[seq_id].tail = cell_id;
  3622. }
  3623. }
  3624. // allow getting the range of used cells, from head to head + n
  3625. cache.head = min;
  3626. cache.n = max - min + 1;
  3627. // sanity check
  3628. return cache.n >= n_seqs;
  3629. }
  3630. // otherwise, one cell per token.
  3631. if (n_tokens > cache.size) {
  3632. LLAMA_LOG_ERROR("%s: n_tokens=%d > cache.size=%d\n", __func__, n_tokens, cache.size);
  3633. return false;
  3634. }
  3635. uint32_t n_tested = 0;
  3636. while (true) {
  3637. if (cache.head + n_tokens > cache.size) {
  3638. n_tested += cache.size - cache.head;
  3639. cache.head = 0;
  3640. continue;
  3641. }
  3642. bool found = true;
  3643. for (uint32_t i = 0; i < n_tokens; i++) {
  3644. if (cache.cells[cache.head + i].pos >= 0) {
  3645. found = false;
  3646. cache.head += i + 1;
  3647. n_tested += i + 1;
  3648. break;
  3649. }
  3650. }
  3651. if (found) {
  3652. break;
  3653. }
  3654. if (n_tested >= cache.size) {
  3655. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  3656. return false;
  3657. }
  3658. }
  3659. for (uint32_t s = 0; s < n_seqs; s++) {
  3660. for (uint32_t i = 0; i < n_seq_tokens; ++i) {
  3661. uint32_t k = s*n_seq_tokens + i;
  3662. cache.cells[cache.head + k].pos = batch.pos[k];
  3663. for (int32_t j = 0; j < batch.n_seq_id[s]; j++) {
  3664. cache.cells[cache.head + k].seq_id.insert(batch.seq_id[s][j]);
  3665. }
  3666. }
  3667. }
  3668. cache.used += n_tokens;
  3669. return true;
  3670. }
  3671. // find how many cells are currently in use
  3672. static uint32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  3673. for (uint32_t i = cache.size; i > 0; --i) {
  3674. const llama_kv_cell & cell = cache.cells[i - 1];
  3675. if (cell.pos >= 0 && !cell.is_empty()) {
  3676. return i;
  3677. }
  3678. }
  3679. return 0;
  3680. }
  3681. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  3682. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  3683. cache.cells[i].pos = -1;
  3684. cache.cells[i].seq_id.clear();
  3685. cache.cells[i].src = -1;
  3686. cache.cells[i].tail = -1;
  3687. }
  3688. cache.head = 0;
  3689. cache.used = 0;
  3690. for (auto & buf : cache.bufs) {
  3691. ggml_backend_buffer_clear(buf, 0);
  3692. }
  3693. }
  3694. static bool llama_kv_cache_seq_rm(
  3695. struct llama_kv_cache & cache,
  3696. llama_seq_id seq_id,
  3697. llama_pos p0,
  3698. llama_pos p1) {
  3699. uint32_t new_head = cache.size;
  3700. if (p0 < 0) p0 = 0;
  3701. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3702. // models like Mamba or RWKV can't have a state partially erased
  3703. if (cache.recurrent) {
  3704. if (seq_id >= (int64_t) cache.size) {
  3705. // could be fatal
  3706. return false;
  3707. }
  3708. if (0 <= seq_id) {
  3709. int32_t & tail_id = cache.cells[seq_id].tail;
  3710. if (tail_id >= 0) {
  3711. const llama_kv_cell & cell = cache.cells[tail_id];
  3712. // partial intersection is invalid
  3713. if ((0 < p0 && p0 <= cell.pos) || (0 < p1 && p1 <= cell.pos)) {
  3714. return false;
  3715. }
  3716. // invalidate tails which will be cleared
  3717. if (p0 <= cell.pos && cell.pos < p1) {
  3718. tail_id = -1;
  3719. }
  3720. }
  3721. } else {
  3722. // seq_id is negative, then the range should include everything or nothing
  3723. if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
  3724. return false;
  3725. }
  3726. }
  3727. }
  3728. for (uint32_t i = 0; i < cache.size; ++i) {
  3729. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3730. if (seq_id < 0) {
  3731. cache.cells[i].seq_id.clear();
  3732. } else if (cache.cells[i].has_seq_id(seq_id)) {
  3733. cache.cells[i].seq_id.erase(seq_id);
  3734. } else {
  3735. continue;
  3736. }
  3737. if (cache.cells[i].is_empty()) {
  3738. // keep count of the number of used cells
  3739. if (cache.cells[i].pos >= 0) cache.used--;
  3740. cache.cells[i].pos = -1;
  3741. cache.cells[i].src = -1;
  3742. if (new_head == cache.size) new_head = i;
  3743. }
  3744. }
  3745. }
  3746. // If we freed up a slot, set head to it so searching can start there.
  3747. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  3748. return true;
  3749. }
  3750. static void llama_kv_cache_seq_cp(
  3751. struct llama_kv_cache & cache,
  3752. llama_seq_id seq_id_src,
  3753. llama_seq_id seq_id_dst,
  3754. llama_pos p0,
  3755. llama_pos p1) {
  3756. if (p0 < 0) p0 = 0;
  3757. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3758. if (cache.recurrent) {
  3759. if ((uint32_t) seq_id_dst < cache.size && (uint32_t) seq_id_src < cache.size) {
  3760. llama_kv_cell & tail_src = cache.cells[seq_id_src];
  3761. llama_kv_cell & tail_dst = cache.cells[seq_id_dst];
  3762. if (tail_dst.tail >= 0) {
  3763. // clear destination seq_id if it wasn't empty
  3764. llama_kv_cell & cell_dst = cache.cells[tail_dst.tail];
  3765. cell_dst.seq_id.erase(seq_id_dst);
  3766. tail_dst.tail = -1;
  3767. if (cell_dst.seq_id.empty()) {
  3768. cell_dst.pos = -1;
  3769. cell_dst.delta = -1;
  3770. cell_dst.src = -1;
  3771. cache.used -= 1;
  3772. }
  3773. }
  3774. if (tail_src.tail >= 0) {
  3775. llama_kv_cell & cell_src = cache.cells[tail_src.tail];
  3776. cell_src.seq_id.insert(seq_id_dst);
  3777. tail_dst.tail = tail_src.tail;
  3778. }
  3779. }
  3780. return;
  3781. }
  3782. // otherwise, this is the KV cache of a Transformer-like model
  3783. cache.head = 0;
  3784. for (uint32_t i = 0; i < cache.size; ++i) {
  3785. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3786. cache.cells[i].seq_id.insert(seq_id_dst);
  3787. }
  3788. }
  3789. }
  3790. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  3791. uint32_t new_head = cache.size;
  3792. for (uint32_t i = 0; i < cache.size; ++i) {
  3793. if (cache.recurrent && (llama_seq_id) i != seq_id) {
  3794. cache.cells[i].tail = -1;
  3795. }
  3796. if (!cache.cells[i].has_seq_id(seq_id)) {
  3797. if (cache.cells[i].pos >= 0) cache.used--;
  3798. cache.cells[i].pos = -1;
  3799. cache.cells[i].src = -1;
  3800. cache.cells[i].seq_id.clear();
  3801. if (new_head == cache.size) new_head = i;
  3802. } else {
  3803. cache.cells[i].seq_id.clear();
  3804. cache.cells[i].seq_id.insert(seq_id);
  3805. }
  3806. }
  3807. // If we freed up a slot, set head to it so searching can start there.
  3808. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  3809. }
  3810. static void llama_kv_cache_seq_add(
  3811. struct llama_kv_cache & cache,
  3812. llama_seq_id seq_id,
  3813. llama_pos p0,
  3814. llama_pos p1,
  3815. llama_pos delta) {
  3816. uint32_t new_head = cache.size;
  3817. if (p0 < 0) p0 = 0;
  3818. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3819. // If there is no range then return early to avoid looping over the cache.
  3820. if (p0 == p1) return;
  3821. if (cache.recurrent) {
  3822. // for Mamba-like or RWKV models, only the pos needs to be shifted
  3823. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  3824. const int32_t tail_id = cache.cells[seq_id].tail;
  3825. if (tail_id >= 0) {
  3826. llama_kv_cell & cell = cache.cells[tail_id];
  3827. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  3828. cell.pos += delta;
  3829. }
  3830. }
  3831. }
  3832. return;
  3833. }
  3834. for (uint32_t i = 0; i < cache.size; ++i) {
  3835. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3836. cache.has_shift = true;
  3837. cache.cells[i].pos += delta;
  3838. cache.cells[i].delta += delta;
  3839. if (cache.cells[i].pos < 0) {
  3840. if (!cache.cells[i].is_empty()) {
  3841. cache.used--;
  3842. }
  3843. cache.cells[i].pos = -1;
  3844. cache.cells[i].seq_id.clear();
  3845. if (new_head == cache.size) {
  3846. new_head = i;
  3847. }
  3848. }
  3849. }
  3850. }
  3851. // If we freed up a slot, set head to it so searching can start there.
  3852. // Otherwise we just start the next search from the beginning.
  3853. cache.head = new_head != cache.size ? new_head : 0;
  3854. }
  3855. static void llama_kv_cache_seq_div(
  3856. struct llama_kv_cache & cache,
  3857. llama_seq_id seq_id,
  3858. llama_pos p0,
  3859. llama_pos p1,
  3860. int d) {
  3861. if (p0 < 0) p0 = 0;
  3862. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3863. // If there is no range then return early to avoid looping over the cache.
  3864. if (p0 == p1) return;
  3865. if (cache.recurrent) {
  3866. // for Mamba-like or RWKV models, only the pos needs to be changed
  3867. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  3868. const int32_t tail_id = cache.cells[seq_id].tail;
  3869. if (tail_id >= 0) {
  3870. llama_kv_cell & cell = cache.cells[tail_id];
  3871. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  3872. cell.pos /= d;
  3873. }
  3874. }
  3875. }
  3876. return;
  3877. }
  3878. for (uint32_t i = 0; i < cache.size; ++i) {
  3879. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3880. cache.has_shift = true;
  3881. {
  3882. llama_pos p_old = cache.cells[i].pos;
  3883. cache.cells[i].pos /= d;
  3884. cache.cells[i].delta += cache.cells[i].pos - p_old;
  3885. }
  3886. }
  3887. }
  3888. }
  3889. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  3890. llama_pos result = 0;
  3891. for (uint32_t i = 0; i < cache.size; ++i) {
  3892. if (cache.cells[i].has_seq_id(seq_id)) {
  3893. result = std::max(result, cache.cells[i].pos);
  3894. }
  3895. }
  3896. return result;
  3897. }
  3898. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  3899. if (!cache.recurrent) {
  3900. cache.do_defrag = true;
  3901. }
  3902. }
  3903. static uint32_t llama_kv_cache_get_padding(const struct llama_cparams & cparams) {
  3904. // the FA kernels require padding to avoid extra runtime boundary checks
  3905. return cparams.flash_attn ? 256u : 32u;
  3906. }
  3907. //
  3908. // model loading and saving
  3909. //
  3910. enum llama_fver {
  3911. GGUF_FILE_VERSION_V1 = 1,
  3912. GGUF_FILE_VERSION_V2 = 2,
  3913. GGUF_FILE_VERSION_V3 = 3,
  3914. };
  3915. static const char * llama_file_version_name(llama_fver version) {
  3916. switch (version) {
  3917. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  3918. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  3919. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  3920. }
  3921. return "unknown";
  3922. }
  3923. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  3924. char buf[256];
  3925. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  3926. for (size_t i = 1; i < ne.size(); i++) {
  3927. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  3928. }
  3929. return buf;
  3930. }
  3931. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  3932. char buf[256];
  3933. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  3934. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  3935. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  3936. }
  3937. return buf;
  3938. }
  3939. namespace GGUFMeta {
  3940. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  3941. struct GKV_Base_Type {
  3942. static constexpr gguf_type gt = gt_;
  3943. static T getter(const gguf_context * ctx, const int kid) {
  3944. return gfun(ctx, kid);
  3945. }
  3946. };
  3947. template<typename T> struct GKV_Base;
  3948. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  3949. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  3950. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  3951. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  3952. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  3953. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  3954. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  3955. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  3956. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  3957. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  3958. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  3959. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  3960. template<> struct GKV_Base<std::string> {
  3961. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  3962. static std::string getter(const gguf_context * ctx, const int kid) {
  3963. return gguf_get_val_str(ctx, kid);
  3964. }
  3965. };
  3966. struct ArrayInfo {
  3967. const gguf_type gt;
  3968. const size_t length;
  3969. const void * data;
  3970. };
  3971. template<> struct GKV_Base<ArrayInfo> {
  3972. public:
  3973. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  3974. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  3975. return ArrayInfo {
  3976. gguf_get_arr_type(ctx, k),
  3977. size_t(gguf_get_arr_n(ctx, k)),
  3978. gguf_get_arr_data(ctx, k),
  3979. };
  3980. }
  3981. };
  3982. template<typename T>
  3983. class GKV : public GKV_Base<T> {
  3984. GKV() = delete;
  3985. public:
  3986. static T get_kv(const gguf_context * ctx, const int k) {
  3987. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  3988. if (kt != GKV::gt) {
  3989. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  3990. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  3991. }
  3992. return GKV::getter(ctx, k);
  3993. }
  3994. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  3995. switch (ty) {
  3996. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  3997. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  3998. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  3999. case LLAMA_KV_OVERRIDE_TYPE_STR: return "str";
  4000. }
  4001. return "unknown";
  4002. }
  4003. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  4004. if (!ovrd) { return false; }
  4005. if (ovrd->tag == expected_type) {
  4006. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  4007. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  4008. switch (ovrd->tag) {
  4009. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  4010. LLAMA_LOG_INFO("%s\n", ovrd->val_bool ? "true" : "false");
  4011. } break;
  4012. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  4013. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->val_i64);
  4014. } break;
  4015. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  4016. LLAMA_LOG_INFO("%.6f\n", ovrd->val_f64);
  4017. } break;
  4018. case LLAMA_KV_OVERRIDE_TYPE_STR: {
  4019. LLAMA_LOG_INFO("%s\n", ovrd->val_str);
  4020. } break;
  4021. default:
  4022. // Shouldn't be possible to end up here, but just in case...
  4023. throw std::runtime_error(
  4024. format("Unsupported attempt to override %s type for metadata key %s\n",
  4025. override_type_to_str(ovrd->tag), ovrd->key));
  4026. }
  4027. return true;
  4028. }
  4029. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  4030. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  4031. return false;
  4032. }
  4033. template<typename OT>
  4034. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  4035. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  4036. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  4037. target = ovrd->val_bool;
  4038. return true;
  4039. }
  4040. return false;
  4041. }
  4042. template<typename OT>
  4043. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  4044. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  4045. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  4046. target = ovrd->val_i64;
  4047. return true;
  4048. }
  4049. return false;
  4050. }
  4051. template<typename OT>
  4052. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  4053. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  4054. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  4055. target = ovrd->val_f64;
  4056. return true;
  4057. }
  4058. return false;
  4059. }
  4060. template<typename OT>
  4061. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  4062. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  4063. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_STR, ovrd)) {
  4064. target = ovrd->val_str;
  4065. return true;
  4066. }
  4067. return false;
  4068. }
  4069. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  4070. if (try_override<T>(target, ovrd)) {
  4071. return true;
  4072. }
  4073. if (k < 0) { return false; }
  4074. target = get_kv(ctx, k);
  4075. return true;
  4076. }
  4077. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  4078. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  4079. }
  4080. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  4081. return set(ctx, key.c_str(), target, ovrd);
  4082. }
  4083. };
  4084. }
  4085. using llama_buf_map = std::unordered_map<uint32_t, ggml_backend_buffer_t>;
  4086. static size_t llama_model_max_nodes(const llama_model & model) {
  4087. return std::max<size_t>(8192, model.tensors_by_name.size()*5);
  4088. }
  4089. struct llama_model_loader {
  4090. int n_kv = 0;
  4091. int n_tensors = 0;
  4092. int n_created = 0;
  4093. int64_t n_elements = 0;
  4094. size_t n_bytes = 0;
  4095. bool use_mmap = false;
  4096. bool check_tensors;
  4097. llama_files files;
  4098. llama_ftype ftype;
  4099. llama_fver fver;
  4100. llama_mmaps mappings;
  4101. // Holds information on a model weight
  4102. struct llama_tensor_weight {
  4103. uint16_t idx; // source file index
  4104. size_t offs; // tensor data offset in the original file
  4105. ggml_tensor * tensor;
  4106. llama_tensor_weight(const llama_file * file, uint16_t idx, const char * name, const struct gguf_context * gguf_ctx, ggml_tensor * tensor) : idx(idx), tensor(tensor) {
  4107. const int tensor_idx = gguf_find_tensor(gguf_ctx, name);
  4108. offs = gguf_get_data_offset(gguf_ctx) + gguf_get_tensor_offset(gguf_ctx, tensor_idx);
  4109. if (offs + ggml_nbytes(tensor) < offs || offs + ggml_nbytes(tensor) > file->size) {
  4110. throw std::runtime_error(format("tensor '%s' data is not within the file bounds, model is corrupted or incomplete", name));
  4111. }
  4112. }
  4113. };
  4114. std::vector<llama_tensor_weight> weights;
  4115. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  4116. struct gguf_context * meta = NULL;
  4117. std::vector<ggml_context *> contexts;
  4118. std::string arch_name;
  4119. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  4120. llama_model_loader(const std::string & fname, bool use_mmap, bool check_tensors, const struct llama_model_kv_override * param_overrides_p) {
  4121. int trace = 0;
  4122. if (getenv("LLAMA_TRACE")) {
  4123. trace = atoi(getenv("LLAMA_TRACE"));
  4124. }
  4125. if (param_overrides_p != nullptr) {
  4126. for (const struct llama_model_kv_override * p = param_overrides_p; p->key[0] != 0; p++) {
  4127. kv_overrides.insert({std::string(p->key), *p});
  4128. }
  4129. }
  4130. struct ggml_context * ctx = NULL;
  4131. struct gguf_init_params params = {
  4132. /*.no_alloc = */ true,
  4133. /*.ctx = */ &ctx,
  4134. };
  4135. meta = gguf_init_from_file(fname.c_str(), params);
  4136. if (!meta) {
  4137. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  4138. }
  4139. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  4140. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  4141. files.emplace_back(new llama_file(fname.c_str(), "rb"));
  4142. contexts.emplace_back(ctx);
  4143. // Save tensors data offset of the main file.
  4144. // For subsidiary files, `meta` tensor data offset must not be used,
  4145. // so we build a unified tensors index for weights.
  4146. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  4147. weights.emplace_back(files.back().get(), 0, cur->name, meta, cur);
  4148. }
  4149. uint16_t n_split = 0;
  4150. get_key(llm_kv(LLM_KV_SPLIT_COUNT), n_split, false);
  4151. // Load additional GGML contexts
  4152. if (n_split > 1) {
  4153. uint16_t idx = 0;
  4154. get_key(llm_kv(LLM_KV_SPLIT_NO), idx);
  4155. if (idx != 0) {
  4156. throw std::runtime_error(format("illegal split file: %d, model must be loaded with the first split", idx));
  4157. }
  4158. char split_prefix[PATH_MAX] = {0};
  4159. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), fname.c_str(), idx, n_split)) {
  4160. throw std::runtime_error(format("invalid split file: %s", fname.c_str()));
  4161. }
  4162. if (trace > 0) {
  4163. LLAMA_LOG_INFO("%s: loading additional %d GGUFs\n", __func__, n_split);
  4164. }
  4165. char split_path[PATH_MAX] = {0};
  4166. for (idx = 1; idx < n_split; idx++) {
  4167. llama_split_path(split_path, sizeof(split_path), split_prefix, idx, n_split);
  4168. struct gguf_init_params split_params = {
  4169. /*.no_alloc = */ true,
  4170. /*.ctx = */ &ctx,
  4171. };
  4172. struct gguf_context * ctx_gguf = gguf_init_from_file(split_path, split_params);
  4173. if (!ctx_gguf) {
  4174. throw std::runtime_error(format("%s: failed to load GGUF split from %s\n", __func__, split_path));
  4175. }
  4176. files.emplace_back(new llama_file(split_path, "rb"));
  4177. contexts.emplace_back(ctx);
  4178. // Save tensors data offset info of the shard.
  4179. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  4180. weights.emplace_back(files.back().get(), idx, cur->name, ctx_gguf, cur);
  4181. }
  4182. gguf_free(ctx_gguf);
  4183. }
  4184. get_key(llm_kv(LLM_KV_SPLIT_TENSORS_COUNT), n_tensors);
  4185. // sanity check
  4186. {
  4187. const int n_tensors_loaded = (int) weights.size();
  4188. if (n_tensors != n_tensors_loaded) {
  4189. throw std::runtime_error(format("corrupted model: %d tensors expected but %d found", n_tensors, n_tensors_loaded));
  4190. }
  4191. }
  4192. LLAMA_LOG_INFO("%s: additional %d GGUFs metadata loaded.\n", __func__, n_split - 1);
  4193. }
  4194. n_kv = gguf_get_n_kv(meta);
  4195. n_tensors = weights.size();
  4196. fver = (enum llama_fver) gguf_get_version(meta);
  4197. std::set<std::string> tensor_names;
  4198. for (auto & w : weights) {
  4199. n_elements += ggml_nelements(w.tensor);
  4200. n_bytes += ggml_nbytes(w.tensor);
  4201. // make sure there is no duplicated tensor names
  4202. const std::string name(w.tensor->name);
  4203. auto found = tensor_names.find(name);
  4204. if (found != tensor_names.end()) {
  4205. throw std::runtime_error(format("invalid model: tensor '%s' is duplicated", w.tensor->name));
  4206. }
  4207. tensor_names.insert(name);
  4208. }
  4209. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  4210. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  4211. // determine file type based on the number of tensors for each quantization and print meta data
  4212. // TODO: make optional
  4213. {
  4214. std::map<enum ggml_type, uint32_t> n_type;
  4215. uint32_t n_type_max = 0;
  4216. enum ggml_type type_max = GGML_TYPE_F32;
  4217. for (int i = 0; i < n_tensors; i++) {
  4218. const ggml_tensor * tensor = weights.at(i).tensor;
  4219. enum ggml_type type = tensor->type;
  4220. n_type[type]++;
  4221. if (n_type_max < n_type[type]) {
  4222. n_type_max = n_type[type];
  4223. type_max = type;
  4224. }
  4225. if (trace > 0) {
  4226. const uint16_t sid = weights.at(i).idx;
  4227. LLAMA_LOG_INFO("%s: - tensor %4d, split %2d: %32s %-8s [ %s ]\n", __func__, i, sid, ggml_get_name(tensor), ggml_type_name(type), llama_format_tensor_shape(tensor).c_str());
  4228. }
  4229. }
  4230. switch (type_max) {
  4231. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  4232. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  4233. case GGML_TYPE_BF16: ftype = LLAMA_FTYPE_MOSTLY_BF16; break;
  4234. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  4235. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  4236. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  4237. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  4238. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  4239. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  4240. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  4241. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  4242. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  4243. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  4244. case GGML_TYPE_TQ1_0: ftype = LLAMA_FTYPE_MOSTLY_TQ1_0; break;
  4245. case GGML_TYPE_TQ2_0: ftype = LLAMA_FTYPE_MOSTLY_TQ2_0; break;
  4246. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  4247. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  4248. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  4249. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  4250. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  4251. case GGML_TYPE_IQ1_M: ftype = LLAMA_FTYPE_MOSTLY_IQ1_M; break;
  4252. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  4253. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  4254. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  4255. case GGML_TYPE_Q4_0_4_4: ftype = LLAMA_FTYPE_MOSTLY_Q4_0_4_4; break;
  4256. case GGML_TYPE_Q4_0_4_8: ftype = LLAMA_FTYPE_MOSTLY_Q4_0_4_8; break;
  4257. case GGML_TYPE_Q4_0_8_8: ftype = LLAMA_FTYPE_MOSTLY_Q4_0_8_8; break;
  4258. default:
  4259. {
  4260. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  4261. ftype = LLAMA_FTYPE_ALL_F32;
  4262. } break;
  4263. }
  4264. // this is a way to mark that we have "guessed" the file type
  4265. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  4266. {
  4267. const int kid = gguf_find_key(meta, "general.file_type"); // TODO: use LLM_KV
  4268. if (kid >= 0) {
  4269. ftype = (llama_ftype) gguf_get_val_u32(meta, kid);
  4270. }
  4271. }
  4272. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  4273. for (int i = 0; i < n_kv; i++) {
  4274. const char * name = gguf_get_key(meta, i);
  4275. const enum gguf_type type = gguf_get_kv_type(meta, i);
  4276. const std::string type_name =
  4277. type == GGUF_TYPE_ARRAY
  4278. ? format("%s[%s,%d]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(meta, i)), gguf_get_arr_n(meta, i))
  4279. : gguf_type_name(type);
  4280. std::string value = gguf_kv_to_str(meta, i);
  4281. const size_t MAX_VALUE_LEN = 40;
  4282. if (value.size() > MAX_VALUE_LEN) {
  4283. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  4284. }
  4285. replace_all(value, "\n", "\\n");
  4286. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  4287. }
  4288. // print type counts
  4289. for (auto & kv : n_type) {
  4290. if (kv.second == 0) {
  4291. continue;
  4292. }
  4293. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  4294. }
  4295. }
  4296. if (!llama_mmap::SUPPORTED) {
  4297. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  4298. use_mmap = false;
  4299. }
  4300. this->use_mmap = use_mmap;
  4301. this->check_tensors = check_tensors;
  4302. }
  4303. ~llama_model_loader() {
  4304. if (meta) {
  4305. gguf_free(meta);
  4306. }
  4307. for (auto * ctx : contexts) {
  4308. ggml_free(ctx);
  4309. }
  4310. }
  4311. template<typename T>
  4312. typename std::enable_if<std::is_integral<T>::value, bool>::type
  4313. get_arr_n(const std::string & key, T & result, const bool required = true) {
  4314. const int kid = gguf_find_key(meta, key.c_str());
  4315. if (kid < 0) {
  4316. if (required) {
  4317. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  4318. }
  4319. return false;
  4320. }
  4321. struct GGUFMeta::ArrayInfo arr_info =
  4322. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  4323. result = arr_info.length;
  4324. return true;
  4325. }
  4326. template<typename T>
  4327. typename std::enable_if<std::is_integral<T>::value, bool>::type
  4328. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  4329. return get_arr_n(llm_kv(kid), result, required);
  4330. }
  4331. template<typename T>
  4332. bool get_arr(const std::string & key, std::vector<T> & result, const bool required = true) {
  4333. const int kid = gguf_find_key(meta, key.c_str());
  4334. if (kid < 0 || gguf_get_kv_type(meta, kid) != GGUF_TYPE_ARRAY) {
  4335. if (required) {
  4336. throw std::runtime_error(format("array 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, kid);
  4342. switch (arr_info.gt) {
  4343. case GGUF_TYPE_FLOAT32: GGML_ASSERT((std::is_same<T, float>::value)); break;
  4344. case GGUF_TYPE_INT32: GGML_ASSERT(
  4345. (std::is_same<T, int32_t>::value) ||
  4346. (std::is_same<T, uint32_t>::value)); break;
  4347. default:
  4348. throw std::runtime_error(format("%s is not a float32, int32 array", key.c_str()));
  4349. }
  4350. result.resize(arr_info.length);
  4351. result.assign((const T*)arr_info.data, (const T *)arr_info.data + arr_info.length);
  4352. return true;
  4353. }
  4354. template<typename T, size_t N_MAX>
  4355. bool get_arr(const std::string & key, std::array<T, N_MAX> & result, const bool required = true) {
  4356. const int kid = gguf_find_key(meta, key.c_str());
  4357. if (kid < 0 || gguf_get_kv_type(meta, kid) != GGUF_TYPE_ARRAY) {
  4358. if (required) {
  4359. throw std::runtime_error(format("array key not found in model: %s", key.c_str()));
  4360. }
  4361. return false;
  4362. }
  4363. struct GGUFMeta::ArrayInfo arr_info =
  4364. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  4365. switch (arr_info.gt) {
  4366. case GGUF_TYPE_FLOAT32: GGML_ASSERT((std::is_same<T, float>::value)); break;
  4367. case GGUF_TYPE_INT32: GGML_ASSERT(
  4368. (std::is_same<T, int32_t>::value) ||
  4369. (std::is_same<T, uint32_t>::value)); break;
  4370. default:
  4371. throw std::runtime_error(format("%s is not a float32, int32 array", key.c_str()));
  4372. }
  4373. if (arr_info.length > N_MAX) {
  4374. 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));
  4375. }
  4376. std::copy((const T*)arr_info.data, (const T *)arr_info.data + arr_info.length, result.begin());
  4377. return true;
  4378. }
  4379. template<typename T>
  4380. bool get_arr(const enum llm_kv kid, T & result, const bool required = true) {
  4381. return get_arr(llm_kv(kid), result, required);
  4382. }
  4383. template<typename T>
  4384. bool get_key(const std::string & key, T & result, const bool required = true) {
  4385. auto it = kv_overrides.find(key);
  4386. const struct llama_model_kv_override * override =
  4387. it != kv_overrides.end() ? &it->second : nullptr;
  4388. const bool found = GGUFMeta::GKV<T>::set(meta, key, result, override);
  4389. if (required && !found) {
  4390. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  4391. }
  4392. return found;
  4393. }
  4394. template<typename T>
  4395. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  4396. return get_key(llm_kv(kid), result, required);
  4397. }
  4398. // get array of n <= N_MAX elements, or a single element repeated n times
  4399. template<typename T, size_t N_MAX>
  4400. bool get_key_or_arr(const std::string & key, std::array<T, N_MAX> & result, uint32_t n, const bool required = true) {
  4401. const int kid = gguf_find_key(meta, key.c_str());
  4402. if (kid < 0) {
  4403. if (required) {
  4404. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  4405. }
  4406. return false;
  4407. }
  4408. if (n > N_MAX) {
  4409. throw std::runtime_error(format("n > N_MAX: %u > %u for key %s", (uint32_t) n, (uint32_t) N_MAX, key.c_str()));
  4410. }
  4411. if (gguf_get_kv_type(meta, kid) == GGUF_TYPE_ARRAY) {
  4412. struct GGUFMeta::ArrayInfo arr_info =
  4413. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  4414. if (n != arr_info.length) {
  4415. throw std::runtime_error(format("key %s has wrong array length; expected %u, got %u", key.c_str(), n, (uint32_t) arr_info.length));
  4416. }
  4417. return get_arr(key, result, required);
  4418. } else {
  4419. T value;
  4420. bool ok = get_key(key, value, required);
  4421. if (!ok) {
  4422. return false;
  4423. }
  4424. for (uint32_t i = 0; i < n; i++) {
  4425. result[i] = value;
  4426. }
  4427. return true;
  4428. }
  4429. }
  4430. template<typename T>
  4431. bool get_key_or_arr(const enum llm_kv kid, T & result, uint32_t n, const bool required = true) {
  4432. return get_key_or_arr(llm_kv(kid), result, n, required);
  4433. }
  4434. std::string get_arch_name() const {
  4435. return arch_name;
  4436. }
  4437. enum llm_arch get_arch() const {
  4438. return llm_kv.arch;
  4439. }
  4440. const char * get_tensor_name(int i) const {
  4441. return weights.at(i).tensor->name;
  4442. }
  4443. const llama_tensor_weight * get_weight(const char * name) const {
  4444. for (const auto & weight : weights) {
  4445. if (strcmp(name, weight.tensor->name) == 0) {
  4446. return &weight;
  4447. }
  4448. }
  4449. return nullptr;
  4450. }
  4451. const llama_tensor_weight * get_weight(int i) const {
  4452. return get_weight(get_tensor_name(i));
  4453. }
  4454. const llama_tensor_weight & require_weight(const char * name) const {
  4455. const llama_tensor_weight * weight = get_weight(name);
  4456. if (!weight) {
  4457. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  4458. }
  4459. return *weight;
  4460. }
  4461. struct ggml_tensor * get_tensor_meta(const char * name) const {
  4462. const auto * weight = get_weight(name);
  4463. if (!weight) {
  4464. return nullptr;
  4465. }
  4466. return weight->tensor;
  4467. }
  4468. struct ggml_tensor * require_tensor_meta(const char * name) const {
  4469. struct ggml_tensor * tensor = get_tensor_meta(name);
  4470. if (!tensor) {
  4471. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  4472. }
  4473. return tensor;
  4474. }
  4475. struct ggml_tensor * get_tensor_meta(int i) const {
  4476. return get_tensor_meta(get_tensor_name(i));
  4477. }
  4478. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, const struct ggml_tensor * cur, bool duplicated) {
  4479. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, cur);
  4480. ggml_set_name(tensor, ggml_get_name(cur));
  4481. if (duplicated) {
  4482. size_data += ggml_nbytes(cur);
  4483. } else {
  4484. n_created++;
  4485. }
  4486. return tensor;
  4487. }
  4488. const struct ggml_tensor * check_tensor_dims(const std::string & name, const std::vector<int64_t> & ne, bool required) const {
  4489. const struct ggml_tensor * cur = get_tensor_meta(name.c_str());
  4490. if (cur == NULL) {
  4491. if (!required) {
  4492. return NULL;
  4493. }
  4494. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  4495. }
  4496. {
  4497. bool is_ok = true;
  4498. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  4499. if ((i < ne.size() && ne[i] != cur->ne[i]) || (i >= ne.size() && cur->ne[i] != 1)) {
  4500. is_ok = false;
  4501. break;
  4502. }
  4503. }
  4504. if (!is_ok) {
  4505. throw std::runtime_error(
  4506. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  4507. __func__, name.c_str(),
  4508. llama_format_tensor_shape(ne).c_str(),
  4509. llama_format_tensor_shape(cur).c_str()));
  4510. }
  4511. }
  4512. return cur;
  4513. }
  4514. static const int TENSOR_NOT_REQUIRED = 1;
  4515. static const int TENSOR_DUPLICATED = 2;
  4516. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, int flags = 0) {
  4517. const struct ggml_tensor * cur = check_tensor_dims(name, ne, !(flags & TENSOR_NOT_REQUIRED));
  4518. if (cur == NULL) {
  4519. return NULL;
  4520. }
  4521. return create_tensor_for(ctx, cur, flags & TENSOR_DUPLICATED);
  4522. }
  4523. struct ggml_tensor * create_tensor_as_view(struct ggml_context * ctx, struct ggml_tensor * base, const std::string & name, const std::vector<int64_t> & ne, size_t offset, bool required = true) {
  4524. const struct ggml_tensor * cur = check_tensor_dims(name, ne, required);
  4525. if (cur == NULL) {
  4526. return NULL;
  4527. }
  4528. if (cur->type != base->type) {
  4529. 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)));
  4530. }
  4531. std::array<int64_t, GGML_MAX_DIMS> dims;
  4532. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  4533. dims[i] = i < ne.size() ? ne[i] : 1;
  4534. }
  4535. struct ggml_tensor * tensor = ggml_view_4d(ctx, base,
  4536. dims[0], dims[1], dims[2], dims[3],
  4537. cur->nb[1], cur->nb[2], cur->nb[3],
  4538. offset);
  4539. ggml_set_name(tensor, name.c_str());
  4540. n_created++;
  4541. return tensor;
  4542. }
  4543. void done_getting_tensors() const {
  4544. if (n_created != n_tensors) {
  4545. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  4546. }
  4547. }
  4548. void init_mappings(bool prefetch = true, llama_mlocks * mlock_mmaps = nullptr) {
  4549. if (use_mmap) {
  4550. mappings.reserve(files.size());
  4551. mmaps_used.reserve(files.size());
  4552. for (const auto & file : files) {
  4553. std::unique_ptr<llama_mmap> mapping(new llama_mmap(file.get(), prefetch ? -1 : 0, ggml_is_numa()));
  4554. mmaps_used.emplace_back(mapping->size, 0);
  4555. if (mlock_mmaps) {
  4556. std::unique_ptr<llama_mlock> mlock_mmap(new llama_mlock());
  4557. mlock_mmap->init(mapping->addr);
  4558. mlock_mmaps->emplace_back(std::move(mlock_mmap));
  4559. }
  4560. mappings.emplace_back(std::move(mapping));
  4561. }
  4562. }
  4563. // compute the total size of all tensors for progress reporting
  4564. for (auto & w : weights) {
  4565. size_data += ggml_nbytes(w.tensor);
  4566. }
  4567. }
  4568. void get_mapping_range(size_t * first, size_t * last, void ** addr, int idx, ggml_context * ctx) const {
  4569. GGML_ASSERT(!mappings.empty());
  4570. const auto & mapping = mappings.at(idx);
  4571. *first = mapping->size;
  4572. *last = 0;
  4573. *addr = mapping->addr;
  4574. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  4575. try {
  4576. const auto * weight = get_weight(ggml_get_name(tensor));
  4577. if (!weight) {
  4578. continue;
  4579. }
  4580. if (weight->idx != idx) {
  4581. continue;
  4582. }
  4583. *first = std::min(*first, weight->offs);
  4584. *last = std::max(*last, weight->offs + ggml_nbytes(tensor));
  4585. } catch(...) {
  4586. // the tensor is not in the model
  4587. }
  4588. }
  4589. }
  4590. // for backwards compatibility, does not support ggml-backend
  4591. void load_data_for(struct ggml_tensor * cur) const {
  4592. const auto & w = require_weight(ggml_get_name(cur));
  4593. if (use_mmap) {
  4594. const auto & mapping = mappings.at(w.idx);
  4595. if (cur->data == nullptr) {
  4596. cur->data = (uint8_t *)mapping->addr + w.offs;
  4597. } else {
  4598. memcpy(cur->data, (uint8_t *)mapping->addr + w.offs, ggml_nbytes(cur));
  4599. }
  4600. } else {
  4601. GGML_ASSERT(cur->data != nullptr);
  4602. GGML_ASSERT(w.idx < files.size());
  4603. const auto & file = files.at(w.idx);
  4604. file->seek(w.offs, SEEK_SET);
  4605. file->read_raw(cur->data, ggml_nbytes(cur));
  4606. }
  4607. if (check_tensors && !ggml_validate_row_data(cur->type, cur->data, ggml_nbytes(cur))) {
  4608. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  4609. }
  4610. }
  4611. size_t size_done = 0;
  4612. size_t size_data = 0;
  4613. std::vector<std::pair<size_t, size_t>> mmaps_used;
  4614. // Returns false if cancelled by progress_callback
  4615. bool load_all_data(
  4616. struct ggml_context * ctx,
  4617. llama_buf_map & bufs_mmap,
  4618. llama_mlocks * lmlocks,
  4619. llama_progress_callback progress_callback,
  4620. void * progress_callback_user_data) {
  4621. GGML_ASSERT(size_data != 0 && "call init_mappings() first");
  4622. std::vector<no_init<uint8_t>> read_buf;
  4623. std::vector<std::future<std::pair<ggml_tensor *, bool>>> validation_result;
  4624. #if defined(GGML_USE_CUDA)
  4625. // 4 staging buffers for async uploads, each sized 1MB seems to be a good default for single NVMe drives.
  4626. // NVMe raid configurations might require more / larger buffers.
  4627. constexpr size_t n_buffers = 4;
  4628. constexpr size_t buffer_size = 1 * 1024 * 1024; // 1MB
  4629. std::vector<ggml_backend_buffer_t> host_buffers;
  4630. std::vector<void*> host_ptrs;
  4631. std::vector<ggml_backend_event_t> events;
  4632. size_t buffer_idx = 0; // buffer to use for async loads
  4633. ggml_backend_t cuda_backend = nullptr;
  4634. if (!use_mmap && !check_tensors) {
  4635. // When not using mmaped io use async uploads from pinned memory to GPU memory.
  4636. // First determine if the CUDA backend is active, and if so, determine the device ID.
  4637. ggml_backend_buffer_t buf = bufs_mmap.count(0) ? bufs_mmap.at(0) : nullptr;
  4638. if (buf) {
  4639. ggml_backend_buffer_type_t buffer_type = ggml_backend_buffer_get_type(buf);
  4640. for (int i = 0; i < ggml_backend_cuda_get_device_count(); ++i) {
  4641. auto * cuda_buffer_type = ggml_backend_cuda_buffer_type(i);
  4642. if (buffer_type == cuda_buffer_type) {
  4643. cuda_backend = ggml_backend_cuda_init(i);
  4644. break;
  4645. }
  4646. }
  4647. }
  4648. // If the cuda backend is active create pinned memory buffers and events for synchronisation.
  4649. if (cuda_backend) {
  4650. for (size_t idx = 0; idx < n_buffers; ++idx) {
  4651. host_buffers.emplace_back(ggml_backend_buft_alloc_buffer(llama_default_buffer_type_cpu(true), buffer_size));
  4652. host_ptrs.emplace_back(ggml_backend_buffer_get_base(host_buffers[idx]));
  4653. events.emplace_back(ggml_backend_event_new(cuda_backend));
  4654. }
  4655. }
  4656. }
  4657. #endif
  4658. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  4659. const auto * weight = get_weight(ggml_get_name(cur));
  4660. if (weight == nullptr) {
  4661. // this can happen with split experts models
  4662. continue;
  4663. }
  4664. if (progress_callback) {
  4665. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  4666. return false;
  4667. }
  4668. }
  4669. size_t n_size = ggml_nbytes(cur);
  4670. if (use_mmap) {
  4671. const auto & mapping = mappings.at(weight->idx);
  4672. ggml_backend_buffer_t buf_mmap = nullptr;
  4673. if (bufs_mmap.count(weight->idx)) {
  4674. buf_mmap = bufs_mmap.at(weight->idx);
  4675. }
  4676. uint8_t * data = (uint8_t *) mapping->addr + weight->offs;
  4677. if (check_tensors) {
  4678. validation_result.emplace_back(std::async(std::launch::async, [cur, data, n_size] {
  4679. return std::make_pair(cur, ggml_validate_row_data(cur->type, data, n_size));
  4680. }));
  4681. }
  4682. GGML_ASSERT(buf_mmap || cur->data); // either we have a buffer to allocate the tensor in, or it is already allocated
  4683. if (buf_mmap && cur->data == nullptr) {
  4684. ggml_backend_tensor_alloc(buf_mmap, cur, data);
  4685. if (lmlocks) {
  4686. const auto & lmlock = lmlocks->at(weight->idx);
  4687. lmlock->grow_to(weight->offs + n_size);
  4688. }
  4689. auto & mmap_used = mmaps_used[weight->idx];
  4690. mmap_used.first = std::min(mmap_used.first, weight->offs);
  4691. mmap_used.second = std::max(mmap_used.second, weight->offs + n_size);
  4692. } else {
  4693. ggml_backend_tensor_set(cur, data, 0, n_size);
  4694. }
  4695. } else {
  4696. GGML_ASSERT(weight->idx < files.size());
  4697. const auto & file = files.at(weight->idx);
  4698. if (ggml_backend_buffer_is_host(cur->buffer)) {
  4699. file->seek(weight->offs, SEEK_SET);
  4700. file->read_raw(cur->data, n_size);
  4701. if (check_tensors) {
  4702. validation_result.emplace_back(std::async(std::launch::async, [cur, n_size] {
  4703. return std::make_pair(cur, ggml_validate_row_data(cur->type, cur->data, n_size));
  4704. }));
  4705. }
  4706. } else {
  4707. #if defined(GGML_USE_CUDA)
  4708. // If cuda_backend is valid load the tensor in chunks to pinned memory and upload the buffers asynchronously to the GPU.
  4709. if (cuda_backend) {
  4710. file->seek(weight->offs, SEEK_SET);
  4711. size_t bytes_read = 0;
  4712. while (bytes_read < n_size) {
  4713. size_t read_iteration = std::min<size_t>(buffer_size, n_size - bytes_read);
  4714. ggml_backend_event_synchronize(events[buffer_idx]);
  4715. file->read_raw(host_ptrs[buffer_idx], read_iteration);
  4716. ggml_backend_tensor_set_async(cuda_backend, cur, host_ptrs[buffer_idx], bytes_read, read_iteration);
  4717. ggml_backend_event_record(events[buffer_idx]);
  4718. bytes_read += read_iteration;
  4719. ++buffer_idx;
  4720. buffer_idx %= n_buffers;
  4721. }
  4722. }
  4723. else
  4724. #endif
  4725. {
  4726. read_buf.resize(n_size);
  4727. file->seek(weight->offs, SEEK_SET);
  4728. file->read_raw(read_buf.data(), n_size);
  4729. ggml_backend_tensor_set(cur, read_buf.data(), 0, n_size);
  4730. if (check_tensors && !ggml_validate_row_data(cur->type, read_buf.data(), n_size)) {
  4731. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  4732. }
  4733. }
  4734. }
  4735. }
  4736. size_done += n_size;
  4737. }
  4738. #if defined(GGML_USE_CUDA)
  4739. // free temporary resources used for async cuda uploads
  4740. if (cuda_backend) {
  4741. for (size_t idx = 0; idx < n_buffers;++idx) {
  4742. ggml_backend_event_synchronize(events[idx]);
  4743. ggml_backend_event_free(events[idx]);
  4744. ggml_backend_buffer_free(host_buffers[idx]);
  4745. }
  4746. ggml_backend_free(cuda_backend);
  4747. }
  4748. #endif
  4749. // check validation results
  4750. bool validation_failed = false;
  4751. for (auto & future : validation_result) {
  4752. auto result = future.get();
  4753. if (!result.second) {
  4754. LLAMA_LOG_ERROR("%s: tensor '%s' has invalid data\n", __func__, ggml_get_name(result.first));
  4755. validation_failed = true;
  4756. }
  4757. }
  4758. if (validation_failed) {
  4759. throw std::runtime_error("found tensors with invalid data");
  4760. }
  4761. // check if this is the last call and do final cleanup
  4762. if (size_done >= size_data) {
  4763. // unmap offloaded tensors and metadata
  4764. if (use_mmap) {
  4765. for (uint32_t idx = 0; idx < mappings.size(); idx++) {
  4766. const auto & mmap_used = mmaps_used.at(idx);
  4767. auto & mapping = mappings.at(idx);
  4768. mapping->unmap_fragment(0, mmap_used.first);
  4769. if (mmap_used.second != 0) {
  4770. mapping->unmap_fragment(mmap_used.second, mapping->size);
  4771. }
  4772. }
  4773. }
  4774. if (progress_callback) {
  4775. // Even though the model is done loading, we still honor
  4776. // cancellation since we need to free allocations.
  4777. return progress_callback(1.0f, progress_callback_user_data);
  4778. }
  4779. }
  4780. return true;
  4781. }
  4782. };
  4783. template<>
  4784. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  4785. uint32_t tmp;
  4786. const bool found = get_key(kid, tmp, required);
  4787. if (found) {
  4788. result = (enum llama_pooling_type) tmp;
  4789. } else {
  4790. result = LLAMA_POOLING_TYPE_UNSPECIFIED;
  4791. }
  4792. return found;
  4793. }
  4794. //
  4795. // load LLaMA models
  4796. //
  4797. static const char * llama_model_arch_name(llm_arch arch) {
  4798. auto it = LLM_ARCH_NAMES.find(arch);
  4799. if (it == LLM_ARCH_NAMES.end()) {
  4800. return "unknown";
  4801. }
  4802. return it->second;
  4803. }
  4804. static std::string llama_model_ftype_name(llama_ftype ftype) {
  4805. if (ftype & LLAMA_FTYPE_GUESSED) {
  4806. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  4807. }
  4808. switch (ftype) {
  4809. case LLAMA_FTYPE_ALL_F32: return "all F32";
  4810. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  4811. case LLAMA_FTYPE_MOSTLY_BF16: return "BF16";
  4812. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  4813. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  4814. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  4815. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  4816. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  4817. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  4818. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  4819. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  4820. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  4821. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  4822. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  4823. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  4824. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  4825. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  4826. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  4827. case LLAMA_FTYPE_MOSTLY_TQ1_0: return "TQ1_0 - 1.69 bpw ternary";
  4828. case LLAMA_FTYPE_MOSTLY_TQ2_0: return "TQ2_0 - 2.06 bpw ternary";
  4829. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: return "IQ2_XXS - 2.0625 bpw";
  4830. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  4831. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  4832. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  4833. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  4834. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: return "IQ3_XXS - 3.0625 bpw";
  4835. case LLAMA_FTYPE_MOSTLY_IQ1_S: return "IQ1_S - 1.5625 bpw";
  4836. case LLAMA_FTYPE_MOSTLY_IQ1_M: return "IQ1_M - 1.75 bpw";
  4837. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  4838. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  4839. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  4840. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  4841. case LLAMA_FTYPE_MOSTLY_Q4_0_4_4: return "Q4_0_4_4";
  4842. case LLAMA_FTYPE_MOSTLY_Q4_0_4_8: return "Q4_0_4_8";
  4843. case LLAMA_FTYPE_MOSTLY_Q4_0_8_8: return "Q4_0_8_8";
  4844. default: return "unknown, may not work";
  4845. }
  4846. }
  4847. static const char * llama_model_type_name(e_model type) {
  4848. switch (type) {
  4849. case MODEL_14M: return "14M";
  4850. case MODEL_17M: return "17M";
  4851. case MODEL_22M: return "22M";
  4852. case MODEL_33M: return "33M";
  4853. case MODEL_60M: return "60M";
  4854. case MODEL_70M: return "70M";
  4855. case MODEL_80M: return "80M";
  4856. case MODEL_109M: return "109M";
  4857. case MODEL_137M: return "137M";
  4858. case MODEL_160M: return "160M";
  4859. case MODEL_220M: return "220M";
  4860. case MODEL_250M: return "250M";
  4861. case MODEL_270M: return "270M";
  4862. case MODEL_335M: return "335M";
  4863. case MODEL_410M: return "410M";
  4864. case MODEL_450M: return "450M";
  4865. case MODEL_770M: return "770M";
  4866. case MODEL_780M: return "780M";
  4867. case MODEL_0_5B: return "0.5B";
  4868. case MODEL_1B: return "1B";
  4869. case MODEL_1_3B: return "1.3B";
  4870. case MODEL_1_4B: return "1.4B";
  4871. case MODEL_1_6B: return "1.6B";
  4872. case MODEL_2B: return "2B";
  4873. case MODEL_2_8B: return "2.8B";
  4874. case MODEL_3B: return "3B";
  4875. case MODEL_4B: return "4B";
  4876. case MODEL_6B: return "6B";
  4877. case MODEL_6_9B: return "6.9B";
  4878. case MODEL_7B: return "7B";
  4879. case MODEL_8B: return "8B";
  4880. case MODEL_9B: return "9B";
  4881. case MODEL_11B: return "11B";
  4882. case MODEL_12B: return "12B";
  4883. case MODEL_13B: return "13B";
  4884. case MODEL_14B: return "14B";
  4885. case MODEL_15B: return "15B";
  4886. case MODEL_16B: return "16B";
  4887. case MODEL_20B: return "20B";
  4888. case MODEL_30B: return "30B";
  4889. case MODEL_34B: return "34B";
  4890. case MODEL_35B: return "35B";
  4891. case MODEL_40B: return "40B";
  4892. case MODEL_65B: return "65B";
  4893. case MODEL_70B: return "70B";
  4894. case MODEL_236B: return "236B";
  4895. case MODEL_314B: return "314B";
  4896. case MODEL_SMALL: return "0.1B";
  4897. case MODEL_MEDIUM: return "0.4B";
  4898. case MODEL_LARGE: return "0.8B";
  4899. case MODEL_XL: return "1.5B";
  4900. case MODEL_A1_7B: return "A1.7B";
  4901. case MODEL_A2_7B: return "A2.7B";
  4902. case MODEL_8x7B: return "8x7B";
  4903. case MODEL_8x22B: return "8x22B";
  4904. case MODEL_16x12B: return "16x12B";
  4905. case MODEL_10B_128x3_66B: return "10B+128x3.66B";
  4906. case MODEL_57B_A14B: return "57B.A14B";
  4907. case MODEL_27B: return "27B";
  4908. default: return "?B";
  4909. }
  4910. }
  4911. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  4912. switch (type) {
  4913. case LLAMA_VOCAB_TYPE_NONE: return "no vocab";
  4914. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  4915. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  4916. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  4917. case LLAMA_VOCAB_TYPE_UGM: return "UGM";
  4918. case LLAMA_VOCAB_TYPE_RWKV: return "RWKV";
  4919. default: return "unknown";
  4920. }
  4921. }
  4922. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  4923. model.arch = ml.get_arch();
  4924. if (model.arch == LLM_ARCH_UNKNOWN) {
  4925. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  4926. }
  4927. }
  4928. static void llm_load_hparams(
  4929. llama_model_loader & ml,
  4930. llama_model & model) {
  4931. auto & hparams = model.hparams;
  4932. const gguf_context * ctx = ml.meta;
  4933. // get metadata as string
  4934. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  4935. enum gguf_type type = gguf_get_kv_type(ctx, i);
  4936. if (type == GGUF_TYPE_ARRAY) {
  4937. continue;
  4938. }
  4939. const char * name = gguf_get_key(ctx, i);
  4940. const std::string value = gguf_kv_to_str(ctx, i);
  4941. model.gguf_kv.emplace(name, value);
  4942. }
  4943. // get general kv
  4944. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  4945. // get hparams kv
  4946. ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab, false) || ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  4947. // everything past this point is not vocab-related
  4948. if (hparams.vocab_only) {
  4949. return;
  4950. }
  4951. ml.get_key(LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  4952. ml.get_key(LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  4953. ml.get_key(LLM_KV_BLOCK_COUNT, hparams.n_layer);
  4954. ml.get_key(LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  4955. ml.get_key(LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  4956. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  4957. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  4958. if (hparams.n_expert > 0) {
  4959. GGML_ASSERT(hparams.n_expert_used > 0);
  4960. } else {
  4961. GGML_ASSERT(hparams.n_expert_used == 0);
  4962. }
  4963. // zero-out the per-layer hparams
  4964. std::fill(hparams.n_head_arr.begin(), hparams.n_head_arr.end(), 0);
  4965. std::fill(hparams.n_head_kv_arr.begin(), hparams.n_head_kv_arr.end(), 0);
  4966. std::fill(hparams.n_ff_arr.begin(), hparams.n_ff_arr.end(), 0);
  4967. std::fill(hparams.cross_attn_layers.begin(), hparams.cross_attn_layers.end(), -1);
  4968. ml.get_key_or_arr(LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff_arr, hparams.n_layer);
  4969. ml.get_key_or_arr(LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head_arr, hparams.n_layer);
  4970. ml.get_arr(LLM_KV_ATTENTION_CROSS_ATTENTION_LAYERS, hparams.cross_attn_layers, false);
  4971. // n_head_kv is optional, default to n_head
  4972. hparams.n_head_kv_arr = hparams.n_head_arr;
  4973. ml.get_key_or_arr(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv_arr, hparams.n_layer, false);
  4974. bool rope_finetuned = false;
  4975. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  4976. hparams.rope_finetuned = rope_finetuned;
  4977. hparams.n_ctx_orig_yarn = hparams.n_ctx_train;
  4978. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_ctx_orig_yarn, false);
  4979. // rope_freq_base (optional)
  4980. hparams.rope_freq_base_train = 10000.0f;
  4981. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  4982. std::string rope_scaling("linear");
  4983. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  4984. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  4985. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  4986. // rope_freq_scale (inverse of the kv) is optional
  4987. float ropescale = 0.0f;
  4988. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  4989. // try the old key name
  4990. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  4991. }
  4992. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  4993. ml.get_key(LLM_KV_ROPE_SCALING_ATTN_FACTOR, hparams.rope_attn_factor, false);
  4994. // non-transformer models do not have attention heads
  4995. if (hparams.n_head() > 0) {
  4996. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  4997. // gpt-j n_rot = rotary_dim
  4998. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head();
  4999. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  5000. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head();
  5001. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  5002. // sanity check for n_rot (optional)
  5003. hparams.n_rot = hparams.n_embd_head_k;
  5004. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  5005. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_MLLAMA || model.arch == LLM_ARCH_FALCON) {
  5006. if (hparams.n_rot != hparams.n_embd_head_k) {
  5007. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd_head_k));
  5008. }
  5009. }
  5010. } else {
  5011. hparams.n_rot = 0;
  5012. hparams.n_embd_head_k = 0;
  5013. hparams.n_embd_head_v = 0;
  5014. }
  5015. // arch-specific KVs
  5016. switch (model.arch) {
  5017. case LLM_ARCH_LLAMA:
  5018. {
  5019. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5020. if (hparams.n_expert == 8) {
  5021. switch (hparams.n_layer) {
  5022. case 32: model.type = e_model::MODEL_8x7B; break;
  5023. case 56: model.type = e_model::MODEL_8x22B; break;
  5024. default: model.type = e_model::MODEL_UNKNOWN;
  5025. }
  5026. } else {
  5027. switch (hparams.n_layer) {
  5028. case 16: model.type = e_model::MODEL_1B; break; // Llama 3.2 1B
  5029. case 22: model.type = e_model::MODEL_1B; break;
  5030. case 26: model.type = e_model::MODEL_3B; break;
  5031. case 28: model.type = e_model::MODEL_3B; break; // Llama 3.2 3B
  5032. // granite uses a vocab with len 49152
  5033. 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;
  5034. case 36: model.type = e_model::MODEL_8B; break; // granite
  5035. case 40: model.type = e_model::MODEL_13B; break;
  5036. case 48: model.type = e_model::MODEL_34B; break;
  5037. case 60: model.type = e_model::MODEL_30B; break;
  5038. case 80: model.type = hparams.n_head() == hparams.n_head_kv() ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  5039. default: model.type = e_model::MODEL_UNKNOWN;
  5040. }
  5041. }
  5042. } break;
  5043. case LLM_ARCH_MLLAMA:
  5044. {
  5045. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5046. switch (hparams.n_layer) {
  5047. case 40: model.type = e_model::MODEL_11B; break;
  5048. case 100: model.type = e_model::MODEL_90B; break;
  5049. default: model.type = e_model::MODEL_UNKNOWN;
  5050. }
  5051. } break;
  5052. case LLM_ARCH_MINICPM:
  5053. {
  5054. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5055. switch (hparams.n_layer) {
  5056. case 40: model.type = e_model::MODEL_2B; break;
  5057. default: model.type = e_model::MODEL_UNKNOWN;
  5058. }
  5059. } break;
  5060. case LLM_ARCH_MINICPM3:
  5061. {
  5062. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5063. ml.get_key(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q);
  5064. ml.get_key(LLM_KV_ATTENTION_KV_LORA_RANK, hparams.n_lora_kv);
  5065. switch (hparams.n_layer) {
  5066. case 62: model.type = e_model::MODEL_4B; break;
  5067. default: model.type = e_model::MODEL_UNKNOWN;
  5068. }
  5069. } break;
  5070. case LLM_ARCH_GROK:
  5071. {
  5072. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5073. switch (hparams.n_layer) {
  5074. case 64: model.type = e_model::MODEL_314B; break;
  5075. default: model.type = e_model::MODEL_UNKNOWN;
  5076. }
  5077. } break;
  5078. case LLM_ARCH_FALCON:
  5079. {
  5080. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5081. switch (hparams.n_layer) {
  5082. case 32: model.type = e_model::MODEL_7B; break;
  5083. case 60: model.type = e_model::MODEL_40B; break;
  5084. default: model.type = e_model::MODEL_UNKNOWN;
  5085. }
  5086. } break;
  5087. case LLM_ARCH_BAICHUAN:
  5088. {
  5089. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5090. switch (hparams.n_layer) {
  5091. case 32: model.type = e_model::MODEL_7B; break;
  5092. case 40: model.type = e_model::MODEL_13B; break;
  5093. default: model.type = e_model::MODEL_UNKNOWN;
  5094. }
  5095. if (model.type == e_model::MODEL_13B) {
  5096. // TODO: become GGUF KV parameter
  5097. hparams.f_max_alibi_bias = 8.0f;
  5098. }
  5099. } break;
  5100. case LLM_ARCH_STARCODER:
  5101. {
  5102. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5103. switch (hparams.n_layer) {
  5104. case 24: model.type = e_model::MODEL_1B; break;
  5105. case 36: model.type = e_model::MODEL_3B; break;
  5106. case 42: model.type = e_model::MODEL_7B; break;
  5107. case 40: model.type = e_model::MODEL_15B; break;
  5108. default: model.type = e_model::MODEL_UNKNOWN;
  5109. }
  5110. } break;
  5111. case LLM_ARCH_REFACT:
  5112. {
  5113. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5114. switch (hparams.n_layer) {
  5115. case 32: model.type = e_model::MODEL_1B; break;
  5116. default: model.type = e_model::MODEL_UNKNOWN;
  5117. }
  5118. // TODO: become GGUF KV parameter
  5119. hparams.f_max_alibi_bias = 8.0f;
  5120. } break;
  5121. case LLM_ARCH_BERT:
  5122. {
  5123. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5124. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  5125. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  5126. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  5127. switch (hparams.n_layer) {
  5128. case 3:
  5129. model.type = e_model::MODEL_17M; break; // bge-micro
  5130. case 6:
  5131. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  5132. case 12:
  5133. switch (hparams.n_embd) {
  5134. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  5135. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  5136. } break;
  5137. case 24:
  5138. model.type = e_model::MODEL_335M; break; // bge-large
  5139. }
  5140. } break;
  5141. case LLM_ARCH_JINA_BERT_V2:
  5142. {
  5143. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5144. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  5145. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  5146. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  5147. hparams.f_max_alibi_bias = 8.0f;
  5148. switch (hparams.n_layer) {
  5149. case 4: model.type = e_model::MODEL_33M; break; // jina-embeddings-small
  5150. case 12: model.type = e_model::MODEL_137M; break; // jina-embeddings-base
  5151. }
  5152. } break;
  5153. case LLM_ARCH_NOMIC_BERT:
  5154. {
  5155. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5156. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  5157. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  5158. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  5159. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  5160. model.type = e_model::MODEL_137M;
  5161. }
  5162. } break;
  5163. case LLM_ARCH_BLOOM:
  5164. {
  5165. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5166. switch (hparams.n_layer) {
  5167. case 24: model.type = e_model::MODEL_1B; break;
  5168. case 30:
  5169. switch (hparams.n_embd) {
  5170. case 2560: model.type = e_model::MODEL_3B; break;
  5171. case 4096: model.type = e_model::MODEL_7B; break;
  5172. } break;
  5173. }
  5174. // TODO: become GGUF KV parameter
  5175. hparams.f_max_alibi_bias = 8.0f;
  5176. } break;
  5177. case LLM_ARCH_MPT:
  5178. {
  5179. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5180. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  5181. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  5182. switch (hparams.n_layer) {
  5183. case 32: model.type = e_model::MODEL_7B; break;
  5184. case 48: model.type = e_model::MODEL_30B; break;
  5185. default: model.type = e_model::MODEL_UNKNOWN;
  5186. }
  5187. } break;
  5188. case LLM_ARCH_STABLELM:
  5189. {
  5190. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5191. switch (hparams.n_layer) {
  5192. case 24: model.type = e_model::MODEL_1B; break;
  5193. case 32: model.type = e_model::MODEL_3B; break;
  5194. case 40: model.type = e_model::MODEL_12B; break;
  5195. default: model.type = e_model::MODEL_UNKNOWN;
  5196. }
  5197. } break;
  5198. case LLM_ARCH_QWEN:
  5199. {
  5200. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5201. switch (hparams.n_layer) {
  5202. case 32: model.type = e_model::MODEL_7B; break;
  5203. case 40: model.type = e_model::MODEL_13B; break;
  5204. default: model.type = e_model::MODEL_UNKNOWN;
  5205. }
  5206. } break;
  5207. case LLM_ARCH_QWEN2:
  5208. {
  5209. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5210. switch (hparams.n_layer) {
  5211. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  5212. case 32: model.type = e_model::MODEL_7B; break;
  5213. case 40: model.type = hparams.n_head() == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  5214. case 80: model.type = e_model::MODEL_70B; break;
  5215. default: model.type = e_model::MODEL_UNKNOWN;
  5216. }
  5217. } break;
  5218. case LLM_ARCH_QWEN2MOE:
  5219. {
  5220. ml.get_key(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp, false);
  5221. ml.get_key(LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, hparams.n_ff_shexp, false);
  5222. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5223. switch (hparams.n_layer) {
  5224. case 24: model.type = e_model::MODEL_A2_7B; break;
  5225. case 28: model.type = e_model::MODEL_57B_A14B; break;
  5226. default: model.type = e_model::MODEL_UNKNOWN;
  5227. }
  5228. } break;
  5229. case LLM_ARCH_PHI2:
  5230. {
  5231. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5232. switch (hparams.n_layer) {
  5233. case 24: model.type = e_model::MODEL_1B; break;
  5234. case 32: model.type = e_model::MODEL_3B; break;
  5235. default: model.type = e_model::MODEL_UNKNOWN;
  5236. }
  5237. } break;
  5238. case LLM_ARCH_PHI3:
  5239. {
  5240. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5241. switch (hparams.n_layer) {
  5242. case 24: model.type = e_model::MODEL_1B; break;
  5243. case 32: model.type = e_model::MODEL_3B; break;
  5244. case 40: model.type = e_model::MODEL_14B; break;
  5245. default: model.type = e_model::MODEL_UNKNOWN;
  5246. }
  5247. // for backward compatibility ; see: https://github.com/ggerganov/llama.cpp/pull/8931
  5248. if ((hparams.n_layer == 32 || hparams.n_layer == 40) && hparams.n_ctx_train == 4096) {
  5249. // default value for Phi-3-mini-4k-instruct and Phi-3-medium-4k-instruct
  5250. hparams.n_swa = 2047;
  5251. } else if (hparams.n_layer == 32 && hparams.n_head_kv(0) == 32 && hparams.n_ctx_train == 131072) {
  5252. // default value for Phi-3-mini-128k-instruct
  5253. hparams.n_swa = 262144;
  5254. } else if (hparams.n_layer == 40 && hparams.n_ctx_train == 131072) {
  5255. // default value for Phi-3-medium-128k-instruct
  5256. hparams.n_swa = 131072;
  5257. }
  5258. bool found_swa = ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa, false);
  5259. if (!found_swa && hparams.n_swa == 0) {
  5260. throw std::runtime_error("invalid value for sliding_window");
  5261. }
  5262. } break;
  5263. case LLM_ARCH_PLAMO:
  5264. {
  5265. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5266. switch (hparams.n_layer) {
  5267. case 40: model.type = e_model::MODEL_13B; break;
  5268. default: model.type = e_model::MODEL_UNKNOWN;
  5269. }
  5270. } break;
  5271. case LLM_ARCH_GPT2:
  5272. {
  5273. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5274. switch (hparams.n_layer) {
  5275. case 12: model.type = e_model::MODEL_SMALL; break;
  5276. case 24: model.type = e_model::MODEL_MEDIUM; break;
  5277. case 36: model.type = e_model::MODEL_LARGE; break;
  5278. case 48: model.type = e_model::MODEL_XL; break;
  5279. default: model.type = e_model::MODEL_UNKNOWN;
  5280. }
  5281. } break;
  5282. case LLM_ARCH_CODESHELL:
  5283. {
  5284. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5285. switch (hparams.n_layer) {
  5286. case 42: model.type = e_model::MODEL_7B; break;
  5287. default: model.type = e_model::MODEL_UNKNOWN;
  5288. }
  5289. } break;
  5290. case LLM_ARCH_ORION:
  5291. {
  5292. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5293. switch (hparams.n_layer) {
  5294. case 40: model.type = e_model::MODEL_14B; break;
  5295. default: model.type = e_model::MODEL_UNKNOWN;
  5296. }
  5297. } break;
  5298. case LLM_ARCH_INTERNLM2:
  5299. {
  5300. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5301. switch (hparams.n_layer) {
  5302. case 32: model.type = e_model::MODEL_7B; break;
  5303. case 48: model.type = e_model::MODEL_20B; break;
  5304. default: model.type = e_model::MODEL_UNKNOWN;
  5305. }
  5306. } break;
  5307. case LLM_ARCH_GEMMA:
  5308. {
  5309. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5310. switch (hparams.n_layer) {
  5311. case 18: model.type = e_model::MODEL_2B; break;
  5312. case 28: model.type = e_model::MODEL_7B; break;
  5313. default: model.type = e_model::MODEL_UNKNOWN;
  5314. }
  5315. } break;
  5316. case LLM_ARCH_GEMMA2:
  5317. {
  5318. hparams.n_swa = 4096; // default value of gemma 2
  5319. ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa, false);
  5320. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5321. ml.get_key(LLM_KV_ATTN_LOGIT_SOFTCAPPING, hparams.f_attn_logit_softcapping, false);
  5322. ml.get_key(LLM_KV_FINAL_LOGIT_SOFTCAPPING, hparams.f_final_logit_softcapping, false);
  5323. hparams.attn_soft_cap = true;
  5324. switch (hparams.n_layer) {
  5325. case 26: model.type = e_model::MODEL_2B; break;
  5326. case 42: model.type = e_model::MODEL_9B; break;
  5327. case 46: model.type = e_model::MODEL_27B; break;
  5328. default: model.type = e_model::MODEL_UNKNOWN;
  5329. }
  5330. } break;
  5331. case LLM_ARCH_STARCODER2:
  5332. {
  5333. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5334. switch (hparams.n_layer) {
  5335. case 30: model.type = e_model::MODEL_3B; break;
  5336. case 32: model.type = e_model::MODEL_7B; break;
  5337. case 40: model.type = e_model::MODEL_15B; break;
  5338. case 52: model.type = e_model::MODEL_20B; break; // granite
  5339. case 88: model.type = e_model::MODEL_34B; break; // granite
  5340. default: model.type = e_model::MODEL_UNKNOWN;
  5341. }
  5342. } break;
  5343. case LLM_ARCH_MAMBA:
  5344. {
  5345. ml.get_key(LLM_KV_SSM_CONV_KERNEL, hparams.ssm_d_conv);
  5346. ml.get_key(LLM_KV_SSM_INNER_SIZE, hparams.ssm_d_inner);
  5347. ml.get_key(LLM_KV_SSM_STATE_SIZE, hparams.ssm_d_state);
  5348. ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
  5349. ml.get_key(LLM_KV_SSM_DT_B_C_RMS, hparams.ssm_dt_b_c_rms, false);
  5350. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5351. switch (hparams.n_layer) {
  5352. case 24:
  5353. switch (hparams.n_embd) {
  5354. case 768: model.type = e_model::MODEL_SMALL; break;
  5355. default: model.type = e_model::MODEL_UNKNOWN;
  5356. } break;
  5357. case 48:
  5358. switch (hparams.n_embd) {
  5359. case 1024: model.type = e_model::MODEL_MEDIUM; break;
  5360. case 1536: model.type = e_model::MODEL_LARGE; break;
  5361. case 2048: model.type = e_model::MODEL_XL; break;
  5362. default: model.type = e_model::MODEL_UNKNOWN;
  5363. } break;
  5364. case 64:
  5365. switch (hparams.n_embd) {
  5366. case 2560: model.type = e_model::MODEL_3B; break;
  5367. default: model.type = e_model::MODEL_UNKNOWN;
  5368. } break;
  5369. default: model.type = e_model::MODEL_UNKNOWN;
  5370. }
  5371. } break;
  5372. case LLM_ARCH_XVERSE:
  5373. {
  5374. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5375. switch (hparams.n_layer) {
  5376. case 32: model.type = e_model::MODEL_7B; break;
  5377. case 40: model.type = e_model::MODEL_13B; break;
  5378. case 80: model.type = e_model::MODEL_65B; break;
  5379. default: model.type = e_model::MODEL_UNKNOWN;
  5380. }
  5381. } break;
  5382. case LLM_ARCH_COMMAND_R:
  5383. {
  5384. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  5385. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5386. switch (hparams.n_layer) {
  5387. case 40: model.type = e_model::MODEL_35B; break;
  5388. default: model.type = e_model::MODEL_UNKNOWN;
  5389. }
  5390. } break;
  5391. case LLM_ARCH_DBRX:
  5392. {
  5393. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5394. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv);
  5395. switch (hparams.n_layer) {
  5396. case 40: model.type = e_model::MODEL_16x12B; break;
  5397. default: model.type = e_model::MODEL_UNKNOWN;
  5398. }
  5399. } break;
  5400. case LLM_ARCH_OLMO:
  5401. {
  5402. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5403. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  5404. switch (hparams.n_layer) {
  5405. case 22: model.type = e_model::MODEL_1B; break;
  5406. case 32: model.type = e_model::MODEL_7B; break;
  5407. case 80: model.type = e_model::MODEL_70B; break;
  5408. default: model.type = e_model::MODEL_UNKNOWN;
  5409. }
  5410. } break;
  5411. case LLM_ARCH_OLMOE:
  5412. {
  5413. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5414. switch (hparams.n_layer) {
  5415. case 16: model.type = e_model::MODEL_A1_7B; break;
  5416. default: model.type = e_model::MODEL_UNKNOWN;
  5417. }
  5418. } break;
  5419. case LLM_ARCH_OPENELM:
  5420. {
  5421. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5422. switch (hparams.n_layer) {
  5423. case 16: model.type = e_model::MODEL_270M; break;
  5424. case 20: model.type = e_model::MODEL_450M; break;
  5425. case 28: model.type = e_model::MODEL_1B; break;
  5426. case 36: model.type = e_model::MODEL_3B; break;
  5427. default: model.type = e_model::MODEL_UNKNOWN;
  5428. }
  5429. } break;
  5430. case LLM_ARCH_GPTNEOX:
  5431. {
  5432. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5433. ml.get_key(LLM_KV_USE_PARALLEL_RESIDUAL, hparams.use_par_res);
  5434. switch (hparams.n_layer) {
  5435. case 6:
  5436. switch (hparams.n_ff()) {
  5437. case 512: model.type = e_model::MODEL_14M; break;
  5438. case 2048: model.type = e_model::MODEL_70M; break;
  5439. default: model.type = e_model::MODEL_UNKNOWN;
  5440. } break;
  5441. case 12:
  5442. switch (hparams.n_ff()) {
  5443. case 3072: model.type = e_model::MODEL_160M; break;
  5444. default: model.type = e_model::MODEL_UNKNOWN;
  5445. } break;
  5446. case 16:
  5447. switch (hparams.n_ff()) {
  5448. case 8192: model.type = e_model::MODEL_1B; break;
  5449. default: model.type = e_model::MODEL_UNKNOWN;
  5450. } break;
  5451. case 24:
  5452. switch (hparams.n_ff()) {
  5453. case 4096: model.type = e_model::MODEL_410M; break;
  5454. case 8192: model.type = e_model::MODEL_1_4B; break;
  5455. default: model.type = e_model::MODEL_UNKNOWN;
  5456. } break;
  5457. case 32:
  5458. switch (hparams.n_ff()) {
  5459. case 10240: model.type = e_model::MODEL_2_8B; break;
  5460. case 16384: model.type = e_model::MODEL_6_9B; break;
  5461. default: model.type = e_model::MODEL_UNKNOWN;
  5462. } break;
  5463. case 36:
  5464. switch (hparams.n_ff()) {
  5465. case 20480: model.type = e_model::MODEL_12B; break;
  5466. default: model.type = e_model::MODEL_UNKNOWN;
  5467. } break;
  5468. case 44:
  5469. switch (hparams.n_ff()) {
  5470. case 24576: model.type = e_model::MODEL_20B; break;
  5471. default: model.type = e_model::MODEL_UNKNOWN;
  5472. } break;
  5473. default: model.type = e_model::MODEL_UNKNOWN;
  5474. }
  5475. } break;
  5476. case LLM_ARCH_ARCTIC:
  5477. {
  5478. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5479. if (hparams.n_expert == 128) {
  5480. switch (hparams.n_layer) {
  5481. case 35: model.type = e_model::MODEL_10B_128x3_66B; break;
  5482. default: model.type = e_model::MODEL_UNKNOWN;
  5483. }
  5484. } else {
  5485. model.type = e_model::MODEL_UNKNOWN;
  5486. }
  5487. } break;
  5488. case LLM_ARCH_DEEPSEEK2:
  5489. {
  5490. bool is_lite = (hparams.n_layer == 27);
  5491. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5492. ml.get_key(LLM_KV_LEADING_DENSE_BLOCK_COUNT, hparams.n_layer_dense_lead);
  5493. if (!is_lite) {
  5494. ml.get_key(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q);
  5495. }
  5496. ml.get_key(LLM_KV_ATTENTION_KV_LORA_RANK, hparams.n_lora_kv);
  5497. ml.get_key(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp);
  5498. ml.get_key(LLM_KV_EXPERT_SHARED_COUNT, hparams.n_expert_shared);
  5499. ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale);
  5500. ml.get_key(LLM_KV_ROPE_SCALING_YARN_LOG_MUL, hparams.rope_yarn_log_mul);
  5501. switch (hparams.n_layer) {
  5502. case 27: model.type = e_model::MODEL_16B; break;
  5503. case 60: model.type = e_model::MODEL_236B; break;
  5504. default: model.type = e_model::MODEL_UNKNOWN;
  5505. }
  5506. } break;
  5507. case LLM_ARCH_CHATGLM:
  5508. {
  5509. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5510. switch (hparams.n_layer) {
  5511. case 28: model.type = e_model::MODEL_6B; break;
  5512. case 40: model.type = e_model::MODEL_9B; break;
  5513. default: model.type = e_model::MODEL_UNKNOWN;
  5514. }
  5515. } break;
  5516. case LLM_ARCH_BITNET:
  5517. {
  5518. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5519. switch (hparams.n_layer) {
  5520. case 26: model.type = e_model::MODEL_3B; break;
  5521. default: model.type = e_model::MODEL_UNKNOWN;
  5522. }
  5523. } break;
  5524. case LLM_ARCH_T5:
  5525. {
  5526. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5527. ml.get_key(LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, hparams.n_rel_attn_bkts);
  5528. uint32_t dec_start_token_id;
  5529. if (ml.get_key(LLM_KV_DECODER_START_TOKEN_ID, dec_start_token_id, false)) {
  5530. hparams.dec_start_token_id = dec_start_token_id;
  5531. }
  5532. switch (hparams.n_layer) {
  5533. case 6: model.type = e_model::MODEL_60M; break; // t5-small
  5534. case 8: model.type = e_model::MODEL_80M; break; // flan-t5-small
  5535. case 12:
  5536. switch (hparams.n_ff()) {
  5537. case 3072: model.type = e_model::MODEL_220M; break; // t5-base
  5538. case 2048: model.type = e_model::MODEL_250M; break; // flan-t5-base
  5539. default: model.type = e_model::MODEL_UNKNOWN;
  5540. } break;
  5541. case 24:
  5542. switch (hparams.n_ff()) {
  5543. case 4096: model.type = e_model::MODEL_770M; break; // t5-large
  5544. case 2816: model.type = e_model::MODEL_780M; break; // flan-t5-large
  5545. case 16384: model.type = e_model::MODEL_3B; break; // t5-3b
  5546. case 5120: model.type = e_model::MODEL_3B; break; // flan-t5-xl
  5547. case 65536: model.type = e_model::MODEL_11B; break; // t5-11b
  5548. case 10240: model.type = e_model::MODEL_11B; break; // flan-t5-xxl
  5549. default: model.type = e_model::MODEL_UNKNOWN;
  5550. } break;
  5551. default: model.type = e_model::MODEL_UNKNOWN;
  5552. }
  5553. } break;
  5554. case LLM_ARCH_T5ENCODER:
  5555. {
  5556. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5557. ml.get_key(LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, hparams.n_rel_attn_bkts);
  5558. model.type = e_model::MODEL_UNKNOWN;
  5559. } break;
  5560. case LLM_ARCH_JAIS:
  5561. {
  5562. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5563. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  5564. switch (hparams.n_layer) {
  5565. case 24: model.type = e_model::MODEL_1_3B; break;
  5566. case 40: model.type = e_model::MODEL_13B; break;
  5567. /* TODO: add variants */
  5568. default: model.type = e_model::MODEL_UNKNOWN;
  5569. }
  5570. } break;
  5571. case LLM_ARCH_NEMOTRON:
  5572. {
  5573. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5574. switch (hparams.n_layer) {
  5575. case 32: model.type = e_model::MODEL_4B; break;
  5576. default: model.type = e_model::MODEL_UNKNOWN;
  5577. }
  5578. } break;
  5579. case LLM_ARCH_EXAONE:
  5580. {
  5581. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5582. switch (hparams.n_layer) {
  5583. case 32: model.type = e_model::MODEL_8B; break;
  5584. default: model.type = e_model::MODEL_UNKNOWN;
  5585. }
  5586. } break;
  5587. case LLM_ARCH_RWKV6:
  5588. {
  5589. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5590. ml.get_key(LLM_KV_WKV_HEAD_SIZE, hparams.wkv_head_size);
  5591. ml.get_key(LLM_KV_TIME_MIX_EXTRA_DIM, hparams.time_mix_extra_dim);
  5592. ml.get_key(LLM_KV_TIME_DECAY_EXTRA_DIM, hparams.time_decay_extra_dim);
  5593. ml.get_key(LLM_KV_RESCALE_EVERY_N_LAYERS, hparams.rescale_every_n_layers, false);
  5594. switch (hparams.n_layer) {
  5595. case 24: model.type = e_model::MODEL_1_6B; break;
  5596. case 32:
  5597. switch (hparams.n_embd) {
  5598. case 2560: model.type = e_model::MODEL_3B; break;
  5599. case 4096: model.type = e_model::MODEL_7B; break;
  5600. default: model.type = e_model::MODEL_UNKNOWN;
  5601. } break;
  5602. case 61: model.type = e_model::MODEL_14B; break;
  5603. default: model.type = e_model::MODEL_UNKNOWN;
  5604. }
  5605. } break;
  5606. case LLM_ARCH_GRANITE:
  5607. case LLM_ARCH_GRANITE_MOE:
  5608. {
  5609. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5610. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  5611. ml.get_key(LLM_KV_RESIDUAL_SCALE, hparams.f_residual_scale);
  5612. ml.get_key(LLM_KV_EMBEDDING_SCALE, hparams.f_embedding_scale);
  5613. ml.get_key(LLM_KV_ATTENTION_SCALE, hparams.f_attention_scale);
  5614. switch (hparams.n_layer) {
  5615. case 32: model.type = e_model::MODEL_3B; break;
  5616. case 40: model.type = e_model::MODEL_3B; break;
  5617. // Add additional layer/vocab/etc checks here for other model sizes
  5618. default: model.type = e_model::MODEL_UNKNOWN;
  5619. }
  5620. } break;
  5621. case LLM_ARCH_CHAMELEON:
  5622. {
  5623. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5624. hparams.f_norm_eps = 1e-5; // eps for qk-norm, torch default
  5625. ml.get_key(LLM_KV_SWIN_NORM, hparams.swin_norm);
  5626. switch (hparams.n_layer) {
  5627. case 32: model.type = e_model::MODEL_7B; break;
  5628. case 48: model.type = e_model::MODEL_34B; break;
  5629. default: model.type = e_model::MODEL_UNKNOWN;
  5630. }
  5631. } break;
  5632. case LLM_ARCH_SOLAR:
  5633. {
  5634. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5635. for (int i = 0; i < hparams.n_bskcn_arr.max_size(); ++i) {
  5636. auto & bskcn = hparams.n_bskcn_arr.at(i);
  5637. bskcn.fill(0);
  5638. 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);
  5639. }
  5640. switch (hparams.n_layer) {
  5641. case 64: model.type = e_model::MODEL_22B; break;
  5642. default: model.type = e_model::MODEL_UNKNOWN;
  5643. }
  5644. }
  5645. default: (void)0;
  5646. }
  5647. model.ftype = ml.ftype;
  5648. if (hparams.f_max_alibi_bias > 0.0f) {
  5649. hparams.use_alibi = true;
  5650. }
  5651. hparams.rope_type = llama_rope_type(&model);
  5652. }
  5653. static void llm_load_vocab(
  5654. llama_model_loader & ml,
  5655. llama_model & model) {
  5656. auto & vocab = model.vocab;
  5657. struct gguf_context * ctx = ml.meta;
  5658. const auto kv = LLM_KV(model.arch);
  5659. // determine vocab type
  5660. {
  5661. std::string tokenizer_model;
  5662. std::string tokenizer_pre;
  5663. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_model);
  5664. ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false);
  5665. if (tokenizer_model == "no_vocab") {
  5666. vocab.type = LLAMA_VOCAB_TYPE_NONE;
  5667. // default special tokens
  5668. vocab.special_bos_id = -1;
  5669. vocab.special_eos_id = -1;
  5670. vocab.special_unk_id = -1;
  5671. vocab.special_sep_id = -1;
  5672. vocab.special_pad_id = -1;
  5673. vocab.special_cls_id = -1;
  5674. vocab.special_mask_id = -1;
  5675. vocab.linefeed_id = -1;
  5676. // read vocab size from metadata
  5677. if (!ml.get_key(LLM_KV_VOCAB_SIZE, vocab.n_vocab, false)) {
  5678. vocab.n_vocab = 0;
  5679. LLAMA_LOG_WARN("%s: there is no vocab_size in metadata, vocab.n_vocab will be set to %u\n", __func__, vocab.n_vocab);
  5680. }
  5681. return;
  5682. }
  5683. if (tokenizer_model == "llama") {
  5684. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  5685. // default special tokens
  5686. vocab.special_bos_id = 1;
  5687. vocab.special_eos_id = 2;
  5688. vocab.special_unk_id = 0;
  5689. vocab.special_sep_id = -1;
  5690. vocab.special_pad_id = -1;
  5691. vocab.special_cls_id = -1;
  5692. vocab.special_mask_id = -1;
  5693. } else if (tokenizer_model == "bert") {
  5694. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  5695. // default special tokens
  5696. vocab.special_bos_id = -1;
  5697. vocab.special_eos_id = -1;
  5698. vocab.special_unk_id = 100;
  5699. vocab.special_sep_id = 102;
  5700. vocab.special_pad_id = 0;
  5701. vocab.special_cls_id = 101;
  5702. vocab.special_mask_id = 103;
  5703. } else if (tokenizer_model == "gpt2") {
  5704. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  5705. // read bpe merges and populate bpe ranks
  5706. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  5707. if (merges_keyidx == -1) {
  5708. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  5709. }
  5710. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  5711. for (int i = 0; i < n_merges; i++) {
  5712. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  5713. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  5714. std::string first;
  5715. std::string second;
  5716. const size_t pos = word.find(' ', 1);
  5717. if (pos != std::string::npos) {
  5718. first = word.substr(0, pos);
  5719. second = word.substr(pos + 1);
  5720. }
  5721. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  5722. }
  5723. // default special tokens
  5724. vocab.special_bos_id = 11;
  5725. vocab.special_eos_id = 11;
  5726. vocab.special_unk_id = -1;
  5727. vocab.special_sep_id = -1;
  5728. vocab.special_pad_id = -1;
  5729. vocab.special_cls_id = -1;
  5730. vocab.special_mask_id = -1;
  5731. } else if (tokenizer_model == "t5") {
  5732. vocab.type = LLAMA_VOCAB_TYPE_UGM;
  5733. // default special tokens
  5734. vocab.special_bos_id = -1;
  5735. vocab.special_eos_id = 1;
  5736. vocab.special_unk_id = 2;
  5737. vocab.special_sep_id = -1;
  5738. vocab.special_pad_id = 0;
  5739. vocab.special_cls_id = -1;
  5740. vocab.special_mask_id = -1;
  5741. const int precompiled_charsmap_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP).c_str());
  5742. if (precompiled_charsmap_keyidx != -1) {
  5743. size_t n_precompiled_charsmap = gguf_get_arr_n(ctx, precompiled_charsmap_keyidx);
  5744. const char * precompiled_charsmap = (const char *) gguf_get_arr_data(ctx, precompiled_charsmap_keyidx);
  5745. vocab.precompiled_charsmap.assign(precompiled_charsmap, precompiled_charsmap + n_precompiled_charsmap);
  5746. #ifdef IS_BIG_ENDIAN
  5747. // correct endiannes of data in precompiled_charsmap binary blob
  5748. uint32_t * xcda_blob_size = (uint32_t *) &vocab.precompiled_charsmap[0];
  5749. *xcda_blob_size = __builtin_bswap32(*xcda_blob_size);
  5750. assert(*xcda_blob_size + sizeof(uint32_t) < n_precompiled_charsmap);
  5751. size_t xcda_array_size = *xcda_blob_size / sizeof(uint32_t);
  5752. uint32_t * xcda_array = (uint32_t *) &vocab.precompiled_charsmap[sizeof(uint32_t)];
  5753. for (size_t i = 0; i < xcda_array_size; ++i) {
  5754. xcda_array[i] = __builtin_bswap32(xcda_array[i]);
  5755. }
  5756. #endif
  5757. }
  5758. } else if (tokenizer_model == "rwkv") {
  5759. vocab.type = LLAMA_VOCAB_TYPE_RWKV;
  5760. // default special tokens
  5761. vocab.special_bos_id = -1;
  5762. vocab.special_eos_id = -1;
  5763. vocab.special_unk_id = -1;
  5764. vocab.special_sep_id = -1;
  5765. vocab.special_pad_id = -1;
  5766. } else {
  5767. throw std::runtime_error(format("unknown tokenizer: '%s'", tokenizer_model.c_str()));
  5768. }
  5769. // for now, only BPE models have pre-tokenizers
  5770. if (vocab.type == LLAMA_VOCAB_TYPE_BPE) {
  5771. vocab.tokenizer_add_space_prefix = false;
  5772. vocab.tokenizer_clean_spaces = true;
  5773. if (tokenizer_pre == "default") {
  5774. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5775. } else if (
  5776. tokenizer_pre == "llama3" ||
  5777. tokenizer_pre == "llama-v3" ||
  5778. tokenizer_pre == "llama-bpe") {
  5779. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_LLAMA3;
  5780. vocab.tokenizer_ignore_merges = true;
  5781. vocab.tokenizer_add_bos = true;
  5782. } else if (
  5783. tokenizer_pre == "deepseek-llm") {
  5784. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM;
  5785. vocab.tokenizer_clean_spaces = false;
  5786. } else if (
  5787. tokenizer_pre == "deepseek-coder") {
  5788. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER;
  5789. vocab.tokenizer_clean_spaces = false;
  5790. } else if (
  5791. tokenizer_pre == "falcon") {
  5792. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_FALCON;
  5793. } else if (
  5794. tokenizer_pre == "mpt") {
  5795. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_MPT;
  5796. } else if (
  5797. tokenizer_pre == "starcoder") {
  5798. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_STARCODER;
  5799. } else if (
  5800. tokenizer_pre == "gpt-2" ||
  5801. tokenizer_pre == "phi-2" ||
  5802. tokenizer_pre == "jina-es" ||
  5803. tokenizer_pre == "jina-de" ||
  5804. tokenizer_pre == "jina-v1-en" ||
  5805. tokenizer_pre == "jina-v2-es" ||
  5806. tokenizer_pre == "jina-v2-de" ||
  5807. tokenizer_pre == "jina-v2-code") {
  5808. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_GPT2;
  5809. } else if (
  5810. tokenizer_pre == "refact") {
  5811. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_REFACT;
  5812. } else if (
  5813. tokenizer_pre == "command-r") {
  5814. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_COMMAND_R;
  5815. vocab.tokenizer_clean_spaces = false;
  5816. } else if (
  5817. tokenizer_pre == "qwen2") {
  5818. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_QWEN2;
  5819. vocab.tokenizer_clean_spaces = false;
  5820. } else if (
  5821. tokenizer_pre == "stablelm2") {
  5822. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_STABLELM2;
  5823. } else if (
  5824. tokenizer_pre == "olmo") {
  5825. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_OLMO;
  5826. } else if (
  5827. tokenizer_pre == "dbrx") {
  5828. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DBRX;
  5829. } else if (
  5830. tokenizer_pre == "smaug-bpe") {
  5831. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_SMAUG;
  5832. } else if (
  5833. tokenizer_pre == "poro-chat") {
  5834. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_PORO;
  5835. vocab.tokenizer_clean_spaces = false;
  5836. } else if (
  5837. tokenizer_pre == "chatglm-bpe") {
  5838. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_CHATGLM4;
  5839. vocab.special_bos_id = -1;
  5840. } else if (
  5841. tokenizer_pre == "viking") {
  5842. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_VIKING;
  5843. vocab.tokenizer_clean_spaces = false;
  5844. } else if (
  5845. tokenizer_pre == "jais") {
  5846. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_JAIS;
  5847. } else if (
  5848. tokenizer_pre == "tekken") {
  5849. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_TEKKEN;
  5850. vocab.tokenizer_clean_spaces = false;
  5851. vocab.tokenizer_ignore_merges = true;
  5852. vocab.tokenizer_add_bos = true;
  5853. } else if (
  5854. tokenizer_pre == "smollm") {
  5855. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_SMOLLM;
  5856. vocab.tokenizer_clean_spaces = false;
  5857. } else if (
  5858. tokenizer_pre == "codeshell") {
  5859. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_CODESHELL;
  5860. } else if (
  5861. tokenizer_pre == "bloom") {
  5862. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_BLOOM;
  5863. } else if (
  5864. tokenizer_pre == "gpt3-finnish") {
  5865. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_GPT3_FINNISH;
  5866. } else if (
  5867. tokenizer_pre == "exaone") {
  5868. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_EXAONE;
  5869. } else if (
  5870. tokenizer_pre == "chameleon") {
  5871. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_CHAMELEON;
  5872. vocab.tokenizer_add_bos = true;
  5873. vocab.tokenizer_clean_spaces = false;
  5874. } else {
  5875. LLAMA_LOG_WARN("%s: missing or unrecognized pre-tokenizer type, using: 'default'\n", __func__);
  5876. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5877. }
  5878. } else if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  5879. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5880. vocab.tokenizer_add_space_prefix = true;
  5881. vocab.tokenizer_clean_spaces = false;
  5882. vocab.tokenizer_add_bos = true;
  5883. vocab.tokenizer_add_eos = false;
  5884. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  5885. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5886. vocab.tokenizer_add_space_prefix = false;
  5887. vocab.tokenizer_clean_spaces = true;
  5888. vocab.tokenizer_add_bos = true;
  5889. vocab.tokenizer_add_eos = false;
  5890. } else if (vocab.type == LLAMA_VOCAB_TYPE_UGM) {
  5891. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5892. vocab.tokenizer_add_bos = false;
  5893. vocab.tokenizer_add_eos = true;
  5894. } else if (vocab.type == LLAMA_VOCAB_TYPE_RWKV) {
  5895. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5896. vocab.tokenizer_add_space_prefix = false;
  5897. vocab.tokenizer_clean_spaces = false;
  5898. vocab.tokenizer_add_bos = false;
  5899. vocab.tokenizer_add_eos = false;
  5900. } else {
  5901. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5902. }
  5903. ml.get_key(LLM_KV_TOKENIZER_ADD_PREFIX, vocab.tokenizer_add_space_prefix, false);
  5904. ml.get_key(LLM_KV_TOKENIZER_REMOVE_EXTRA_WS, vocab.tokenizer_remove_extra_whitespaces, false);
  5905. }
  5906. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  5907. if (token_idx == -1) {
  5908. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  5909. }
  5910. const float * scores = nullptr;
  5911. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  5912. if (score_idx != -1) {
  5913. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  5914. }
  5915. const int * toktypes = nullptr;
  5916. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  5917. if (toktype_idx != -1) {
  5918. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  5919. }
  5920. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  5921. vocab.n_vocab = n_vocab;
  5922. vocab.id_to_token.resize(n_vocab);
  5923. for (uint32_t i = 0; i < n_vocab; i++) {
  5924. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  5925. //GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  5926. if (word.empty()) {
  5927. LLAMA_LOG_WARN("%s: empty token at index %u\n", __func__, i);
  5928. word = "[EMPTY_" + std::to_string(i) + "]";
  5929. }
  5930. vocab.token_to_id[word] = i;
  5931. vocab.max_token_len = std::max(vocab.max_token_len, (int) word.size());
  5932. auto & token_data = vocab.id_to_token[i];
  5933. token_data.text = std::move(word);
  5934. token_data.score = scores ? scores[i] : 0.0f;
  5935. token_data.attr = LLAMA_TOKEN_ATTR_NORMAL;
  5936. if (toktypes) { //TODO: remove, required until per token attributes are available from GGUF file
  5937. switch(toktypes[i]) {
  5938. case LLAMA_TOKEN_TYPE_UNKNOWN: token_data.attr = LLAMA_TOKEN_ATTR_UNKNOWN; break;
  5939. case LLAMA_TOKEN_TYPE_UNUSED: token_data.attr = LLAMA_TOKEN_ATTR_UNUSED; break;
  5940. case LLAMA_TOKEN_TYPE_NORMAL: token_data.attr = LLAMA_TOKEN_ATTR_NORMAL; break;
  5941. case LLAMA_TOKEN_TYPE_CONTROL: token_data.attr = LLAMA_TOKEN_ATTR_CONTROL; break;
  5942. case LLAMA_TOKEN_TYPE_USER_DEFINED: token_data.attr = LLAMA_TOKEN_ATTR_USER_DEFINED; break;
  5943. case LLAMA_TOKEN_TYPE_BYTE: token_data.attr = LLAMA_TOKEN_ATTR_BYTE; break;
  5944. case LLAMA_TOKEN_TYPE_UNDEFINED: token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED; break;
  5945. default: token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED; break;
  5946. }
  5947. }
  5948. }
  5949. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  5950. vocab.init_tokenizer();
  5951. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  5952. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  5953. // For Fill-In-the-Middle (FIM)/infill models which where converted
  5954. // prior to support of FIM special tokens in GGUF, the following
  5955. // will allow those models to continue to work. The general names
  5956. // of the known models are currently CodeLlama (LLM_ARCH_LLAMA) and
  5957. // CodeGemma (LLM_ARCH_GEMMA). This can potentially be removed once
  5958. // new versions of these models have been published.
  5959. std::string gen_name;
  5960. ml.get_key(LLM_KV_GENERAL_NAME, gen_name, false);
  5961. std::transform(gen_name.begin(), gen_name.end(), gen_name.begin(),
  5962. [](unsigned char c){ return std::tolower(c); });
  5963. if (gen_name.find("code") != std::string::npos) {
  5964. if (model.arch == LLM_ARCH_LLAMA
  5965. && 32010 < vocab.id_to_token.size()
  5966. && vocab.id_to_token[32007].text.find("<PRE>") != std::string::npos
  5967. && vocab.id_to_token[32008].text.find("<SUF>") != std::string::npos
  5968. && vocab.id_to_token[32009].text.find("<MID>") != std::string::npos
  5969. && vocab.id_to_token[32010].text.find("<EOT>") != std::string::npos) {
  5970. vocab.special_prefix_id = 32007;
  5971. vocab.special_suffix_id = 32008;
  5972. vocab.special_middle_id = 32009;
  5973. vocab.special_eot_id = 32010;
  5974. } else if (model.arch == LLM_ARCH_GEMMA
  5975. && 107 < vocab.id_to_token.size()
  5976. && vocab.id_to_token[67].text == "<|fim_prefix|>"
  5977. && vocab.id_to_token[69].text == "<|fim_suffix|>"
  5978. && vocab.id_to_token[68].text == "<|fim_middle|>"
  5979. && vocab.id_to_token[107].text == "<end_of_turn>") {
  5980. vocab.special_prefix_id = 67;
  5981. vocab.special_suffix_id = 69;
  5982. vocab.special_middle_id = 68;
  5983. // TODO: this is not EOT, it is "file separator" token, needs fix
  5984. // https://huggingface.co/google/codegemma-7b-it/blob/9b1d9231388358c04d90bd003458f5070d97db44/tokenizer_config.json#L565-L572
  5985. //vocab.special_eot_id = 70;
  5986. vocab.special_eot_id = 107;
  5987. }
  5988. }
  5989. try {
  5990. vocab.linefeed_id = llama_byte_to_token_impl(vocab, '\n');
  5991. } catch (const std::exception & e) {
  5992. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  5993. vocab.linefeed_id = vocab.special_pad_id;
  5994. }
  5995. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  5996. vocab.linefeed_id = vocab.special_pad_id;
  5997. } else if (vocab.type == LLAMA_VOCAB_TYPE_RWKV) {
  5998. const std::vector<int> ids = llama_tokenize_internal(vocab, "\n", false);
  5999. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  6000. vocab.linefeed_id = ids[0];
  6001. } else {
  6002. const std::vector<int> ids = llama_tokenize_internal(vocab, "\xC4\x8A", false); // U+010A
  6003. //GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  6004. if (ids.empty()) {
  6005. LLAMA_LOG_WARN("%s: model vocab missing newline token, using special_pad_id instead\n", __func__);
  6006. vocab.linefeed_id = vocab.special_pad_id;
  6007. } else {
  6008. vocab.linefeed_id = ids[0];
  6009. }
  6010. }
  6011. // special tokens
  6012. {
  6013. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  6014. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  6015. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  6016. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  6017. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  6018. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  6019. { LLM_KV_TOKENIZER_CLS_ID, vocab.special_cls_id },
  6020. { LLM_KV_TOKENIZER_MASK_ID, vocab.special_mask_id },
  6021. { LLM_KV_TOKENIZER_PREFIX_ID, vocab.special_prefix_id },
  6022. { LLM_KV_TOKENIZER_SUFFIX_ID, vocab.special_suffix_id },
  6023. { LLM_KV_TOKENIZER_MIDDLE_ID, vocab.special_middle_id },
  6024. { LLM_KV_TOKENIZER_EOT_ID, vocab.special_eot_id },
  6025. { LLM_KV_TOKENIZER_EOM_ID, vocab.special_eom_id },
  6026. };
  6027. for (const auto & it : special_token_types) {
  6028. const std::string & key = kv(std::get<0>(it));
  6029. int32_t & id = std::get<1>(it);
  6030. uint32_t new_id;
  6031. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  6032. continue;
  6033. }
  6034. if (new_id >= vocab.id_to_token.size()) {
  6035. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  6036. __func__, key.c_str(), new_id, id);
  6037. } else {
  6038. id = new_id;
  6039. }
  6040. }
  6041. // Handle add_bos_token and add_eos_token
  6042. {
  6043. bool temp = true;
  6044. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  6045. vocab.tokenizer_add_bos = temp;
  6046. }
  6047. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  6048. vocab.tokenizer_add_eos = temp;
  6049. }
  6050. }
  6051. // find EOT token: "<|eot_id|>", "<|im_end|>", "<end_of_turn>", etc.
  6052. //
  6053. // TODO: convert scripts should provide this token through the KV metadata LLAMA_KV_TOKENIZER_EOT_ID
  6054. // for now, we apply this workaround to find the EOT token based on its text
  6055. if (vocab.special_eot_id == -1) {
  6056. for (const auto & t : vocab.token_to_id) {
  6057. if (false
  6058. // TODO: gemma "<end_of_turn>" is exported as a normal token, so the following check does not work
  6059. // need to fix convert script
  6060. //vocab.id_to_token[t.second].type == LLAMA_TOKEN_TYPE_CONTROL &&
  6061. || t.first == "<|eot_id|>"
  6062. || t.first == "<|im_end|>"
  6063. || t.first == "<|end|>"
  6064. || t.first == "<end_of_turn>"
  6065. || t.first == "<|endoftext|>"
  6066. || t.first == "<EOT>"
  6067. ) {
  6068. vocab.special_eot_id = t.second;
  6069. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6070. LLAMA_LOG_WARN("%s: control-looking token: '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  6071. __func__, t.first.c_str());
  6072. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6073. }
  6074. break;
  6075. }
  6076. }
  6077. }
  6078. // find EOM token: "<|eom_id|>"
  6079. //
  6080. // TODO: convert scripts should provide this token through the KV metadata LLAMA_KV_TOKENIZER_EOM_ID
  6081. // for now, we apply this workaround to find the EOM token based on its text
  6082. if (vocab.special_eom_id == -1) {
  6083. const auto & t = vocab.token_to_id.find("<|eom_id|>");
  6084. if (t != vocab.token_to_id.end()) {
  6085. vocab.special_eom_id = t->second;
  6086. if ((vocab.id_to_token[t->second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6087. LLAMA_LOG_WARN("%s: control-looking token: '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  6088. __func__, t->first.c_str());
  6089. vocab.id_to_token[t->second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6090. }
  6091. }
  6092. }
  6093. // maintain a list of tokens that cause end-of-generation
  6094. // this is currently determined based on the token text, which is obviously not ideal
  6095. // ref: https://github.com/ggerganov/llama.cpp/issues/9606
  6096. vocab.special_eog_ids.clear();
  6097. for (const auto & t : vocab.token_to_id) {
  6098. if (false
  6099. || t.first == "<|eot_id|>"
  6100. || t.first == "<|im_end|>"
  6101. || t.first == "<|end|>"
  6102. || t.first == "<end_of_turn>"
  6103. || t.first == "<|endoftext|>"
  6104. || t.first == "<|eom_id|>"
  6105. || t.first == "<EOT>"
  6106. ) {
  6107. vocab.special_eog_ids.insert(t.second);
  6108. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6109. LLAMA_LOG_WARN("%s: control-looking token: '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  6110. __func__, t.first.c_str());
  6111. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6112. }
  6113. }
  6114. }
  6115. if (vocab.special_eos_id != -1 && vocab.special_eog_ids.count(vocab.special_eos_id) == 0) {
  6116. vocab.special_eog_ids.insert(vocab.special_eos_id);
  6117. LLAMA_LOG_WARN("%s: special_eos_id is not in special_eog_ids - the tokenizer config may be incorrect\n", __func__);
  6118. }
  6119. if (vocab.special_eot_id != -1 && vocab.special_eog_ids.count(vocab.special_eot_id) == 0) {
  6120. vocab.special_eog_ids.insert(vocab.special_eot_id);
  6121. LLAMA_LOG_WARN("%s: special_eot_id is not in special_eog_ids - the tokenizer config may be incorrect\n", __func__);
  6122. }
  6123. if (vocab.special_eom_id != -1 && vocab.special_eog_ids.count(vocab.special_eom_id) == 0) {
  6124. vocab.special_eog_ids.insert(vocab.special_eom_id);
  6125. LLAMA_LOG_WARN("%s: special_eom_id is not in special_eog_ids - the tokenizer config may be incorrect\n", __func__);
  6126. }
  6127. }
  6128. // build special tokens cache
  6129. {
  6130. for (llama_vocab::id id = 0; id < (llama_vocab::id)n_vocab; ++id) {
  6131. if (vocab.id_to_token[id].attr & (LLAMA_TOKEN_ATTR_CONTROL | LLAMA_TOKEN_ATTR_USER_DEFINED | LLAMA_TOKEN_ATTR_UNKNOWN)) {
  6132. vocab.cache_special_tokens.push_back(id);
  6133. }
  6134. }
  6135. std::sort(vocab.cache_special_tokens.begin(), vocab.cache_special_tokens.end(),
  6136. [&] (const llama_vocab::id a, const llama_vocab::id b) {
  6137. return vocab.id_to_token[a].text.size() > vocab.id_to_token[b].text.size();
  6138. }
  6139. );
  6140. LLAMA_LOG_INFO("%s: special tokens cache size = %u\n", __func__, (uint32_t)vocab.cache_special_tokens.size());
  6141. }
  6142. // build token to piece cache
  6143. {
  6144. size_t size_cache = 0;
  6145. std::vector<llama_vocab::token> cache_token_to_piece(n_vocab);
  6146. for (uint32_t id = 0; id < n_vocab; ++id) {
  6147. cache_token_to_piece[id] = llama_token_to_piece(&model, id, true);
  6148. size_cache += cache_token_to_piece[id].size();
  6149. }
  6150. std::swap(vocab.cache_token_to_piece, cache_token_to_piece);
  6151. LLAMA_LOG_INFO("%s: token to piece cache size = %.4f MB\n", __func__, size_cache / 1024.0 / 1024.0);
  6152. }
  6153. // Handle per token attributes
  6154. //NOTE: Each model customizes per token attributes.
  6155. //NOTE: Per token attributes are missing from the GGUF file.
  6156. //TODO: Extract attributes from GGUF file.
  6157. {
  6158. auto _contains_any = [] (const std::string &str, const std::vector<std::string> &substrs) -> bool {
  6159. for (auto substr : substrs) {
  6160. if (str.find(substr) < std::string::npos) {
  6161. return true;
  6162. }
  6163. }
  6164. return false;
  6165. };
  6166. auto _set_tokenid_attr = [&] (const llama_vocab::id id, llama_token_attr attr, bool value) {
  6167. uint32_t current = vocab.id_to_token.at(id).attr;
  6168. current = value ? (current | attr) : (current & ~attr);
  6169. vocab.id_to_token[id].attr = (llama_token_attr) current;
  6170. };
  6171. auto _set_token_attr = [&] (const std::string & token, llama_token_attr attr, bool value) {
  6172. _set_tokenid_attr(vocab.token_to_id.at(token), attr, value);
  6173. };
  6174. std::string model_name;
  6175. std::string tokenizer_pre;
  6176. ml.get_key(LLM_KV_GENERAL_NAME, model_name, false);
  6177. ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false);
  6178. // model name to lowercase
  6179. std::transform(model_name.begin(), model_name.end(), model_name.begin(),
  6180. [] (const std::string::value_type x) {
  6181. return std::tolower(x);
  6182. }
  6183. );
  6184. // set attributes by model/tokenizer name
  6185. if (_contains_any(tokenizer_pre, {"jina-v2-de", "jina-v2-es", "jina-v2-code"})) {
  6186. _set_token_attr("<mask>", LLAMA_TOKEN_ATTR_LSTRIP, true);
  6187. } else if (_contains_any(model_name, {"phi-3", "phi3"})) {
  6188. for (auto id : vocab.cache_special_tokens) {
  6189. _set_tokenid_attr(id, LLAMA_TOKEN_ATTR_RSTRIP, true);
  6190. }
  6191. for (auto token : {"</s>"}) {
  6192. _set_token_attr(token, LLAMA_TOKEN_ATTR_RSTRIP, true);
  6193. }
  6194. for (auto token : {"<unk>", "<s>", "<|endoftext|>"}) {
  6195. _set_token_attr(token, LLAMA_TOKEN_ATTR_RSTRIP, false);
  6196. }
  6197. }
  6198. }
  6199. }
  6200. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  6201. const auto & hparams = model.hparams;
  6202. const auto & vocab = model.vocab;
  6203. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  6204. auto print_f = [](const std::function<uint32_t(uint32_t)> & f, uint32_t n) {
  6205. bool is_var = false;
  6206. std::vector<uint32_t> v;
  6207. for (uint32_t i = 0; i < n; ++i) {
  6208. v.push_back(f(i));
  6209. if (v[i] != v[0]) {
  6210. is_var = true;
  6211. }
  6212. }
  6213. std::stringstream ss;
  6214. if (is_var) {
  6215. ss << "[";
  6216. for (uint32_t i = 0; i < n; ++i) {
  6217. ss << v[i];
  6218. if (i < n - 1) {
  6219. ss << ", ";
  6220. }
  6221. }
  6222. ss << "]";
  6223. } else {
  6224. ss << v[0];
  6225. }
  6226. return ss.str();
  6227. };
  6228. // hparams
  6229. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  6230. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  6231. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  6232. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  6233. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  6234. LLAMA_LOG_INFO("%s: vocab_only = %d\n", __func__, hparams.vocab_only);
  6235. if (!hparams.vocab_only) {
  6236. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  6237. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  6238. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  6239. LLAMA_LOG_INFO("%s: n_head = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_head(il); }, hparams.n_layer).c_str());
  6240. 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());
  6241. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  6242. LLAMA_LOG_INFO("%s: n_swa = %u\n", __func__, hparams.n_swa);
  6243. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  6244. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  6245. LLAMA_LOG_INFO("%s: n_gqa = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_gqa(il); }, hparams.n_layer).c_str());
  6246. 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());
  6247. 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());
  6248. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  6249. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  6250. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  6251. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  6252. LLAMA_LOG_INFO("%s: f_logit_scale = %.1e\n", __func__, hparams.f_logit_scale);
  6253. LLAMA_LOG_INFO("%s: n_ff = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_ff(il); }, hparams.n_layer).c_str());
  6254. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  6255. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  6256. LLAMA_LOG_INFO("%s: causal attn = %d\n", __func__, hparams.causal_attn);
  6257. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  6258. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  6259. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  6260. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  6261. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  6262. LLAMA_LOG_INFO("%s: n_ctx_orig_yarn = %u\n", __func__, hparams.n_ctx_orig_yarn);
  6263. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  6264. LLAMA_LOG_INFO("%s: ssm_d_conv = %u\n", __func__, hparams.ssm_d_conv);
  6265. LLAMA_LOG_INFO("%s: ssm_d_inner = %u\n", __func__, hparams.ssm_d_inner);
  6266. LLAMA_LOG_INFO("%s: ssm_d_state = %u\n", __func__, hparams.ssm_d_state);
  6267. LLAMA_LOG_INFO("%s: ssm_dt_rank = %u\n", __func__, hparams.ssm_dt_rank);
  6268. LLAMA_LOG_INFO("%s: ssm_dt_b_c_rms = %d\n", __func__, hparams.ssm_dt_b_c_rms);
  6269. }
  6270. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  6271. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  6272. if (ml.n_elements >= 1e12) {
  6273. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  6274. } else if (ml.n_elements >= 1e9) {
  6275. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  6276. } else if (ml.n_elements >= 1e6) {
  6277. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  6278. } else {
  6279. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  6280. }
  6281. if (ml.n_bytes < GiB) {
  6282. 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);
  6283. } else {
  6284. 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);
  6285. }
  6286. // general kv
  6287. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  6288. // special tokens
  6289. 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() ); }
  6290. 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() ); }
  6291. 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() ); }
  6292. 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() ); }
  6293. 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() ); }
  6294. 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() ); }
  6295. 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() ); }
  6296. 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() ); }
  6297. if (vocab.special_prefix_id != -1) { LLAMA_LOG_INFO( "%s: PRE token = %d '%s'\n", __func__, vocab.special_prefix_id, vocab.id_to_token[vocab.special_prefix_id].text.c_str() ); }
  6298. if (vocab.special_suffix_id != -1) { LLAMA_LOG_INFO( "%s: SUF token = %d '%s'\n", __func__, vocab.special_suffix_id, vocab.id_to_token[vocab.special_suffix_id].text.c_str() ); }
  6299. if (vocab.special_middle_id != -1) { LLAMA_LOG_INFO( "%s: MID token = %d '%s'\n", __func__, vocab.special_middle_id, vocab.id_to_token[vocab.special_middle_id].text.c_str() ); }
  6300. 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() ); }
  6301. 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() ); }
  6302. for (const auto & id : vocab.special_eog_ids) {
  6303. LLAMA_LOG_INFO( "%s: EOG token = %d '%s'\n", __func__, id, vocab.id_to_token[id].text.c_str() );
  6304. }
  6305. LLAMA_LOG_INFO("%s: max token length = %d\n", __func__, vocab.max_token_len);
  6306. if (model.arch == LLM_ARCH_DEEPSEEK2) {
  6307. LLAMA_LOG_INFO("%s: n_layer_dense_lead = %d\n", __func__, hparams.n_layer_dense_lead);
  6308. LLAMA_LOG_INFO("%s: n_lora_q = %d\n", __func__, hparams.n_lora_q);
  6309. LLAMA_LOG_INFO("%s: n_lora_kv = %d\n", __func__, hparams.n_lora_kv);
  6310. LLAMA_LOG_INFO("%s: n_ff_exp = %d\n", __func__, hparams.n_ff_exp);
  6311. LLAMA_LOG_INFO("%s: n_expert_shared = %d\n", __func__, hparams.n_expert_shared);
  6312. LLAMA_LOG_INFO("%s: expert_weights_scale = %.1f\n", __func__, hparams.expert_weights_scale);
  6313. LLAMA_LOG_INFO("%s: rope_yarn_log_mul = %.4f\n", __func__, hparams.rope_yarn_log_mul);
  6314. }
  6315. if (model.arch == LLM_ARCH_QWEN2MOE) {
  6316. LLAMA_LOG_INFO("%s: n_ff_exp = %d\n", __func__, hparams.n_ff_exp);
  6317. LLAMA_LOG_INFO("%s: n_ff_shexp = %d\n", __func__, hparams.n_ff_shexp);
  6318. }
  6319. if (model.arch == LLM_ARCH_GRANITE || model.arch == LLM_ARCH_GRANITE_MOE) {
  6320. LLAMA_LOG_INFO("%s: f_embedding_scale = %f\n", __func__, hparams.f_embedding_scale);
  6321. LLAMA_LOG_INFO("%s: f_residual_scale = %f\n", __func__, hparams.f_residual_scale);
  6322. LLAMA_LOG_INFO("%s: f_attention_scale = %f\n", __func__, hparams.f_attention_scale);
  6323. }
  6324. }
  6325. // Returns false if cancelled by progress_callback
  6326. static bool llm_load_tensors(
  6327. llama_model_loader & ml,
  6328. llama_model & model,
  6329. int n_gpu_layers,
  6330. enum llama_split_mode split_mode,
  6331. int main_gpu,
  6332. const float * tensor_split,
  6333. bool use_mlock,
  6334. llama_progress_callback progress_callback,
  6335. void * progress_callback_user_data) {
  6336. auto & hparams = model.hparams;
  6337. model.split_mode = split_mode;
  6338. model.main_gpu = main_gpu;
  6339. model.n_gpu_layers = n_gpu_layers;
  6340. const int n_layer = hparams.n_layer;
  6341. const int i_gpu_start = std::max((int) hparams.n_layer - n_gpu_layers, (int) 0);
  6342. bool use_mmap_buffer = true;
  6343. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  6344. model.buft_input = llama_default_buffer_type_cpu(true);
  6345. //model.buft_input = llama_default_buffer_type_offload(main_gpu);
  6346. model.buft_layer.resize(n_layer);
  6347. // assign cpu layers
  6348. for (int i = 0; i < i_gpu_start; ++i) {
  6349. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  6350. }
  6351. if (split_mode == LLAMA_SPLIT_MODE_LAYER) {
  6352. // calculate the split points
  6353. int device_count = llama_get_device_count(model);
  6354. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  6355. std::vector<float> splits(device_count);
  6356. if (all_zero) {
  6357. // default split, by free memory
  6358. for (int i = 0; i < device_count; ++i) {
  6359. splits[i] = llama_get_device_memory(model, i);
  6360. }
  6361. } else {
  6362. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  6363. }
  6364. // sum and normalize the splits to get the split points
  6365. float split_sum = 0.0f;
  6366. for (int i = 0; i < device_count; ++i) {
  6367. split_sum += splits[i];
  6368. splits[i] = split_sum;
  6369. }
  6370. for (int i = 0; i < device_count; ++i) {
  6371. splits[i] /= split_sum;
  6372. }
  6373. // assign the repeating layers to the devices according to the splits
  6374. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  6375. for (int i = i_gpu_start; i < n_layer; ++i) {
  6376. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  6377. model.buft_layer[i] = llama_default_buffer_type_offload(model, layer_gpu);
  6378. }
  6379. // assign the output layer
  6380. if (n_gpu_layers > n_layer) {
  6381. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  6382. model.buft_output = llama_default_buffer_type_offload(model, layer_gpu);
  6383. } else {
  6384. model.buft_output = llama_default_buffer_type_cpu(true);
  6385. }
  6386. } else {
  6387. ggml_backend_buffer_type_t split_buft;
  6388. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  6389. split_buft = llama_default_buffer_type_split(model, main_gpu, tensor_split);
  6390. } else {
  6391. // LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_LAYER in backends where it is not supported
  6392. split_buft = llama_default_buffer_type_offload(model, main_gpu);
  6393. }
  6394. // assign the repeating layers
  6395. for (int i = i_gpu_start; i < n_layer; ++i) {
  6396. model.buft_layer[i] = {
  6397. split_buft,
  6398. llama_default_buffer_type_offload(model, main_gpu)
  6399. };
  6400. }
  6401. // assign the output layer
  6402. if (n_gpu_layers > n_layer) {
  6403. model.buft_output = {
  6404. split_buft,
  6405. llama_default_buffer_type_offload(model, main_gpu)
  6406. };
  6407. } else {
  6408. model.buft_output = llama_default_buffer_type_cpu(true);
  6409. }
  6410. }
  6411. // count used buffer types
  6412. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  6413. buft_layer_count[model.buft_input.buft]++;
  6414. buft_layer_count[model.buft_input.buft_matrix]++;
  6415. buft_layer_count[model.buft_output.buft]++;
  6416. buft_layer_count[model.buft_output.buft_matrix]++;
  6417. for (int i = 0; i < n_layer; ++i) {
  6418. buft_layer_count[model.buft_layer[i].buft]++;
  6419. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  6420. }
  6421. // create one context per buffer type
  6422. size_t ctx_size = ggml_tensor_overhead()*(ml.n_tensors + 1); // +1 for models where tok_embd is duplicated as output
  6423. // for moe merged tensors
  6424. ctx_size += ggml_tensor_overhead()*n_layer*3;
  6425. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  6426. for (auto & it : buft_layer_count) {
  6427. struct ggml_init_params params = {
  6428. /*.mem_size =*/ ctx_size,
  6429. /*.mem_buffer =*/ NULL,
  6430. /*.no_alloc =*/ true,
  6431. };
  6432. ggml_context * ctx = ggml_init(params);
  6433. if (!ctx) {
  6434. throw std::runtime_error(format("failed to create context"));
  6435. }
  6436. ctx_map[it.first] = ctx;
  6437. model.ctxs.push_back(ctx);
  6438. }
  6439. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  6440. // create tensors for the weights
  6441. {
  6442. // note: cast to int64_t since we will use these for the tensor dimensions
  6443. const int64_t n_head = hparams.n_head();
  6444. const int64_t n_head_kv = hparams.n_head_kv();
  6445. const int64_t n_embd = hparams.n_embd;
  6446. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  6447. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  6448. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  6449. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  6450. const int64_t n_ff = hparams.n_ff();
  6451. const int64_t n_embd_gqa = n_embd_v_gqa;
  6452. const int64_t n_vocab = hparams.n_vocab;
  6453. const int64_t n_vocab_type = hparams.n_vocab_type;
  6454. const int64_t n_rot = hparams.n_rot;
  6455. const int64_t n_expert = hparams.n_expert;
  6456. const int64_t n_expert_used = hparams.n_expert_used;
  6457. const int64_t n_ctx_train = hparams.n_ctx_train;
  6458. if (n_expert > 0 && hparams.n_expert_used == 0) {
  6459. throw std::runtime_error("model has expert layers but no expert layers are used");
  6460. }
  6461. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  6462. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  6463. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  6464. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  6465. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  6466. model.layers.resize(n_layer);
  6467. const auto tn = LLM_TN(model.arch);
  6468. switch (model.arch) {
  6469. case LLM_ARCH_LLAMA:
  6470. case LLM_ARCH_REFACT:
  6471. case LLM_ARCH_MINICPM:
  6472. case LLM_ARCH_GRANITE:
  6473. case LLM_ARCH_GRANITE_MOE:
  6474. {
  6475. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6476. // output
  6477. {
  6478. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6479. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6480. // if output is NULL, init from the input tok embed
  6481. if (model.output == NULL) {
  6482. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6483. }
  6484. }
  6485. for (int i = 0; i < n_layer; ++i) {
  6486. ggml_context * ctx_layer = ctx_for_layer(i);
  6487. ggml_context * ctx_split = ctx_for_layer_split(i);
  6488. auto & layer = model.layers[i];
  6489. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6490. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  6491. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  6492. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  6493. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  6494. // optional bias tensors
  6495. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6496. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6497. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6498. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6499. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6500. layer.rope_freqs = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ROPE_FREQS, "weight"), {n_rot/2}, llama_model_loader::TENSOR_NOT_REQUIRED | (i != 0 ? llama_model_loader::TENSOR_DUPLICATED : 0));
  6501. if (n_expert == 0) {
  6502. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6503. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6504. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6505. // optional MLP bias
  6506. layer.ffn_gate_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6507. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6508. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6509. } else {
  6510. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  6511. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6512. if (layer.ffn_gate_exps) {
  6513. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  6514. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  6515. } else {
  6516. // merge split expert into a single tensor for compatibility with older models
  6517. // requires disabling mmap
  6518. use_mmap_buffer = false;
  6519. ggml_type type_gate = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, 0).c_str())->type;
  6520. ggml_type type_down = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, 0).c_str())->type;
  6521. ggml_type type_up = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, 0).c_str())->type;
  6522. layer.ffn_gate_exps = ggml_new_tensor_3d(ctx_split, type_gate, n_embd, n_ff, n_expert);
  6523. layer.ffn_down_exps = ggml_new_tensor_3d(ctx_split, type_down, n_ff, n_embd, n_expert);
  6524. layer.ffn_up_exps = ggml_new_tensor_3d(ctx_split, type_up, n_embd, n_ff, n_expert);
  6525. ggml_set_name(layer.ffn_gate_exps, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i).c_str());
  6526. ggml_set_name(layer.ffn_down_exps, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i).c_str());
  6527. ggml_set_name(layer.ffn_up_exps, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i).c_str());
  6528. for (uint32_t x = 0; x < n_expert; ++x) {
  6529. // the individual experts are loaded into a view of the merged tensor
  6530. ml.create_tensor_as_view(ctx_split, layer.ffn_gate_exps, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), { n_embd, n_ff }, layer.ffn_gate_exps->nb[2]*x);
  6531. ml.create_tensor_as_view(ctx_split, layer.ffn_down_exps, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd }, layer.ffn_down_exps->nb[2]*x);
  6532. ml.create_tensor_as_view(ctx_split, layer.ffn_up_exps, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), { n_embd, n_ff }, layer.ffn_up_exps->nb[2]*x);
  6533. }
  6534. }
  6535. }
  6536. }
  6537. } break;
  6538. case LLM_ARCH_MINICPM3:
  6539. {
  6540. const int64_t n_embd_head_qk_rope = hparams.n_rot;
  6541. const int64_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  6542. const int64_t q_lora_rank = hparams.n_lora_q;
  6543. const int64_t kv_lora_rank = hparams.n_lora_kv;
  6544. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6545. // output
  6546. {
  6547. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6548. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6549. // if output is NULL, init from the input tok embed
  6550. if (model.output == NULL) {
  6551. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6552. }
  6553. }
  6554. for (int i = 0; i < n_layer; ++i) {
  6555. ggml_context * ctx_layer = ctx_for_layer(i);
  6556. ggml_context * ctx_split = ctx_for_layer_split(i);
  6557. auto & layer = model.layers[i];
  6558. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6559. layer.attn_q_a_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_A_NORM, "weight", i), {q_lora_rank});
  6560. layer.attn_kv_a_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_KV_A_NORM, "weight", i), {kv_lora_rank});
  6561. layer.wq_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q_A, "weight", i), {n_embd, q_lora_rank});
  6562. layer.wq_b = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q_B, "weight", i), {q_lora_rank, n_head * n_embd_head_k});
  6563. layer.wkv_a_mqa = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_KV_A_MQA, "weight", i), {n_embd, kv_lora_rank + (n_embd_head_qk_rope)});
  6564. layer.wkv_b = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_KV_B, "weight", i), {kv_lora_rank, n_head * (n_embd_head_qk_nope + n_embd_head_v)});
  6565. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_head * ( n_embd_head_v), n_embd});
  6566. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6567. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6568. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6569. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6570. layer.rope_long = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ROPE_FACTORS_LONG, "weight"), { n_embd_head_qk_rope/2 }, llama_model_loader::TENSOR_NOT_REQUIRED | (i != 0 ? llama_model_loader::TENSOR_DUPLICATED : 0));
  6571. layer.rope_short = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ROPE_FACTORS_SHORT, "weight"), { n_embd_head_qk_rope/2 }, llama_model_loader::TENSOR_NOT_REQUIRED | (i != 0 ? llama_model_loader::TENSOR_DUPLICATED : 0));
  6572. }
  6573. } break;
  6574. case LLM_ARCH_MLLAMA:
  6575. {
  6576. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab+8});
  6577. // output
  6578. {
  6579. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6580. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6581. // if output is NULL, init from the input tok embed
  6582. if (model.output == NULL) {
  6583. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6584. }
  6585. }
  6586. for (int i = 0; i < n_layer; ++i) {
  6587. ggml_context * ctx_layer = ctx_for_layer(i);
  6588. ggml_context * ctx_split = ctx_for_layer_split(i);
  6589. auto & layer = model.layers[i];
  6590. if (hparams.cross_attention_layer(i)) {
  6591. layer.cross_attn_k_norm = ml.create_tensor(ctx_split, tn(LLM_TENSOR_CROSS_ATTN_K_NORM, "weight", i), {128});
  6592. layer.cross_attn_k_proj = ml.create_tensor(ctx_split, tn(LLM_TENSOR_CROSS_ATTN_K_PROJ, "weight", i), {n_embd, 1024});
  6593. layer.cross_attn_o_proj = ml.create_tensor(ctx_split, tn(LLM_TENSOR_CROSS_ATTN_O_PROJ, "weight", i), {n_embd, n_embd});
  6594. layer.cross_attn_q_norm = ml.create_tensor(ctx_split, tn(LLM_TENSOR_CROSS_ATTN_Q_NORM, "weight", i), {128});
  6595. layer.cross_attn_q_proj = ml.create_tensor(ctx_split, tn(LLM_TENSOR_CROSS_ATTN_Q_PROJ, "weight", i), {n_embd, n_embd});
  6596. layer.cross_attn_v_proj = ml.create_tensor(ctx_split, tn(LLM_TENSOR_CROSS_ATTN_V_PROJ, "weight", i), {n_embd, 1024});
  6597. layer.cross_attn_attn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_CROSS_ATTN_ATTN_GATE, i), {1});
  6598. layer.cross_attn_mlp_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_CROSS_ATTN_MLP_GATE, i), {1});
  6599. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6600. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6601. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6602. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6603. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6604. } else {
  6605. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6606. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  6607. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  6608. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  6609. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  6610. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6611. layer.rope_freqs = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ROPE_FREQS, "weight"), {n_rot/2}, llama_model_loader::TENSOR_NOT_REQUIRED | (i != 0 ? llama_model_loader::TENSOR_DUPLICATED : 0));
  6612. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6613. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6614. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6615. }
  6616. }
  6617. } break;
  6618. case LLM_ARCH_GROK:
  6619. {
  6620. if (n_expert == 0) {
  6621. throw std::runtime_error("Grok model cannot have zero experts");
  6622. }
  6623. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6624. // output
  6625. {
  6626. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6627. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6628. // if output is NULL, init from the input tok embed
  6629. if (model.output == NULL) {
  6630. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6631. }
  6632. }
  6633. for (int i = 0; i < n_layer; ++i) {
  6634. ggml_context * ctx_layer = ctx_for_layer(i);
  6635. ggml_context * ctx_split = ctx_for_layer_split(i);
  6636. auto & layer = model.layers[i];
  6637. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6638. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6639. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6640. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6641. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6642. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  6643. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6644. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  6645. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6646. if (layer.ffn_gate_exps) {
  6647. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  6648. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  6649. } else {
  6650. // merge split expert into a single tensor for compatibility with older models
  6651. // requires disabling mmap
  6652. use_mmap_buffer = false;
  6653. ggml_type type_gate = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, 0).c_str())->type;
  6654. ggml_type type_down = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, 0).c_str())->type;
  6655. ggml_type type_up = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, 0).c_str())->type;
  6656. layer.ffn_gate_exps = ggml_new_tensor_3d(ctx_split, type_gate, n_embd, n_ff, n_expert);
  6657. layer.ffn_down_exps = ggml_new_tensor_3d(ctx_split, type_down, n_ff, n_embd, n_expert);
  6658. layer.ffn_up_exps = ggml_new_tensor_3d(ctx_split, type_up, n_embd, n_ff, n_expert);
  6659. ggml_set_name(layer.ffn_gate_exps, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i).c_str());
  6660. ggml_set_name(layer.ffn_down_exps, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i).c_str());
  6661. ggml_set_name(layer.ffn_up_exps, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i).c_str());
  6662. for (uint32_t x = 0; x < n_expert; ++x) {
  6663. // the individual experts are loaded into a view of the merged tensor
  6664. ml.create_tensor_as_view(ctx_split, layer.ffn_gate_exps, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), { n_embd, n_ff }, layer.ffn_gate_exps->nb[2]*x);
  6665. ml.create_tensor_as_view(ctx_split, layer.ffn_down_exps, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd }, layer.ffn_down_exps->nb[2]*x);
  6666. ml.create_tensor_as_view(ctx_split, layer.ffn_up_exps, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), { n_embd, n_ff }, layer.ffn_up_exps->nb[2]*x);
  6667. }
  6668. }
  6669. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  6670. }
  6671. } break;
  6672. case LLM_ARCH_DBRX:
  6673. {
  6674. if (n_expert == 0) {
  6675. throw std::runtime_error("DBRX model cannot have zero experts");
  6676. }
  6677. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6678. // output
  6679. {
  6680. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6681. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6682. }
  6683. for (int i = 0; i < n_layer; ++i) {
  6684. ggml_context * ctx_layer = ctx_for_layer(i);
  6685. ggml_context * ctx_split = ctx_for_layer_split(i);
  6686. auto & layer = model.layers[i];
  6687. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6688. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6689. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6690. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  6691. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  6692. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  6693. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff, n_embd, n_expert});
  6694. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  6695. }
  6696. } break;
  6697. case LLM_ARCH_BAICHUAN:
  6698. {
  6699. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6700. {
  6701. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6702. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6703. }
  6704. for (int i = 0; i < n_layer; ++i) {
  6705. ggml_context * ctx_layer = ctx_for_layer(i);
  6706. ggml_context * ctx_split = ctx_for_layer_split(i);
  6707. auto & layer = model.layers[i];
  6708. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6709. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6710. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6711. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6712. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6713. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6714. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6715. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6716. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6717. }
  6718. } break;
  6719. case LLM_ARCH_FALCON:
  6720. {
  6721. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6722. // output
  6723. {
  6724. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6725. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6726. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6727. if (!model.output) {
  6728. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED); // needs to be on GPU
  6729. }
  6730. }
  6731. for (int i = 0; i < n_layer; ++i) {
  6732. ggml_context * ctx_layer = ctx_for_layer(i);
  6733. ggml_context * ctx_split = ctx_for_layer_split(i);
  6734. auto & layer = model.layers[i];
  6735. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6736. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6737. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6738. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6739. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6740. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6741. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6742. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6743. }
  6744. } break;
  6745. case LLM_ARCH_STARCODER:
  6746. {
  6747. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6748. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train});
  6749. // output
  6750. {
  6751. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6752. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6753. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6754. if (!model.output) {
  6755. // needs to be on GPU
  6756. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6757. }
  6758. }
  6759. for (int i = 0; i < n_layer; ++i) {
  6760. ggml_context * ctx_layer = ctx_for_layer(i);
  6761. ggml_context * ctx_split = ctx_for_layer_split(i);
  6762. auto & layer = model.layers[i];
  6763. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6764. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6765. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6766. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  6767. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6768. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6769. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6770. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  6771. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6772. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6773. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6774. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  6775. }
  6776. } break;
  6777. case LLM_ARCH_BERT:
  6778. case LLM_ARCH_NOMIC_BERT:
  6779. {
  6780. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6781. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  6782. if (model.arch == LLM_ARCH_BERT) {
  6783. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train});
  6784. model.cls = ml.create_tensor(ctx_output, tn(LLM_TENSOR_CLS, "weight"), {n_embd, n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6785. model.cls_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_CLS, "bias"), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6786. model.cls_out = ml.create_tensor(ctx_output, tn(LLM_TENSOR_CLS_OUT, "weight"), {n_embd, 1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6787. model.cls_out_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_CLS_OUT, "bias"), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6788. }
  6789. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  6790. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  6791. for (int i = 0; i < n_layer; ++i) {
  6792. ggml_context * ctx_layer = ctx_for_layer(i);
  6793. ggml_context * ctx_split = ctx_for_layer_split(i);
  6794. auto & layer = model.layers[i];
  6795. if (model.arch == LLM_ARCH_BERT) {
  6796. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6797. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  6798. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6799. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  6800. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6801. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  6802. } else {
  6803. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6804. }
  6805. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6806. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  6807. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  6808. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6809. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6810. if (model.arch == LLM_ARCH_BERT) {
  6811. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6812. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  6813. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6814. } else {
  6815. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6816. }
  6817. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  6818. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  6819. }
  6820. } break;
  6821. case LLM_ARCH_JINA_BERT_V2:
  6822. {
  6823. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // word_embeddings
  6824. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type}); // token_type_embeddings
  6825. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd}); // LayerNorm
  6826. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd}); //LayerNorm bias
  6827. model.cls = ml.create_tensor(ctx_output, tn(LLM_TENSOR_CLS, "weight"), {n_embd, 1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6828. model.cls_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_CLS, "bias"), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6829. for (int i = 0; i < n_layer; ++i) {
  6830. ggml_context * ctx_layer = ctx_for_layer(i);
  6831. ggml_context * ctx_split = ctx_for_layer_split(i);
  6832. auto & layer = model.layers[i]; // JinaBertLayer
  6833. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6834. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  6835. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6836. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6837. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6838. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  6839. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6840. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6841. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6842. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  6843. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}); //output_dens
  6844. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}); //output_dens
  6845. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd}); //output_norm
  6846. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  6847. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6848. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6849. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6850. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6851. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6852. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6853. layer.layer_out_norm = ml.create_tensor(ctx_split, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  6854. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  6855. }
  6856. } break;
  6857. case LLM_ARCH_BLOOM:
  6858. {
  6859. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6860. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  6861. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  6862. // output
  6863. {
  6864. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6865. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6866. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6867. }
  6868. for (int i = 0; i < n_layer; ++i) {
  6869. ggml_context * ctx_layer = ctx_for_layer(i);
  6870. ggml_context * ctx_split = ctx_for_layer_split(i);
  6871. auto & layer = model.layers[i];
  6872. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6873. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6874. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6875. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  6876. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6877. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6878. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6879. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  6880. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6881. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6882. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6883. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  6884. }
  6885. } break;
  6886. case LLM_ARCH_MPT:
  6887. {
  6888. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6889. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6890. // output
  6891. {
  6892. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6893. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6894. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6895. if (!model.output) {
  6896. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED); // needs to be on GPU
  6897. }
  6898. }
  6899. for (int i = 0; i < n_layer; ++i) {
  6900. ggml_context * ctx_layer = ctx_for_layer(i);
  6901. ggml_context * ctx_split = ctx_for_layer_split(i);
  6902. auto & layer = model.layers[i];
  6903. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6904. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6905. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6906. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6907. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6908. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6909. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6910. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6911. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6912. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6913. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6914. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6915. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6916. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6917. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6918. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6919. // AWQ ScaleActivation layer
  6920. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6921. }
  6922. } break;
  6923. case LLM_ARCH_STABLELM:
  6924. {
  6925. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6926. // output
  6927. {
  6928. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6929. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6930. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6931. }
  6932. for (int i = 0; i < n_layer; ++i) {
  6933. ggml_context * ctx_layer = ctx_for_layer(i);
  6934. ggml_context * ctx_split = ctx_for_layer_split(i);
  6935. auto & layer = model.layers[i];
  6936. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6937. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6938. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6939. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6940. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6941. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6942. // optional bias tensors, present in Stable LM 2 1.6B
  6943. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6944. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6945. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6946. // optional q and k layernorms, present in StableLM 2 12B
  6947. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k, n_head}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6948. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k, n_head_kv}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6949. // optional FFN norm, not present in StableLM 2 12B which uses parallel residual
  6950. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6951. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6952. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6953. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6954. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6955. }
  6956. } break;
  6957. case LLM_ARCH_QWEN:
  6958. {
  6959. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6960. // output
  6961. {
  6962. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6963. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6964. }
  6965. for (int i = 0; i < n_layer; ++i) {
  6966. ggml_context * ctx_layer = ctx_for_layer(i);
  6967. ggml_context * ctx_split = ctx_for_layer_split(i);
  6968. auto & layer = model.layers[i];
  6969. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6970. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  6971. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  6972. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6973. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6974. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  6975. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  6976. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  6977. }
  6978. } break;
  6979. case LLM_ARCH_QWEN2:
  6980. {
  6981. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6982. // output
  6983. {
  6984. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6985. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6986. // if output is NULL, init from the input tok embed
  6987. if (model.output == NULL) {
  6988. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6989. }
  6990. }
  6991. for (int i = 0; i < n_layer; ++i) {
  6992. ggml_context * ctx_layer = ctx_for_layer(i);
  6993. ggml_context * ctx_split = ctx_for_layer_split(i);
  6994. auto & layer = model.layers[i];
  6995. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6996. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6997. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6998. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6999. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7000. // optional bias tensors
  7001. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  7002. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  7003. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  7004. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7005. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7006. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7007. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7008. }
  7009. } break;
  7010. case LLM_ARCH_QWEN2MOE:
  7011. {
  7012. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7013. // output
  7014. {
  7015. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7016. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7017. }
  7018. for (int i = 0; i < n_layer; ++i) {
  7019. ggml_context * ctx_layer = ctx_for_layer(i);
  7020. ggml_context * ctx_split = ctx_for_layer_split(i);
  7021. auto & layer = model.layers[i];
  7022. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7023. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7024. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7025. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7026. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7027. // optional bias tensors
  7028. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  7029. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  7030. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  7031. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7032. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  7033. GGML_ASSERT(n_expert > 0);
  7034. GGML_ASSERT(n_expert_used > 0);
  7035. // MoE branch
  7036. const int64_t n_ff_exp = hparams.n_ff_exp ? hparams.n_ff_exp : n_ff / n_expert_used;
  7037. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  7038. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert});
  7039. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  7040. // Shared expert branch
  7041. const int64_t n_ff_shexp = hparams.n_ff_shexp ? hparams.n_ff_shexp : n_ff;
  7042. layer.ffn_gate_inp_shexp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP_SHEXP, "weight", i), {n_embd});
  7043. layer.ffn_gate_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), { n_embd, n_ff_shexp});
  7044. layer.ffn_down_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), {n_ff_shexp, n_embd});
  7045. layer.ffn_up_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), { n_embd, n_ff_shexp});
  7046. }
  7047. } break;
  7048. case LLM_ARCH_PHI2:
  7049. {
  7050. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7051. // output
  7052. {
  7053. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7054. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7055. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7056. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  7057. }
  7058. for (int i = 0; i < n_layer; ++i) {
  7059. ggml_context * ctx_layer = ctx_for_layer(i);
  7060. ggml_context * ctx_split = ctx_for_layer_split(i);
  7061. auto & layer = model.layers[i];
  7062. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7063. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7064. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7065. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7066. if (layer.wqkv == nullptr) {
  7067. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7068. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  7069. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7070. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  7071. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7072. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  7073. }
  7074. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7075. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  7076. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  7077. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  7078. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7079. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  7080. }
  7081. } break;
  7082. case LLM_ARCH_PHI3:
  7083. {
  7084. const int64_t n_embd_head = n_embd / n_head;
  7085. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), { n_embd, n_vocab });
  7086. // output
  7087. {
  7088. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), { n_embd });
  7089. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), { n_embd, n_vocab });
  7090. }
  7091. for (int i = 0; i < n_layer; ++i) {
  7092. ggml_context * ctx_layer = ctx_for_layer(i);
  7093. ggml_context * ctx_split = ctx_for_layer_split(i);
  7094. auto & layer = model.layers[i];
  7095. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), { n_embd });
  7096. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), { n_embd, n_embd + 2 * n_embd_gqa }, llama_model_loader::TENSOR_NOT_REQUIRED);
  7097. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_embd, n_embd });
  7098. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), { n_embd });
  7099. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd });
  7100. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), { n_embd, 2 * n_ff });
  7101. layer.rope_long = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ROPE_FACTORS_LONG, "weight"), { n_embd_head/2 }, llama_model_loader::TENSOR_NOT_REQUIRED | (i != 0 ? llama_model_loader::TENSOR_DUPLICATED : 0));
  7102. layer.rope_short = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ROPE_FACTORS_SHORT, "weight"), { n_embd_head/2 }, llama_model_loader::TENSOR_NOT_REQUIRED | (i != 0 ? llama_model_loader::TENSOR_DUPLICATED : 0));
  7103. }
  7104. } break;
  7105. case LLM_ARCH_PLAMO:
  7106. {
  7107. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7108. // output
  7109. {
  7110. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7111. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7112. }
  7113. for (int i = 0; i < n_layer; ++i) {
  7114. ggml_context * ctx_layer = ctx_for_layer(i);
  7115. ggml_context * ctx_split = ctx_for_layer_split(i);
  7116. auto & layer = model.layers[i];
  7117. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7118. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7119. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7120. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7121. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7122. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7123. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7124. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7125. }
  7126. } break;
  7127. case LLM_ARCH_GPT2:
  7128. {
  7129. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7130. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train});
  7131. // output
  7132. {
  7133. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7134. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7135. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7136. }
  7137. for (int i = 0; i < n_layer; ++i) {
  7138. ggml_context * ctx_layer = ctx_for_layer(i);
  7139. ggml_context * ctx_split = ctx_for_layer_split(i);
  7140. auto & layer = model.layers[i];
  7141. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7142. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7143. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  7144. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  7145. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7146. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  7147. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7148. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  7149. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  7150. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  7151. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7152. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  7153. }
  7154. } break;
  7155. case LLM_ARCH_CODESHELL:
  7156. {
  7157. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7158. // output
  7159. {
  7160. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7161. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7162. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7163. }
  7164. for (int i = 0; i < n_layer; ++i) {
  7165. ggml_context * ctx_layer = ctx_for_layer(i);
  7166. ggml_context * ctx_split = ctx_for_layer_split(i);
  7167. auto & layer = model.layers[i];
  7168. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7169. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7170. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  7171. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  7172. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7173. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  7174. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7175. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  7176. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  7177. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  7178. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7179. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  7180. }
  7181. } break;
  7182. case LLM_ARCH_ORION:
  7183. {
  7184. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7185. {
  7186. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7187. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7188. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7189. }
  7190. for (int i = 0; i < n_layer; ++i) {
  7191. ggml_context * ctx_layer = ctx_for_layer(i);
  7192. ggml_context * ctx_split = ctx_for_layer_split(i);
  7193. auto & layer = model.layers[i];
  7194. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7195. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7196. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7197. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7198. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7199. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7200. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7201. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  7202. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7203. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7204. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7205. }
  7206. } break;
  7207. case LLM_ARCH_INTERNLM2:
  7208. {
  7209. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7210. // output
  7211. {
  7212. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7213. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7214. }
  7215. for (int i = 0; i < n_layer; ++i) {
  7216. ggml_context * ctx_layer = ctx_for_layer(i);
  7217. ggml_context * ctx_split = ctx_for_layer_split(i);
  7218. auto & layer = model.layers[i];
  7219. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7220. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  7221. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7222. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7223. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7224. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7225. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7226. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7227. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7228. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7229. }
  7230. } break;
  7231. case LLM_ARCH_GEMMA:
  7232. {
  7233. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7234. // output
  7235. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7236. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED); // same as tok_embd, duplicated to allow offloading
  7237. for (int i = 0; i < n_layer; ++i) {
  7238. ggml_context * ctx_layer = ctx_for_layer(i);
  7239. ggml_context * ctx_split = ctx_for_layer_split(i);
  7240. auto & layer = model.layers[i];
  7241. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7242. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  7243. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  7244. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  7245. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  7246. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7247. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7248. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7249. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7250. }
  7251. } break;
  7252. case LLM_ARCH_GEMMA2:
  7253. {
  7254. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7255. // output
  7256. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7257. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED); // same as tok_embd, duplicated to allow offloading
  7258. for (int i = 0; i < n_layer; ++i) {
  7259. ggml_context * ctx_layer = ctx_for_layer(i);
  7260. ggml_context * ctx_split = ctx_for_layer_split(i);
  7261. auto & layer = model.layers[i];
  7262. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7263. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  7264. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  7265. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  7266. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  7267. layer.attn_post_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_POST_NORM, "weight", i), {n_embd});
  7268. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7269. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7270. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7271. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7272. layer.ffn_post_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_POST_NORM, "weight", i), {n_embd});
  7273. }
  7274. } break;
  7275. case LLM_ARCH_STARCODER2:
  7276. {
  7277. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7278. // output
  7279. {
  7280. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7281. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7282. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7283. // if output is NULL, init from the input tok embed
  7284. if (model.output == NULL) {
  7285. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7286. }
  7287. }
  7288. for (int i = 0; i < n_layer; ++i) {
  7289. ggml_context * ctx_layer = ctx_for_layer(i);
  7290. ggml_context * ctx_split = ctx_for_layer_split(i);
  7291. auto & layer = model.layers[i];
  7292. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7293. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7294. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7295. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7296. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7297. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7298. // optional bias tensors
  7299. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  7300. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  7301. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  7302. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  7303. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7304. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  7305. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7306. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7307. // optional bias tensors
  7308. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  7309. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP , "bias", i), { n_ff});
  7310. }
  7311. } break;
  7312. case LLM_ARCH_MAMBA:
  7313. {
  7314. const int64_t d_conv = hparams.ssm_d_conv;
  7315. const int64_t d_inner = hparams.ssm_d_inner;
  7316. const int64_t d_state = hparams.ssm_d_state;
  7317. const int64_t dt_rank = hparams.ssm_dt_rank;
  7318. // only an expansion factor of 2 is supported for now
  7319. GGML_ASSERT(2 * n_embd == d_inner);
  7320. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7321. // output
  7322. {
  7323. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7324. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7325. // if output is NULL, init from the input tok embed, duplicated to allow offloading
  7326. if (model.output == NULL) {
  7327. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7328. }
  7329. }
  7330. for (int i = 0; i < n_layer; ++i) {
  7331. ggml_context * ctx_layer = ctx_for_layer(i);
  7332. ggml_context * ctx_split = ctx_for_layer_split(i);
  7333. auto & layer = model.layers[i];
  7334. // norm
  7335. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7336. layer.ssm_in = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_IN, "weight", i), {n_embd, 2*d_inner});
  7337. layer.ssm_conv1d = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_CONV1D, "weight", i), {d_conv, d_inner});
  7338. layer.ssm_conv1d_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_CONV1D, "bias", i), {d_inner});
  7339. layer.ssm_x = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_X, "weight", i), {d_inner, dt_rank + 2*d_state});
  7340. layer.ssm_dt = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_DT, "weight", i), {dt_rank, d_inner});
  7341. layer.ssm_dt_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_DT, "bias", i), {d_inner});
  7342. // no "weight" suffix for these
  7343. layer.ssm_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_A, i), {d_state, d_inner});
  7344. layer.ssm_d = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_D, i), {d_inner});
  7345. // out_proj
  7346. layer.ssm_out = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_OUT, "weight", i), {d_inner, n_embd});
  7347. }
  7348. } break;
  7349. case LLM_ARCH_XVERSE:
  7350. {
  7351. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7352. {
  7353. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7354. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7355. }
  7356. for (int i = 0; i < n_layer; ++i) {
  7357. ggml_context * ctx_layer = ctx_for_layer(i);
  7358. ggml_context * ctx_split = ctx_for_layer_split(i);
  7359. auto & layer = model.layers[i];
  7360. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7361. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7362. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7363. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7364. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7365. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7366. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7367. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7368. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7369. }
  7370. } break;
  7371. case LLM_ARCH_COMMAND_R:
  7372. {
  7373. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7374. // output
  7375. {
  7376. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7377. // init output from the input tok embed
  7378. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7379. }
  7380. for (int i = 0; i < n_layer; ++i) {
  7381. ggml_context * ctx_layer = ctx_for_layer(i);
  7382. ggml_context * ctx_split = ctx_for_layer_split(i);
  7383. auto & layer = model.layers[i];
  7384. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7385. if (n_layer >= 64){
  7386. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k, n_head});
  7387. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k, n_head_kv});
  7388. }
  7389. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7390. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7391. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7392. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7393. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7394. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7395. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7396. }
  7397. } break;
  7398. case LLM_ARCH_OLMO: // adapted from LLM_ARCH_LLAMA with norm params removed
  7399. {
  7400. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7401. // output
  7402. {
  7403. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7404. // if output is NULL, init from the input tok embed
  7405. if (model.output == NULL) {
  7406. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7407. }
  7408. }
  7409. for (int i = 0; i < n_layer; ++i) {
  7410. ggml_context * ctx_split = ctx_for_layer_split(i);
  7411. auto & layer = model.layers[i];
  7412. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7413. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7414. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7415. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7416. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7417. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7418. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7419. }
  7420. } break;
  7421. case LLM_ARCH_OLMOE:
  7422. {
  7423. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7424. // output
  7425. {
  7426. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7427. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7428. }
  7429. for (int i = 0; i < n_layer; ++i) {
  7430. ggml_context * ctx_layer = ctx_for_layer(i);
  7431. ggml_context * ctx_split = ctx_for_layer_split(i);
  7432. auto & layer = model.layers[i];
  7433. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7434. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7435. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7436. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7437. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7438. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd});
  7439. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd});
  7440. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7441. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  7442. GGML_ASSERT(n_expert > 0);
  7443. GGML_ASSERT(n_expert_used > 0);
  7444. // MoE branch
  7445. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  7446. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff, n_embd, n_expert});
  7447. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  7448. }
  7449. } break;
  7450. case LLM_ARCH_OPENELM:
  7451. {
  7452. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7453. // output
  7454. {
  7455. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7456. // init output from the input tok embed
  7457. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7458. }
  7459. for (int i = 0; i < n_layer; ++i) {
  7460. const int64_t n_head = hparams.n_head(i);
  7461. const int64_t n_head_qkv = 2*hparams.n_head_kv(i) + n_head;
  7462. const int64_t n_ff = hparams.n_ff(i);
  7463. ggml_context * ctx_layer = ctx_for_layer(i);
  7464. ggml_context * ctx_split = ctx_for_layer_split(i);
  7465. auto & layer = model.layers[i];
  7466. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7467. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_head_qkv*n_embd_head_k});
  7468. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k});
  7469. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k});
  7470. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_head*n_embd_head_k, n_embd});
  7471. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7472. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7473. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  7474. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7475. }
  7476. } break;
  7477. case LLM_ARCH_GPTNEOX:
  7478. {
  7479. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7480. // output
  7481. {
  7482. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7483. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7484. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7485. }
  7486. for (int i = 0; i < n_layer; ++i) {
  7487. ggml_context * ctx_layer = ctx_for_layer(i);
  7488. ggml_context * ctx_split = ctx_for_layer_split(i);
  7489. auto & layer = model.layers[i];
  7490. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7491. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7492. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  7493. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  7494. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7495. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  7496. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7497. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  7498. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  7499. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  7500. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7501. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  7502. }
  7503. } break;
  7504. case LLM_ARCH_ARCTIC:
  7505. {
  7506. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7507. // output
  7508. {
  7509. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7510. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7511. // if output is NULL, init from the input tok embed
  7512. if (model.output == NULL) {
  7513. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7514. }
  7515. }
  7516. for (int i = 0; i < n_layer; ++i) {
  7517. ggml_context * ctx_layer = ctx_for_layer(i);
  7518. ggml_context * ctx_split = ctx_for_layer_split(i);
  7519. auto & layer = model.layers[i];
  7520. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7521. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7522. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7523. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7524. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7525. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7526. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_embd});
  7527. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_embd, n_embd});
  7528. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_embd});
  7529. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  7530. layer.ffn_norm_exps = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM_EXPS, "weight", i), {n_embd});
  7531. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, false);
  7532. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  7533. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  7534. }
  7535. } break;
  7536. case LLM_ARCH_DEEPSEEK2:
  7537. {
  7538. const bool is_lite = (hparams.n_layer == 27);
  7539. const int64_t n_embd_head_qk_rope = hparams.n_rot;
  7540. const int64_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  7541. const int64_t q_lora_rank = hparams.n_lora_q;
  7542. const int64_t kv_lora_rank = hparams.n_lora_kv;
  7543. const int64_t n_ff_exp = hparams.n_ff_exp;
  7544. const int64_t n_expert_shared = hparams.n_expert_shared;
  7545. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7546. // output
  7547. {
  7548. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7549. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7550. }
  7551. for (int i = 0; i < n_layer; ++i) {
  7552. ggml_context * ctx_layer = ctx_for_layer(i);
  7553. ggml_context * ctx_split = ctx_for_layer_split(i);
  7554. auto & layer = model.layers[i];
  7555. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7556. if (!is_lite) {
  7557. layer.attn_q_a_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_A_NORM, "weight", i), {q_lora_rank});
  7558. }
  7559. layer.attn_kv_a_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_KV_A_NORM, "weight", i), {kv_lora_rank});
  7560. if (!is_lite) {
  7561. layer.wq_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q_A, "weight", i), {n_embd, q_lora_rank});
  7562. layer.wq_b = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q_B, "weight", i), {q_lora_rank, n_head * n_embd_head_k});
  7563. } else {
  7564. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  7565. }
  7566. layer.wkv_a_mqa = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_KV_A_MQA, "weight", i), {n_embd, kv_lora_rank + (n_embd_head_qk_rope)});
  7567. layer.wkv_b = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_KV_B, "weight", i), {kv_lora_rank, n_head * (n_embd_head_qk_nope + n_embd_head_v)});
  7568. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_head * ( n_embd_head_v), n_embd});
  7569. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7570. if (i < (int) hparams.n_layer_dense_lead) {
  7571. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7572. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7573. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7574. } else {
  7575. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  7576. GGML_ASSERT(n_expert > 0);
  7577. GGML_ASSERT(n_expert_used > 0);
  7578. // MoE branch
  7579. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  7580. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert});
  7581. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  7582. // Shared expert branch
  7583. layer.ffn_gate_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), {n_embd, n_ff_exp * n_expert_shared});
  7584. layer.ffn_down_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), { n_ff_exp * n_expert_shared, n_embd});
  7585. layer.ffn_up_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), {n_embd, n_ff_exp * n_expert_shared});
  7586. }
  7587. }
  7588. } break;
  7589. case LLM_ARCH_BITNET:
  7590. {
  7591. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7592. // output
  7593. {
  7594. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7595. }
  7596. for (int i = 0; i < n_layer; ++i) {
  7597. ggml_context * ctx_layer = ctx_for_layer(i);
  7598. ggml_context * ctx_split = ctx_for_layer_split(i);
  7599. auto & layer = model.layers[i];
  7600. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7601. layer.attn_sub_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_SUB_NORM, "weight", i), {n_embd});
  7602. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7603. layer.wq_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7604. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7605. layer.wk_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7606. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7607. layer.wv_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7608. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7609. layer.wo_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7610. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7611. layer.ffn_sub_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_SUB_NORM, "weight", i), {n_ff});
  7612. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7613. layer.ffn_gate_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7614. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  7615. layer.ffn_down_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7616. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7617. layer.ffn_up_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7618. }
  7619. } break;
  7620. case LLM_ARCH_T5:
  7621. {
  7622. const auto n_rel_attn_bkts = hparams.n_rel_attn_bkts;
  7623. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7624. // output
  7625. {
  7626. model.output_norm_enc = ml.create_tensor(ctx_output, tn(LLM_TENSOR_ENC_OUTPUT_NORM, "weight"), {n_embd});
  7627. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_DEC_OUTPUT_NORM, "weight"), {n_embd});
  7628. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7629. // if output is NULL, init from the input tok embed
  7630. if (model.output == NULL) {
  7631. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7632. }
  7633. }
  7634. for (int i = 0; i < n_layer; ++i) {
  7635. ggml_context * ctx_layer = ctx_for_layer(i);
  7636. ggml_context * ctx_split = ctx_for_layer_split(i);
  7637. auto & layer = model.layers[i];
  7638. layer.attn_norm_enc = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ENC_ATTN_NORM, "weight", i), {n_embd});
  7639. layer.attn_rel_b_enc = ml.create_tensor(ctx_input, tn(LLM_TENSOR_ENC_ATTN_REL_B, "weight", i), {n_head, n_rel_attn_bkts}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7640. layer.wq_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  7641. layer.wk_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  7642. layer.wv_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  7643. layer.wo_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd});
  7644. layer.ffn_norm_enc = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ENC_FFN_NORM, "weight", i), {n_embd});
  7645. layer.ffn_gate_enc = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ENC_FFN_GATE, "weight", i), {n_embd, n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7646. layer.ffn_down_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7647. layer.ffn_up_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_FFN_UP, "weight", i), {n_embd, n_ff});
  7648. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_DEC_ATTN_NORM, "weight", i), {n_embd});
  7649. layer.attn_rel_b = ml.create_tensor(ctx_input, tn(LLM_TENSOR_DEC_ATTN_REL_B, "weight", i), {n_head, n_rel_attn_bkts}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7650. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  7651. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  7652. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  7653. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd});
  7654. layer.attn_norm_cross = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_DEC_CROSS_ATTN_NORM, "weight", i), {n_embd});
  7655. // this tensor seems to be unused in HF transformers implementation
  7656. layer.attn_rel_b_cross = ml.create_tensor(ctx_input, tn(LLM_TENSOR_DEC_CROSS_ATTN_REL_B, "weight", i), {n_head, n_rel_attn_bkts}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7657. layer.wq_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  7658. layer.wk_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  7659. layer.wv_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  7660. layer.wo_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd});
  7661. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_DEC_FFN_NORM, "weight", i), {n_embd});
  7662. layer.ffn_gate = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_DEC_FFN_GATE, "weight", i), {n_embd, n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7663. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7664. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_FFN_UP, "weight", i), {n_embd, n_ff});
  7665. }
  7666. } break;
  7667. case LLM_ARCH_T5ENCODER:
  7668. {
  7669. const auto n_rel_attn_bkts = hparams.n_rel_attn_bkts;
  7670. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7671. // output
  7672. {
  7673. model.output_norm_enc = ml.create_tensor(ctx_output, tn(LLM_TENSOR_ENC_OUTPUT_NORM, "weight"), {n_embd});
  7674. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7675. // if output is NULL, init from the input tok embed
  7676. if (model.output == NULL) {
  7677. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7678. }
  7679. }
  7680. for (int i = 0; i < n_layer; ++i) {
  7681. ggml_context * ctx_layer = ctx_for_layer(i);
  7682. ggml_context * ctx_split = ctx_for_layer_split(i);
  7683. auto & layer = model.layers[i];
  7684. layer.attn_norm_enc = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ENC_ATTN_NORM, "weight", i), {n_embd});
  7685. layer.attn_rel_b_enc = ml.create_tensor(ctx_input, tn(LLM_TENSOR_ENC_ATTN_REL_B, "weight", i), {n_head, n_rel_attn_bkts}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7686. layer.wq_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  7687. layer.wk_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  7688. layer.wv_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  7689. layer.wo_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd});
  7690. layer.ffn_norm_enc = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ENC_FFN_NORM, "weight", i), {n_embd});
  7691. layer.ffn_gate_enc = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ENC_FFN_GATE, "weight", i), {n_embd, n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7692. layer.ffn_down_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7693. layer.ffn_up_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_FFN_UP, "weight", i), {n_embd, n_ff});
  7694. }
  7695. } break;
  7696. case LLM_ARCH_JAIS:
  7697. {
  7698. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7699. // Output
  7700. {
  7701. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7702. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7703. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7704. }
  7705. for (int i = 0; i < n_layer; ++i) {
  7706. ggml_context * ctx_layer = ctx_for_layer(i);
  7707. ggml_context * ctx_split = ctx_for_layer_split(i);
  7708. auto & layer = model.layers[i];
  7709. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7710. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7711. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  7712. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  7713. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7714. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  7715. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7716. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  7717. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  7718. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  7719. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7720. layer.ffn_gate_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE, "bias", i), {n_ff});
  7721. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7722. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  7723. }
  7724. } break;
  7725. case LLM_ARCH_CHATGLM:
  7726. {
  7727. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7728. // output
  7729. {
  7730. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7731. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7732. }
  7733. for (int i = 0; i < n_layer; ++i) {
  7734. ggml_context * ctx_layer = ctx_for_layer(i);
  7735. ggml_context * ctx_split = ctx_for_layer_split(i);
  7736. auto & layer = model.layers[i];
  7737. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7738. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  7739. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  7740. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7741. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7742. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff * 2});
  7743. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  7744. }
  7745. } break;
  7746. case LLM_ARCH_NEMOTRON:
  7747. {
  7748. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7749. // output
  7750. {
  7751. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7752. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7753. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7754. }
  7755. for (int i = 0; i < n_layer; ++i) {
  7756. ggml_context * ctx_layer = ctx_for_layer(i);
  7757. ggml_context * ctx_split = ctx_for_layer_split(i);
  7758. auto & layer = model.layers[i];
  7759. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7760. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7761. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7762. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7763. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7764. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7765. // optional bias tensors
  7766. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7767. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7768. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7769. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7770. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7771. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  7772. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7773. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7774. // optional MLP bias
  7775. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7776. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7777. }
  7778. } break;
  7779. case LLM_ARCH_EXAONE:
  7780. {
  7781. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7782. // output
  7783. {
  7784. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7785. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7786. }
  7787. for (int i = 0; i < n_layer; ++i) {
  7788. ggml_context * ctx_layer = ctx_for_layer(i);
  7789. ggml_context * ctx_split = ctx_for_layer_split(i);
  7790. auto & layer = model.layers[i];
  7791. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7792. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  7793. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  7794. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  7795. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  7796. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7797. layer.rope_freqs = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ROPE_FREQS, "weight"), {n_rot/2}, llama_model_loader::TENSOR_NOT_REQUIRED | (i != 0 ? llama_model_loader::TENSOR_DUPLICATED : 0));
  7798. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7799. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7800. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7801. }
  7802. } break;
  7803. case LLM_ARCH_RWKV6:
  7804. {
  7805. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7806. // Block 0, LN0
  7807. model.tok_norm = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  7808. model.tok_norm_b = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  7809. // output
  7810. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7811. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7812. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7813. const int time_mix_extra_dim = hparams.time_mix_extra_dim;
  7814. const int time_decay_extra_dim = hparams.time_decay_extra_dim;
  7815. const int head_size = hparams.wkv_head_size;
  7816. const int attn_hidden_size = n_embd;
  7817. const int ffn_size = hparams.n_ff_arr[0];
  7818. for (int i = 0; i < n_layer; ++i) {
  7819. ggml_context * ctx_layer = ctx_for_layer(i);
  7820. auto & layer = model.layers[i];
  7821. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7822. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7823. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd});
  7824. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd});
  7825. layer.time_mix_w1 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_W1, "weight", i), {n_embd, time_mix_extra_dim * 5});
  7826. layer.time_mix_w2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_W2, "weight", i), {time_mix_extra_dim, n_embd, 5});
  7827. layer.time_mix_lerp_x = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_LERP_X, "weight", i), {n_embd, 1, 1});
  7828. layer.time_mix_lerp_w = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_LERP_W, "weight", i), {n_embd, 1, 1});
  7829. layer.time_mix_lerp_k = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_LERP_K, "weight", i), {n_embd, 1, 1});
  7830. layer.time_mix_lerp_v = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_LERP_V, "weight", i), {n_embd, 1, 1});
  7831. layer.time_mix_lerp_r = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_LERP_R, "weight", i), {n_embd, 1, 1});
  7832. layer.time_mix_lerp_g = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_LERP_G, "weight", i), {n_embd, 1, 1});
  7833. layer.time_mix_first = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_FIRST, "weight", i), {head_size, n_embd / head_size});
  7834. layer.time_mix_decay = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_DECAY, "weight", i), {n_embd});
  7835. layer.time_mix_decay_w1 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_DECAY_W1, "weight", i), {n_embd, time_decay_extra_dim});
  7836. layer.time_mix_decay_w2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_DECAY_W2, "weight", i), {time_decay_extra_dim, attn_hidden_size});
  7837. layer.time_mix_key = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_KEY, "weight", i), {attn_hidden_size, n_embd});
  7838. layer.time_mix_value = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_VALUE, "weight", i), {attn_hidden_size, n_embd});
  7839. layer.time_mix_receptance = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_RECEPTANCE, "weight", i), {attn_hidden_size, n_embd});
  7840. layer.time_mix_gate = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_GATE, "weight", i), {attn_hidden_size, n_embd});
  7841. layer.time_mix_ln = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_LN, "weight", i), {n_embd});
  7842. layer.time_mix_ln_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_LN, "bias", i), {n_embd});
  7843. layer.time_mix_output = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_OUTPUT, "weight", i), {n_embd, attn_hidden_size});
  7844. layer.channel_mix_lerp_k = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_CHANNEL_MIX_LERP_K, "weight", i), {n_embd, 1, 1});
  7845. layer.channel_mix_lerp_r = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_CHANNEL_MIX_LERP_R, "weight", i), {n_embd, 1, 1});
  7846. layer.channel_mix_key = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_CHANNEL_MIX_KEY, "weight", i), {n_embd, ffn_size});
  7847. layer.channel_mix_value = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_CHANNEL_MIX_VALUE, "weight", i), {ffn_size, n_embd});
  7848. layer.channel_mix_receptance = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_CHANNEL_MIX_RECEPTANCE, "weight", i), {n_embd, n_embd});
  7849. }
  7850. } break;
  7851. case LLM_ARCH_CHAMELEON:
  7852. {
  7853. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7854. // output
  7855. {
  7856. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7857. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7858. // if output is NULL, init from the input tok embed
  7859. if (model.output == NULL) {
  7860. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7861. }
  7862. }
  7863. for (int i = 0; i < n_layer; ++i) {
  7864. ggml_context * ctx_layer = ctx_for_layer(i);
  7865. ggml_context * ctx_split = ctx_for_layer_split(i);
  7866. auto & layer = model.layers[i];
  7867. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7868. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k, n_head});
  7869. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k, n_head_kv});
  7870. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {n_embd_head_k, n_head}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7871. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {n_embd_head_k, n_head_kv}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7872. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7873. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7874. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7875. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7876. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7877. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7878. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7879. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7880. }
  7881. } break;
  7882. case LLM_ARCH_SOLAR:
  7883. {
  7884. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7885. // output
  7886. {
  7887. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7888. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7889. }
  7890. for (int i = 0; i < n_layer; ++i) {
  7891. ggml_context * ctx_layer = ctx_for_layer(i);
  7892. ggml_context * ctx_split = ctx_for_layer_split(i);
  7893. auto & layer = model.layers[i];
  7894. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7895. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  7896. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  7897. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  7898. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  7899. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7900. layer.bskcn_tv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_BSKCN_TV, "weight"), {2}, llama_model_loader::TENSOR_NOT_REQUIRED | (i != 0 ? llama_model_loader::TENSOR_DUPLICATED : 0));
  7901. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7902. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7903. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7904. }
  7905. } break;
  7906. default:
  7907. throw std::runtime_error("unknown architecture");
  7908. }
  7909. }
  7910. ml.done_getting_tensors();
  7911. ml.init_mappings(true, use_mlock ? &model.mlock_mmaps : nullptr);
  7912. model.mappings.reserve(ml.mappings.size());
  7913. // create the backend buffers
  7914. std::vector<std::pair<ggml_context *, llama_buf_map>> ctx_bufs;
  7915. ctx_bufs.reserve(ctx_map.size());
  7916. // Ensure we have enough capacity for the maximum backend buffer we will potentially create
  7917. size_t n_max_backend_buffer = ctx_map.size() * ml.files.size();
  7918. model.bufs.reserve(n_max_backend_buffer);
  7919. for (auto & it : ctx_map) {
  7920. ggml_backend_buffer_type_t buft = it.first;
  7921. ggml_context * ctx = it.second;
  7922. llama_buf_map bufs;
  7923. bufs.reserve(n_max_backend_buffer);
  7924. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  7925. // 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
  7926. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  7927. if (ml.use_mmap && use_mmap_buffer && buft == llama_default_buffer_type_cpu(true)) {
  7928. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  7929. void * addr = nullptr;
  7930. size_t first, last;
  7931. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  7932. if (first >= last) {
  7933. continue;
  7934. }
  7935. ggml_backend_buffer_t buf = ggml_backend_cpu_buffer_from_ptr((char *) addr + first, last - first);
  7936. if (buf == nullptr) {
  7937. throw std::runtime_error("unable to allocate backend CPU buffer");
  7938. }
  7939. model.bufs.push_back(buf);
  7940. bufs.emplace(idx, buf);
  7941. #ifdef GGML_USE_CUDA
  7942. if (n_layer >= n_gpu_layers) {
  7943. ggml_backend_cuda_register_host_buffer(
  7944. ggml_backend_buffer_get_base(buf),
  7945. ggml_backend_buffer_get_size(buf));
  7946. }
  7947. #endif
  7948. }
  7949. }
  7950. #ifdef GGML_USE_METAL
  7951. else if (ml.use_mmap && use_mmap_buffer && buft == ggml_backend_metal_buffer_type()) {
  7952. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  7953. const size_t max_size = ggml_get_max_tensor_size(ctx);
  7954. void * addr = nullptr;
  7955. size_t first, last;
  7956. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  7957. if (first >= last) {
  7958. continue;
  7959. }
  7960. ggml_backend_buffer_t buf = ggml_backend_metal_buffer_from_ptr((char *) addr + first, last - first, max_size);
  7961. if (buf == nullptr) {
  7962. throw std::runtime_error("unable to allocate backend metal buffer");
  7963. }
  7964. model.bufs.push_back(buf);
  7965. bufs.emplace(idx, buf);
  7966. }
  7967. }
  7968. #endif
  7969. else {
  7970. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  7971. if (buf == nullptr) {
  7972. throw std::runtime_error("unable to allocate backend buffer");
  7973. }
  7974. model.bufs.push_back(buf);
  7975. if (use_mlock && ggml_backend_buffer_is_host(buf)) {
  7976. model.mlock_bufs.emplace_back(new llama_mlock);
  7977. auto & mlock_buf = model.mlock_bufs.back();
  7978. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  7979. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  7980. }
  7981. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  7982. bufs.emplace(idx, buf);
  7983. }
  7984. }
  7985. if (bufs.empty()) {
  7986. throw std::runtime_error("failed to allocate buffer");
  7987. }
  7988. for (auto & buf : bufs) {
  7989. // indicate that this buffer contains weights
  7990. // 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
  7991. ggml_backend_buffer_set_usage(buf.second, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  7992. }
  7993. ctx_bufs.emplace_back(ctx, bufs);
  7994. }
  7995. if (llama_supports_gpu_offload()) {
  7996. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  7997. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  7998. if (n_gpu_layers > (int) hparams.n_layer) {
  7999. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  8000. }
  8001. const int max_backend_supported_layers = hparams.n_layer + 1;
  8002. const int max_offloadable_layers = hparams.n_layer + 1;
  8003. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  8004. }
  8005. // print memory requirements
  8006. for (ggml_backend_buffer_t buf : model.bufs) {
  8007. LLAMA_LOG_INFO("%s: %10s buffer size = %8.2f MiB\n", __func__, ggml_backend_buffer_name(buf), ggml_backend_buffer_get_size(buf) / 1024.0 / 1024.0);
  8008. }
  8009. // populate tensors_by_name
  8010. for (ggml_context * ctx : model.ctxs) {
  8011. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  8012. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  8013. }
  8014. }
  8015. // load tensor data
  8016. for (auto & it : ctx_bufs) {
  8017. ggml_context * ctx = it.first;
  8018. auto & bufs = it.second;
  8019. if (!ml.load_all_data(ctx, bufs, use_mlock ? &model.mlock_mmaps : NULL, progress_callback, progress_callback_user_data)) {
  8020. return false;
  8021. }
  8022. }
  8023. if (use_mmap_buffer) {
  8024. for (auto & mapping : ml.mappings) {
  8025. model.mappings.emplace_back(std::move(mapping));
  8026. }
  8027. }
  8028. return true;
  8029. }
  8030. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  8031. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  8032. model.t_start_us = ggml_time_us();
  8033. try {
  8034. llama_model_loader ml(fname, params.use_mmap, params.check_tensors, params.kv_overrides);
  8035. model.hparams.vocab_only = params.vocab_only;
  8036. try {
  8037. llm_load_arch(ml, model);
  8038. } catch(const std::exception & e) {
  8039. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  8040. }
  8041. try {
  8042. llm_load_hparams(ml, model);
  8043. } catch(const std::exception & e) {
  8044. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  8045. }
  8046. try {
  8047. llm_load_vocab(ml, model);
  8048. } catch(const std::exception & e) {
  8049. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  8050. }
  8051. llm_load_print_meta(ml, model);
  8052. if (model.vocab.type != LLAMA_VOCAB_TYPE_NONE &&
  8053. model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  8054. LLAMA_LOG_WARN("%s: vocab mismatch %u !- %zu ...\n", __func__, model.hparams.n_vocab, model.vocab.id_to_token.size());
  8055. }
  8056. if (params.vocab_only) {
  8057. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  8058. return 0;
  8059. }
  8060. #ifdef GGML_USE_KOMPUTE
  8061. if (params.n_gpu_layers > 0 && (
  8062. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  8063. || !(
  8064. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  8065. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  8066. model.ftype == LLAMA_FTYPE_MOSTLY_BF16 ||
  8067. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  8068. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  8069. )
  8070. )) {
  8071. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  8072. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  8073. params.n_gpu_layers = 0;
  8074. }
  8075. #endif
  8076. if (!llm_load_tensors(
  8077. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  8078. params.progress_callback, params.progress_callback_user_data
  8079. )) {
  8080. return -2;
  8081. }
  8082. } catch (const std::exception & err) {
  8083. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  8084. return -1;
  8085. }
  8086. // loading time will be recalculate after the first eval, so
  8087. // we take page faults deferred by mmap() into consideration
  8088. model.t_load_us = ggml_time_us() - model.t_start_us;
  8089. return 0;
  8090. }
  8091. //
  8092. // llm_build
  8093. //
  8094. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  8095. enum llm_ffn_op_type {
  8096. LLM_FFN_SILU,
  8097. LLM_FFN_GELU,
  8098. LLM_FFN_RELU,
  8099. LLM_FFN_RELU_SQR,
  8100. LLM_FFN_SWIGLU,
  8101. };
  8102. enum llm_ffn_gate_type {
  8103. LLM_FFN_SEQ,
  8104. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  8105. };
  8106. enum llm_norm_type {
  8107. LLM_NORM,
  8108. LLM_NORM_RMS,
  8109. };
  8110. static struct ggml_tensor * llm_build_inp_embd(
  8111. struct ggml_context * ctx,
  8112. struct llama_context & lctx,
  8113. const llama_hparams & hparams,
  8114. const llama_ubatch & batch,
  8115. struct ggml_tensor * tok_embd,
  8116. const llm_build_cb & cb) {
  8117. const int64_t n_embd = hparams.n_embd;
  8118. struct ggml_tensor * inpL;
  8119. if (batch.token) {
  8120. lctx.inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  8121. cb(lctx.inp_tokens, "inp_tokens", -1);
  8122. ggml_set_input(lctx.inp_tokens);
  8123. inpL = ggml_get_rows(ctx, tok_embd, lctx.inp_tokens);
  8124. } else {
  8125. lctx.inp_embd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  8126. inpL = lctx.inp_embd;
  8127. ggml_set_input(lctx.inp_embd);
  8128. }
  8129. // For Granite architecture
  8130. if (hparams.f_embedding_scale != 0.0f) {
  8131. inpL = ggml_scale(ctx, inpL, hparams.f_embedding_scale);
  8132. }
  8133. cb(inpL, "inp_embd", -1);
  8134. return inpL;
  8135. }
  8136. static struct ggml_tensor * llm_build_inp_cross_attn_state(
  8137. struct ggml_context * ctx,
  8138. struct llama_context & lctx,
  8139. const llama_hparams & hparams,
  8140. const llm_build_cb & cb) {
  8141. const int64_t n_embd = hparams.n_embd;
  8142. struct ggml_tensor * inpCAS;
  8143. lctx.inp_cross_attn_state = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n_embd, 1601, 4);
  8144. cb(lctx.inp_cross_attn_state, "inp_cross_attn_state", -1);
  8145. ggml_set_input(lctx.inp_cross_attn_state);
  8146. inpCAS = lctx.inp_cross_attn_state;
  8147. return inpCAS;
  8148. }
  8149. static void llm_build_kv_store(
  8150. struct ggml_context * ctx,
  8151. const llama_hparams & hparams,
  8152. const llama_cparams & cparams,
  8153. const llama_kv_cache & kv,
  8154. struct ggml_cgraph * graph,
  8155. struct ggml_tensor * k_cur,
  8156. struct ggml_tensor * v_cur,
  8157. int32_t n_tokens,
  8158. int32_t kv_head,
  8159. const llm_build_cb & cb,
  8160. int64_t il) {
  8161. const int64_t n_ctx = cparams.n_ctx;
  8162. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  8163. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  8164. GGML_ASSERT(kv.size == n_ctx);
  8165. 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);
  8166. cb(k_cache_view, "k_cache_view", il);
  8167. // note: storing RoPE-ed version of K in the KV cache
  8168. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  8169. assert(v_cur->ne[0] == n_embd_v_gqa && v_cur->ne[1] == n_tokens);
  8170. struct ggml_tensor * v_cache_view = nullptr;
  8171. if (cparams.flash_attn) {
  8172. 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);
  8173. } else {
  8174. // note: the V cache is transposed when not using flash attention
  8175. v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  8176. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  8177. (kv_head)*ggml_element_size(kv.v_l[il]));
  8178. v_cur = ggml_transpose(ctx, v_cur);
  8179. }
  8180. cb(v_cache_view, "v_cache_view", il);
  8181. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur, v_cache_view));
  8182. }
  8183. // do mat_mul, while optionally apply lora
  8184. static struct ggml_tensor * llm_build_lora_mm(
  8185. struct llama_context & lctx,
  8186. struct ggml_context * ctx0,
  8187. struct ggml_tensor * w,
  8188. struct ggml_tensor * cur) {
  8189. struct ggml_tensor * res = ggml_mul_mat(ctx0, w, cur);
  8190. for (auto & it : lctx.lora_adapters) {
  8191. struct llama_lora_weight * lora = it.first->get_weight(w);
  8192. if (lora == nullptr) {
  8193. continue;
  8194. }
  8195. const float alpha = it.first->alpha;
  8196. const float rank = (float) lora->b->ne[0];
  8197. const float scale = alpha ? it.second * alpha / rank : it.second;
  8198. struct ggml_tensor * ab_cur = ggml_mul_mat(
  8199. ctx0, lora->b,
  8200. ggml_mul_mat(ctx0, lora->a, cur)
  8201. );
  8202. ab_cur = ggml_scale(ctx0, ab_cur, scale);
  8203. res = ggml_add(ctx0, res, ab_cur);
  8204. }
  8205. return res;
  8206. }
  8207. // do mat_mul_id, while optionally apply lora
  8208. static struct ggml_tensor * llm_build_lora_mm_id(
  8209. struct llama_context & lctx,
  8210. struct ggml_context * ctx0,
  8211. struct ggml_tensor * w, // struct ggml_tensor * as
  8212. struct ggml_tensor * cur, // struct ggml_tensor * b
  8213. struct ggml_tensor * ids) {
  8214. struct ggml_tensor * res = ggml_mul_mat_id(ctx0, w, cur, ids);
  8215. for (auto & it : lctx.lora_adapters) {
  8216. struct llama_lora_weight * lora = it.first->get_weight(w);
  8217. if (lora == nullptr) {
  8218. continue;
  8219. }
  8220. const float alpha = it.first->alpha;
  8221. const float rank = (float) lora->b->ne[0];
  8222. const float scale = alpha ? it.second * alpha / rank : it.second;
  8223. struct ggml_tensor * ab_cur = ggml_mul_mat_id(
  8224. ctx0, lora->b,
  8225. ggml_mul_mat_id(ctx0, lora->a, cur, ids),
  8226. ids
  8227. );
  8228. ab_cur = ggml_scale(ctx0, ab_cur, scale);
  8229. res = ggml_add(ctx0, res, ab_cur);
  8230. }
  8231. return res;
  8232. }
  8233. static struct ggml_tensor * llm_build_norm(
  8234. struct ggml_context * ctx,
  8235. struct ggml_tensor * cur,
  8236. const llama_hparams & hparams,
  8237. struct ggml_tensor * mw,
  8238. struct ggml_tensor * mb,
  8239. llm_norm_type type,
  8240. const llm_build_cb & cb,
  8241. int il) {
  8242. switch (type) {
  8243. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  8244. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  8245. }
  8246. if (mw || mb) {
  8247. cb(cur, "norm", il);
  8248. }
  8249. if (mw) {
  8250. cur = ggml_mul(ctx, cur, mw);
  8251. if (mb) {
  8252. cb(cur, "norm_w", il);
  8253. }
  8254. }
  8255. if (mb) {
  8256. cur = ggml_add(ctx, cur, mb);
  8257. }
  8258. return cur;
  8259. }
  8260. static struct ggml_tensor * llm_build_ffn(
  8261. struct ggml_context * ctx,
  8262. struct llama_context & lctx,
  8263. struct ggml_tensor * cur,
  8264. struct ggml_tensor * up,
  8265. struct ggml_tensor * up_b,
  8266. struct ggml_tensor * up_s,
  8267. struct ggml_tensor * gate,
  8268. struct ggml_tensor * gate_b,
  8269. struct ggml_tensor * gate_s,
  8270. struct ggml_tensor * down,
  8271. struct ggml_tensor * down_b,
  8272. struct ggml_tensor * down_s,
  8273. struct ggml_tensor * act_scales,
  8274. llm_ffn_op_type type_op,
  8275. llm_ffn_gate_type type_gate,
  8276. const llm_build_cb & cb,
  8277. int il) {
  8278. struct ggml_tensor * tmp = up ? llm_build_lora_mm(lctx, ctx, up, cur) : cur;
  8279. cb(tmp, "ffn_up", il);
  8280. if (up_b) {
  8281. tmp = ggml_add(ctx, tmp, up_b);
  8282. cb(tmp, "ffn_up_b", il);
  8283. }
  8284. if (up_s) {
  8285. tmp = ggml_mul(ctx, tmp, up_s);
  8286. cb(tmp, "ffn_up_s", il);
  8287. }
  8288. if (gate) {
  8289. switch (type_gate) {
  8290. case LLM_FFN_SEQ:
  8291. {
  8292. cur = llm_build_lora_mm(lctx, ctx, gate, tmp);
  8293. cb(cur, "ffn_gate", il);
  8294. } break;
  8295. case LLM_FFN_PAR:
  8296. {
  8297. cur = llm_build_lora_mm(lctx, ctx, gate, cur);
  8298. cb(cur, "ffn_gate", il);
  8299. } break;
  8300. }
  8301. if (gate_b) {
  8302. cur = ggml_add(ctx, cur, gate_b);
  8303. cb(cur, "ffn_gate_b", il);
  8304. }
  8305. if (gate_s) {
  8306. cur = ggml_mul(ctx, cur, gate_s);
  8307. cb(cur, "ffn_gate_s", il);
  8308. }
  8309. } else {
  8310. cur = tmp;
  8311. }
  8312. switch (type_op) {
  8313. case LLM_FFN_SILU:
  8314. {
  8315. cur = ggml_silu(ctx, cur);
  8316. cb(cur, "ffn_silu", il);
  8317. } break;
  8318. case LLM_FFN_GELU:
  8319. {
  8320. cur = ggml_gelu(ctx, cur);
  8321. cb(cur, "ffn_gelu", il);
  8322. if (act_scales != NULL) {
  8323. cur = ggml_div(ctx, cur, act_scales);
  8324. cb(cur, "ffn_act", il);
  8325. }
  8326. } break;
  8327. case LLM_FFN_RELU:
  8328. {
  8329. cur = ggml_relu(ctx, cur);
  8330. cb(cur, "ffn_relu", il);
  8331. } break;
  8332. case LLM_FFN_RELU_SQR:
  8333. {
  8334. cur = ggml_relu(ctx, cur);
  8335. cb(cur, "ffn_relu", il);
  8336. cur = ggml_sqr(ctx, cur);
  8337. cb(cur, "ffn_sqr(relu)", il);
  8338. } break;
  8339. case LLM_FFN_SWIGLU:
  8340. {
  8341. // Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf
  8342. int64_t split_point = cur->ne[0] / 2;
  8343. struct ggml_tensor * x0 = ggml_cont(ctx, ggml_view_2d(ctx, cur, split_point, cur->ne[1], cur->nb[1], 0));
  8344. 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)));
  8345. x0 = ggml_silu(ctx, x0);
  8346. cb(cur, "ffn_silu", il);
  8347. cur = ggml_mul(ctx, x0, x1);
  8348. cb(cur, "ffn_mul", il);
  8349. } break;
  8350. }
  8351. if (type_gate == LLM_FFN_PAR) {
  8352. cur = ggml_mul(ctx, cur, tmp);
  8353. cb(cur, "ffn_gate_par", il);
  8354. }
  8355. if (down) {
  8356. cur = llm_build_lora_mm(lctx, ctx, down, cur);
  8357. }
  8358. if (down_b) {
  8359. cb(cur, "ffn_down", il);
  8360. }
  8361. if (down_b) {
  8362. cur = ggml_add(ctx, cur, down_b);
  8363. }
  8364. if (down_s) {
  8365. cur = ggml_mul(ctx, cur, down_s);
  8366. cb(cur, "ffn_down_s", il);
  8367. }
  8368. return cur;
  8369. }
  8370. static struct ggml_tensor * llm_build_moe_ffn(
  8371. struct ggml_context * ctx,
  8372. struct llama_context & lctx,
  8373. struct ggml_tensor * cur,
  8374. struct ggml_tensor * gate_inp,
  8375. struct ggml_tensor * up_exps,
  8376. struct ggml_tensor * gate_exps,
  8377. struct ggml_tensor * down_exps,
  8378. int64_t n_expert,
  8379. int64_t n_expert_used,
  8380. llm_ffn_op_type type_op,
  8381. bool norm_w,
  8382. bool scale_w,
  8383. float w_scale,
  8384. const llm_build_cb & cb,
  8385. int il) {
  8386. int64_t n_embd = cur->ne[0];
  8387. int64_t n_tokens = cur->ne[1];
  8388. ggml_tensor * logits = llm_build_lora_mm(lctx, ctx, gate_inp, cur); // [n_expert, n_tokens]
  8389. cb(logits, "ffn_moe_logits", il);
  8390. ggml_tensor * probs = ggml_soft_max(ctx, logits); // [n_expert, n_tokens]
  8391. cb(probs, "ffn_moe_probs", il);
  8392. // select experts
  8393. ggml_tensor * selected_experts = ggml_top_k(ctx, probs, n_expert_used); // [n_expert_used, n_tokens]
  8394. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  8395. cb(selected_experts, "ffn_moe_topk", il);
  8396. ggml_tensor * weights = ggml_get_rows(ctx,
  8397. ggml_reshape_3d(ctx, probs, 1, n_expert, n_tokens), selected_experts); // [1, n_expert_used, n_tokens]
  8398. cb(weights, "ffn_moe_weights", il);
  8399. if (norm_w) {
  8400. weights = ggml_reshape_2d(ctx, weights, n_expert_used, n_tokens);
  8401. ggml_tensor * weights_sum = ggml_sum_rows(ctx, weights); // [1, n_tokens]
  8402. cb(weights_sum, "ffn_moe_weights_sum", il);
  8403. weights = ggml_div(ctx, weights, weights_sum); // [n_expert_used, n_tokens]
  8404. cb(weights, "ffn_moe_weights_norm", il);
  8405. weights = ggml_reshape_3d(ctx, weights, 1, n_expert_used, n_tokens);
  8406. }
  8407. if (scale_w) {
  8408. weights = ggml_scale(ctx, weights, w_scale);
  8409. cb(weights, "ffn_moe_weights_scaled", il);
  8410. }
  8411. cur = ggml_reshape_3d(ctx, cur, n_embd, 1, n_tokens);
  8412. ggml_tensor * up = llm_build_lora_mm_id(lctx, ctx, up_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  8413. cb(up, "ffn_moe_up", il);
  8414. ggml_tensor * gate = llm_build_lora_mm_id(lctx, ctx, gate_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  8415. cb(gate, "ffn_moe_gate", il);
  8416. switch (type_op) {
  8417. case LLM_FFN_SILU:
  8418. {
  8419. gate = ggml_silu(ctx, gate);
  8420. cb(gate, "ffn_moe_silu", il);
  8421. } break;
  8422. case LLM_FFN_GELU:
  8423. {
  8424. gate = ggml_gelu(ctx, gate);
  8425. cb(gate, "ffn_moe_gelu", il);
  8426. } break;
  8427. default:
  8428. GGML_ABORT("fatal error");
  8429. }
  8430. ggml_tensor * par = ggml_mul(ctx, up, gate); // [n_ff, n_expert_used, n_tokens]
  8431. cb(par, "ffn_moe_gate_par", il);
  8432. ggml_tensor * experts = llm_build_lora_mm_id(lctx, ctx, down_exps, par, selected_experts); // [n_embd, n_expert_used, n_tokens]
  8433. cb(experts, "ffn_moe_down", il);
  8434. experts = ggml_mul(ctx, experts, weights);
  8435. // aggregate experts
  8436. ggml_tensor * moe_out = nullptr;
  8437. for (int i = 0; i < n_expert_used; ++i) {
  8438. ggml_tensor * cur_expert = ggml_view_2d(ctx, experts, n_embd, n_tokens,
  8439. experts->nb[2], i*experts->nb[1]);
  8440. if (i == 0) {
  8441. moe_out = cur_expert;
  8442. } else {
  8443. moe_out = ggml_add(ctx, moe_out, cur_expert);
  8444. }
  8445. }
  8446. if (n_expert_used == 1) {
  8447. // avoid returning a non-contiguous tensor
  8448. moe_out = ggml_cont(ctx, moe_out);
  8449. }
  8450. return moe_out;
  8451. }
  8452. static struct ggml_tensor * llm_build_kqv(
  8453. struct ggml_context * ctx,
  8454. struct llama_context & lctx,
  8455. const llama_kv_cache & kv,
  8456. struct ggml_cgraph * graph,
  8457. struct ggml_tensor * wo,
  8458. struct ggml_tensor * wo_b,
  8459. struct ggml_tensor * q_cur,
  8460. struct ggml_tensor * kq_mask,
  8461. int32_t n_tokens,
  8462. int32_t n_kv,
  8463. float kq_scale,
  8464. const llm_build_cb & cb,
  8465. int il) {
  8466. const llama_model & model = lctx.model;
  8467. const llama_hparams & hparams = lctx.model.hparams;
  8468. const llama_cparams & cparams = lctx.cparams;
  8469. const int64_t n_ctx = cparams.n_ctx;
  8470. const int64_t n_head = hparams.n_head(il);
  8471. const int64_t n_head_kv = hparams.n_head_kv(il);
  8472. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  8473. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  8474. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  8475. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  8476. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  8477. cb(q, "q", il);
  8478. struct ggml_tensor * k =
  8479. ggml_view_3d(ctx, kv.k_l[il],
  8480. n_embd_head_k, n_kv, n_head_kv,
  8481. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  8482. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  8483. 0);
  8484. cb(k, "k", il);
  8485. struct ggml_tensor * cur;
  8486. if (cparams.flash_attn) {
  8487. GGML_UNUSED(model);
  8488. GGML_UNUSED(n_ctx);
  8489. // split cached v into n_head heads (not transposed)
  8490. struct ggml_tensor * v =
  8491. ggml_view_3d(ctx, kv.v_l[il],
  8492. n_embd_head_v, n_kv, n_head_kv,
  8493. ggml_row_size(kv.v_l[il]->type, n_embd_v_gqa),
  8494. ggml_row_size(kv.v_l[il]->type, n_embd_head_v),
  8495. 0);
  8496. cb(v, "v", il);
  8497. cur = ggml_flash_attn_ext(ctx, q, k, v, kq_mask, kq_scale, hparams.f_max_alibi_bias,
  8498. hparams.attn_soft_cap ? hparams.f_attn_logit_softcapping : 0.0f);
  8499. if (model.arch == LLM_ARCH_PHI2 || model.arch == LLM_ARCH_PHI3 || model.arch == LLM_ARCH_GPTNEOX || model.arch == LLM_ARCH_GEMMA2) {
  8500. ggml_flash_attn_ext_set_prec(cur, GGML_PREC_F32);
  8501. }
  8502. cur = ggml_reshape_2d(ctx, cur, n_embd_head_v*n_head, n_tokens);
  8503. } else {
  8504. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  8505. cb(kq, "kq", il);
  8506. if (model.arch == LLM_ARCH_PHI2 || model.arch == LLM_ARCH_PHI3 || model.arch == LLM_ARCH_GPTNEOX || model.arch == LLM_ARCH_QWEN2 || model.arch == LLM_ARCH_NEMOTRON || model.arch == LLM_ARCH_CHATGLM) {
  8507. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  8508. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  8509. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  8510. }
  8511. if (model.arch == LLM_ARCH_GROK) {
  8512. // need to do the following:
  8513. // multiply by attn_output_multiplyer of 0.08838834764831845
  8514. // and then :
  8515. // kq = 30 * tanh(kq / 30)
  8516. // before the softmax below
  8517. //try from phi2
  8518. //ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  8519. kq = ggml_tanh(ctx, ggml_scale(ctx, kq, 0.08838834764831845f/30.0f));
  8520. kq = ggml_scale(ctx, kq, 30);
  8521. }
  8522. if (hparams.attn_soft_cap) {
  8523. kq = ggml_scale(ctx, kq, 1.0f / hparams.f_attn_logit_softcapping);
  8524. kq = ggml_tanh(ctx, kq);
  8525. kq = ggml_scale(ctx, kq, hparams.f_attn_logit_softcapping);
  8526. }
  8527. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_scale, hparams.f_max_alibi_bias);
  8528. cb(kq, "kq_soft_max_ext", il);
  8529. GGML_ASSERT(kv.size == n_ctx);
  8530. // split cached v into n_head heads
  8531. struct ggml_tensor * v =
  8532. ggml_view_3d(ctx, kv.v_l[il],
  8533. n_kv, n_embd_head_v, n_head_kv,
  8534. ggml_element_size(kv.v_l[il])*n_ctx,
  8535. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  8536. 0);
  8537. cb(v, "v", il);
  8538. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  8539. cb(kqv, "kqv", il);
  8540. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  8541. cb(kqv_merged, "kqv_merged", il);
  8542. cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_v*n_head, n_tokens);
  8543. cb(cur, "kqv_merged_cont", il);
  8544. }
  8545. ggml_build_forward_expand(graph, cur);
  8546. if (wo) {
  8547. cur = llm_build_lora_mm(lctx, ctx, wo, cur);
  8548. }
  8549. if (wo_b) {
  8550. cb(cur, "kqv_wo", il);
  8551. }
  8552. if (wo_b) {
  8553. cur = ggml_add(ctx, cur, wo_b);
  8554. }
  8555. return cur;
  8556. }
  8557. static struct ggml_tensor * llm_build_kv(
  8558. struct ggml_context * ctx,
  8559. struct llama_context & lctx,
  8560. const llama_kv_cache & kv,
  8561. struct ggml_cgraph * graph,
  8562. struct ggml_tensor * wo,
  8563. struct ggml_tensor * wo_b,
  8564. struct ggml_tensor * k_cur,
  8565. struct ggml_tensor * v_cur,
  8566. struct ggml_tensor * q_cur,
  8567. struct ggml_tensor * kq_mask,
  8568. int32_t n_tokens,
  8569. int32_t kv_head,
  8570. int32_t n_kv,
  8571. float kq_scale,
  8572. const llm_build_cb & cb,
  8573. int il) {
  8574. const llama_hparams & hparams = lctx.model.hparams;
  8575. const llama_cparams & cparams = lctx.cparams;
  8576. // these nodes are added to the graph together so that they are not reordered
  8577. // by doing so, the number of splits in the graph is reduced
  8578. ggml_build_forward_expand(graph, q_cur);
  8579. ggml_build_forward_expand(graph, k_cur);
  8580. ggml_build_forward_expand(graph, v_cur);
  8581. llm_build_kv_store(ctx, hparams, cparams, kv, graph, k_cur, v_cur, n_tokens, kv_head, cb, il);
  8582. struct ggml_tensor * cur;
  8583. cur = llm_build_kqv(ctx, lctx, kv, graph, wo, wo_b, q_cur, kq_mask, n_tokens, n_kv, kq_scale, cb, il);
  8584. cb(cur, "kqv_out", il);
  8585. return cur;
  8586. }
  8587. static struct ggml_tensor * llm_build_copy_mask_state(
  8588. struct ggml_context * ctx,
  8589. struct ggml_cgraph * graph,
  8590. struct ggml_tensor * s,
  8591. struct ggml_tensor * state_copy,
  8592. struct ggml_tensor * state_mask,
  8593. int32_t n_state,
  8594. int32_t kv_size,
  8595. int32_t kv_head,
  8596. int32_t n_kv,
  8597. int32_t n_seqs) {
  8598. struct ggml_tensor * states = ggml_reshape_2d(ctx, s, n_state, kv_size);
  8599. // copy states
  8600. // NOTE: assuming the copy destinations are ALL contained between kv_head and kv_head + n_kv
  8601. // this shrinks the tensors's ne[1] to n_kv
  8602. states = ggml_get_rows(ctx, states, state_copy);
  8603. // clear states of sequences which are starting at the beginning of this batch
  8604. // FIXME: zero-out NANs?
  8605. states = ggml_mul(ctx, states, state_mask);
  8606. // copy states which won't be changed further (between n_seqs and n_kv)
  8607. ggml_build_forward_expand(graph,
  8608. ggml_cpy(ctx,
  8609. ggml_view_1d(ctx, states, n_state*(n_kv - n_seqs), n_seqs*n_state*ggml_element_size(states)),
  8610. ggml_view_1d(ctx, s, n_state*(n_kv - n_seqs), (kv_head + n_seqs)*n_state*ggml_element_size(s))));
  8611. // the part of the states that will be used and modified
  8612. return ggml_view_2d(ctx, states, n_state, n_seqs, states->nb[1], 0);
  8613. }
  8614. // TODO: split
  8615. static struct ggml_tensor * llm_build_mamba(
  8616. struct ggml_context * ctx,
  8617. struct llama_context & lctx,
  8618. const llama_ubatch & batch,
  8619. struct ggml_cgraph * graph,
  8620. struct ggml_tensor * cur,
  8621. struct ggml_tensor * state_copy,
  8622. struct ggml_tensor * state_mask,
  8623. int32_t kv_head,
  8624. int32_t n_kv,
  8625. const llm_build_cb & cb,
  8626. int il) {
  8627. const llama_model & model = lctx.model;
  8628. const llama_hparams & hparams = model.hparams;
  8629. const llama_kv_cache & kv = lctx.kv_self;
  8630. const int64_t d_conv = hparams.ssm_d_conv;
  8631. const int64_t d_inner = hparams.ssm_d_inner;
  8632. const int64_t d_state = hparams.ssm_d_state;
  8633. const int64_t dt_rank = hparams.ssm_dt_rank;
  8634. const int64_t n_seqs = batch.n_seqs;
  8635. // Some variants of Mamba arch (e.g. FalconMamba do apply layer norm on B and Dt layers)
  8636. const bool ssm_dt_b_c_rms = hparams.ssm_dt_b_c_rms;
  8637. // Use the same RMS norm as the final layer norm
  8638. const float norm_rms_eps = hparams.f_norm_rms_eps;
  8639. const int64_t n_seq_tokens = batch.n_seq_tokens;
  8640. GGML_ASSERT(n_seqs != 0);
  8641. GGML_ASSERT(batch.equal_seqs);
  8642. GGML_ASSERT(batch.n_tokens == n_seq_tokens * n_seqs);
  8643. struct ggml_tensor * conv_states_all = kv.k_l[il];
  8644. struct ggml_tensor * ssm_states_all = kv.v_l[il];
  8645. // (ab)using the KV cache to store the states
  8646. struct ggml_tensor * conv = llm_build_copy_mask_state(ctx,
  8647. graph, conv_states_all, state_copy, state_mask,
  8648. hparams.n_embd_k_s(), kv.size, kv_head, n_kv, n_seqs);
  8649. conv = ggml_reshape_3d(ctx, conv, d_conv - 1, d_inner, n_seqs);
  8650. struct ggml_tensor * ssm = llm_build_copy_mask_state(ctx,
  8651. graph, ssm_states_all, state_copy, state_mask,
  8652. hparams.n_embd_v_s(), kv.size, kv_head, n_kv, n_seqs);
  8653. ssm = ggml_reshape_3d(ctx, ssm, d_state, d_inner, n_seqs);
  8654. // {n_embd, n_tokens} => {n_embd, n_seq_tokens, n_seqs}
  8655. cur = ggml_reshape_3d(ctx, cur, cur->ne[0], n_seq_tokens, n_seqs);
  8656. // {n_embd, 2*d_inner} @ {n_embd, n_seq_tokens, n_seqs} => {2*d_inner, n_seq_tokens, n_seqs}
  8657. struct ggml_tensor * xz = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_in, cur);
  8658. // split the above in two
  8659. // => {d_inner, n_seq_tokens, n_seqs}
  8660. struct ggml_tensor * x = ggml_view_3d(ctx, xz, d_inner, xz->ne[1], xz->ne[2], xz->nb[1], xz->nb[2], 0);
  8661. 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));
  8662. // conv
  8663. {
  8664. // => {d_conv - 1 + n_seq_tokens, d_inner, n_seqs}
  8665. struct ggml_tensor * conv_x = ggml_concat(ctx, conv, ggml_transpose(ctx, x), 0);
  8666. // copy last (d_conv - 1) columns back into the state cache
  8667. 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]));
  8668. ggml_build_forward_expand(graph,
  8669. ggml_cpy(ctx, last_conv,
  8670. ggml_view_1d(ctx, conv_states_all,
  8671. (d_conv - 1)*(d_inner)*(n_seqs),
  8672. kv_head*(d_conv - 1)*(d_inner)*ggml_element_size(conv_states_all))));
  8673. // 1D convolution
  8674. // The equivalent is to make a self-overlapping view of conv_x
  8675. // over d_conv columns at each stride in the 3rd dimension,
  8676. // then element-wise multiply that with the conv1d weight,
  8677. // then sum the elements of each row,
  8678. // (the last two steps are a dot product over rows (also doable with mul_mat))
  8679. // then permute away the ne[0] dimension,
  8680. // and then you're left with the resulting x tensor.
  8681. // For simultaneous sequences, all sequences need to have the same length.
  8682. x = ggml_ssm_conv(ctx, conv_x, model.layers[il].ssm_conv1d);
  8683. // bias
  8684. x = ggml_add(ctx, x, model.layers[il].ssm_conv1d_b);
  8685. x = ggml_silu(ctx, x);
  8686. }
  8687. // ssm
  8688. {
  8689. // {d_inner, dt_rank + 2*d_state} @ {d_inner, n_seq_tokens, n_seqs} => {dt_rank + 2*d_state, n_seq_tokens, n_seqs}
  8690. struct ggml_tensor * x_db = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_x, x);
  8691. // split
  8692. 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);
  8693. 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);
  8694. 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));
  8695. // Some Mamba variants (e.g. FalconMamba) apply RMS norm in B, C & Dt layers
  8696. if (ssm_dt_b_c_rms) {
  8697. dt = ggml_rms_norm(ctx, dt, norm_rms_eps);
  8698. B = ggml_rms_norm(ctx, B, norm_rms_eps);
  8699. C = ggml_rms_norm(ctx, C, norm_rms_eps);
  8700. }
  8701. // {dt_rank, d_inner} @ {dt_rank, n_seq_tokens, n_seqs} => {d_inner, n_seq_tokens, n_seqs}
  8702. dt = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_dt, dt);
  8703. dt = ggml_add(ctx, dt, model.layers[il].ssm_dt_b);
  8704. // Custom operator to optimize the parallel associative scan
  8705. // as described in the Annex D of the Mamba paper.
  8706. // => {d_inner, n_seq_tokens, n_seqs} and {d_state, d_inner, n_seqs}
  8707. struct ggml_tensor * y_ssm = ggml_ssm_scan(ctx, ssm, x, dt, model.layers[il].ssm_a, B, C);
  8708. // store last states
  8709. ggml_build_forward_expand(graph,
  8710. ggml_cpy(ctx,
  8711. ggml_view_1d(ctx, y_ssm, d_state*d_inner*n_seqs, x->nb[3]),
  8712. 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))));
  8713. struct ggml_tensor * y = ggml_view_3d(ctx, y_ssm, d_inner, n_seq_tokens, n_seqs, x->nb[1], x->nb[2], 0);
  8714. // TODO: skip computing output earlier for unused tokens
  8715. // {d_inner, n_seq_tokens, n_seqs} * {d_inner} => {d_inner, n_seq_tokens, n_seqs}
  8716. y = ggml_add(ctx, y, ggml_mul(ctx, x, model.layers[il].ssm_d));
  8717. y = ggml_mul(ctx, y, ggml_silu(ctx, ggml_cont(ctx, z)));
  8718. // {d_inner, n_embd} @ {d_inner, n_seq_tokens, n_seqs} => {n_embd, n_seq_tokens, n_seqs}
  8719. cur = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_out, y);
  8720. }
  8721. // {n_embd, n_seq_tokens, n_seqs} => {n_embd, n_tokens}
  8722. cur = ggml_reshape_2d(ctx, cur, cur->ne[0], n_seq_tokens * n_seqs);
  8723. cb(cur, "mamba_out", il);
  8724. return cur;
  8725. }
  8726. static struct ggml_tensor * llm_build_rwkv6_time_mix(
  8727. struct llama_context & lctx,
  8728. struct ggml_context * ctx,
  8729. const struct llama_layer * layer,
  8730. struct ggml_tensor * cur,
  8731. struct ggml_tensor * x_prev,
  8732. struct ggml_tensor ** wkv_state) {
  8733. size_t n_embd = cur->ne[0];
  8734. size_t n_seq_tokens = cur->ne[1];
  8735. size_t n_seqs = cur->ne[2];
  8736. size_t head_size = layer->time_mix_first->ne[0];
  8737. size_t head_count = layer->time_mix_first->ne[1];
  8738. size_t n_tokens = n_seqs * n_seq_tokens;
  8739. struct ggml_tensor * sx = ggml_sub(ctx, x_prev, cur);
  8740. sx = ggml_reshape_2d(ctx, sx, n_embd, n_tokens);
  8741. cur = ggml_reshape_2d(ctx, cur, n_embd, n_tokens);
  8742. struct ggml_tensor * xxx = ggml_add(ctx, ggml_mul(ctx, sx, layer->time_mix_lerp_x), cur);
  8743. xxx = ggml_reshape_4d(
  8744. ctx,
  8745. ggml_tanh(
  8746. ctx,
  8747. ggml_mul_mat(ctx, layer->time_mix_w1, xxx)
  8748. ),
  8749. layer->time_mix_w1->ne[1] / 5, 1, 5, n_tokens
  8750. );
  8751. xxx = ggml_cont(ctx, ggml_permute(ctx, xxx, 0, 1, 3, 2));
  8752. xxx = ggml_mul_mat(
  8753. ctx,
  8754. ggml_reshape_4d(
  8755. ctx,
  8756. layer->time_mix_w2,
  8757. layer->time_mix_w2->ne[0], layer->time_mix_w2->ne[1], 1, 5
  8758. ),
  8759. xxx
  8760. );
  8761. struct ggml_tensor *mw = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], 0);
  8762. struct ggml_tensor *mk = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * sizeof(float));
  8763. struct ggml_tensor *mv = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * 2 * sizeof(float));
  8764. struct ggml_tensor *mr = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * 3 * sizeof(float));
  8765. struct ggml_tensor *mg = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * 4 * sizeof(float));
  8766. struct ggml_tensor * xw = ggml_add(
  8767. ctx,
  8768. ggml_mul(
  8769. ctx,
  8770. ggml_add(ctx, mw, layer->time_mix_lerp_w),
  8771. sx
  8772. ),
  8773. cur
  8774. );
  8775. struct ggml_tensor * xk = ggml_add(
  8776. ctx,
  8777. ggml_mul(
  8778. ctx,
  8779. ggml_add(ctx, mk, layer->time_mix_lerp_k),
  8780. sx
  8781. ),
  8782. cur
  8783. );
  8784. struct ggml_tensor * xv = ggml_add(
  8785. ctx,
  8786. ggml_mul(
  8787. ctx,
  8788. ggml_add(ctx, mv, layer->time_mix_lerp_v),
  8789. sx
  8790. ),
  8791. cur
  8792. );
  8793. struct ggml_tensor * xr = ggml_add(
  8794. ctx,
  8795. ggml_mul(
  8796. ctx,
  8797. ggml_add(ctx, mr, layer->time_mix_lerp_r),
  8798. sx
  8799. ),
  8800. cur
  8801. );
  8802. struct ggml_tensor * xg = ggml_add(
  8803. ctx,
  8804. ggml_mul(
  8805. ctx,
  8806. ggml_add(ctx, mg, layer->time_mix_lerp_g),
  8807. sx
  8808. ),
  8809. cur
  8810. );
  8811. 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);
  8812. 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);
  8813. 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);
  8814. struct ggml_tensor * g = ggml_silu(
  8815. ctx,
  8816. llm_build_lora_mm(lctx, ctx, layer->time_mix_gate, xg)
  8817. );
  8818. struct ggml_tensor * w = ggml_mul_mat(
  8819. ctx,
  8820. layer->time_mix_decay_w2,
  8821. ggml_tanh(
  8822. ctx,
  8823. ggml_mul_mat(ctx, layer->time_mix_decay_w1, xw)
  8824. )
  8825. );
  8826. w = ggml_add(ctx, w, ggml_reshape_1d(ctx, layer->time_mix_decay, n_embd));
  8827. w = ggml_exp(ctx, ggml_neg(ctx, ggml_exp(ctx, w)));
  8828. w = ggml_reshape_4d(ctx, w, 1, head_size, head_count, n_tokens);
  8829. k = ggml_transpose(ctx, k);
  8830. v = ggml_transpose(ctx, v);
  8831. r = ggml_transpose(ctx, r);
  8832. struct ggml_tensor * wkv_output = ggml_rwkv_wkv(ctx, k, v, r, layer->time_mix_first, w, *wkv_state);
  8833. cur = ggml_view_1d(ctx, wkv_output, n_embd * n_tokens, 0);
  8834. *wkv_state = ggml_view_1d(ctx, wkv_output, n_embd * head_size * n_seqs, n_embd * n_tokens * sizeof(float));
  8835. // group norm with head_count groups
  8836. cur = ggml_reshape_3d(ctx, cur, n_embd / head_count, head_count, n_tokens);
  8837. cur = ggml_norm(ctx, cur, 64e-5f);
  8838. // Convert back to regular vectors.
  8839. cur = ggml_reshape_2d(ctx, cur, n_embd, n_tokens);
  8840. cur = ggml_add(ctx, ggml_mul(ctx, cur, layer->time_mix_ln), layer->time_mix_ln_b);
  8841. cur = ggml_mul(ctx, cur, g);
  8842. cur = llm_build_lora_mm(lctx, ctx, layer->time_mix_output, cur);
  8843. return ggml_reshape_3d(ctx, cur, n_embd, n_seq_tokens, n_seqs);
  8844. }
  8845. static struct ggml_tensor * llm_build_rwkv6_channel_mix(
  8846. struct llama_context & lctx,
  8847. struct ggml_context * ctx,
  8848. const struct llama_layer * layer,
  8849. struct ggml_tensor * cur,
  8850. struct ggml_tensor * x_prev) {
  8851. struct ggml_tensor * sx = ggml_sub(ctx, x_prev, cur);
  8852. struct ggml_tensor * xk = ggml_add(ctx, ggml_mul(ctx, sx, layer->channel_mix_lerp_k), cur);
  8853. struct ggml_tensor * xr = ggml_add(ctx, ggml_mul(ctx, sx, layer->channel_mix_lerp_r), cur);
  8854. struct ggml_tensor * r = ggml_sigmoid(ctx, llm_build_lora_mm(lctx, ctx, layer->channel_mix_receptance, xr));
  8855. struct ggml_tensor * k = ggml_sqr(
  8856. ctx,
  8857. ggml_relu(
  8858. ctx,
  8859. llm_build_lora_mm(lctx, ctx, layer->channel_mix_key, xk)
  8860. )
  8861. );
  8862. return ggml_mul(ctx, r, llm_build_lora_mm(lctx, ctx, layer->channel_mix_value, k));
  8863. }
  8864. struct llm_build_context {
  8865. const llama_model & model;
  8866. llama_context & lctx;
  8867. const llama_hparams & hparams;
  8868. const llama_cparams & cparams;
  8869. const llama_ubatch & batch;
  8870. const llama_kv_cache & kv_self;
  8871. const int64_t n_embd;
  8872. const int64_t n_layer;
  8873. const int64_t n_rot;
  8874. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  8875. const int64_t n_head;
  8876. const int64_t n_head_kv;
  8877. const int64_t n_embd_head_k;
  8878. const int64_t n_embd_k_gqa;
  8879. const int64_t n_embd_head_v;
  8880. const int64_t n_embd_v_gqa;
  8881. const int64_t n_expert;
  8882. const int64_t n_expert_used;
  8883. const float freq_base;
  8884. const float freq_scale;
  8885. const float ext_factor;
  8886. const float attn_factor;
  8887. const float beta_fast;
  8888. const float beta_slow;
  8889. const float norm_eps;
  8890. const float norm_rms_eps;
  8891. const int32_t n_tokens;
  8892. const int32_t n_kv; // size of KV cache to consider (n_kv <= kv_self.size)
  8893. const int32_t n_outputs;
  8894. const int32_t n_outputs_enc;
  8895. const int32_t kv_head; // index of where we store new KV data in the cache
  8896. const int32_t n_ctx_orig;
  8897. const bool flash_attn;
  8898. const enum llama_pooling_type pooling_type;
  8899. const enum llama_rope_type rope_type;
  8900. const llm_build_cb & cb;
  8901. std::vector<uint8_t> & buf_compute_meta;
  8902. struct ggml_context * ctx0 = nullptr;
  8903. // TODO: consider making the entire interface noexcept
  8904. llm_build_context(
  8905. llama_context & lctx,
  8906. const llama_ubatch & batch,
  8907. const llm_build_cb & cb,
  8908. bool worst_case) :
  8909. model (lctx.model),
  8910. lctx (lctx),
  8911. hparams (model.hparams),
  8912. cparams (lctx.cparams),
  8913. batch (batch),
  8914. kv_self (lctx.kv_self),
  8915. n_embd (hparams.n_embd),
  8916. n_layer (hparams.n_layer),
  8917. n_rot (hparams.n_rot),
  8918. n_ctx (cparams.n_ctx),
  8919. n_head (hparams.n_head()),
  8920. n_head_kv (hparams.n_head_kv()),
  8921. n_embd_head_k (hparams.n_embd_head_k),
  8922. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  8923. n_embd_head_v (hparams.n_embd_head_v),
  8924. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  8925. n_expert (hparams.n_expert),
  8926. n_expert_used (hparams.n_expert_used),
  8927. freq_base (cparams.rope_freq_base),
  8928. freq_scale (cparams.rope_freq_scale),
  8929. ext_factor (cparams.yarn_ext_factor),
  8930. attn_factor (cparams.yarn_attn_factor),
  8931. beta_fast (cparams.yarn_beta_fast),
  8932. beta_slow (cparams.yarn_beta_slow),
  8933. norm_eps (hparams.f_norm_eps),
  8934. norm_rms_eps (hparams.f_norm_rms_eps),
  8935. n_tokens (batch.n_tokens),
  8936. n_kv (worst_case ? kv_self.size : kv_self.n),
  8937. n_outputs (worst_case ? n_tokens : lctx.n_outputs),
  8938. n_outputs_enc (worst_case ? n_tokens : lctx.embd_enc.size() / hparams.n_embd),
  8939. kv_head (worst_case ? (kv_self.recurrent ? 0 : kv_self.size - n_tokens) : kv_self.head),
  8940. n_ctx_orig (cparams.n_ctx_orig_yarn),
  8941. flash_attn (cparams.flash_attn),
  8942. pooling_type (cparams.pooling_type),
  8943. rope_type (hparams.rope_type),
  8944. cb (cb),
  8945. buf_compute_meta (lctx.buf_compute_meta) {
  8946. // all initializations should be done in init()
  8947. }
  8948. void init() {
  8949. struct ggml_init_params params = {
  8950. /*.mem_size =*/ buf_compute_meta.size(),
  8951. /*.mem_buffer =*/ buf_compute_meta.data(),
  8952. /*.no_alloc =*/ true,
  8953. };
  8954. ctx0 = ggml_init(params);
  8955. lctx.inp_tokens = nullptr;
  8956. lctx.inp_embd = nullptr;
  8957. lctx.inp_pos = nullptr;
  8958. lctx.inp_out_ids = nullptr;
  8959. lctx.inp_KQ_mask = nullptr;
  8960. lctx.inp_KQ_mask_swa = nullptr;
  8961. lctx.inp_K_shift = nullptr;
  8962. lctx.inp_mean = nullptr;
  8963. lctx.inp_cls = nullptr;
  8964. lctx.inp_s_copy = nullptr;
  8965. lctx.inp_s_mask = nullptr;
  8966. lctx.inp_s_seq = nullptr;
  8967. lctx.inp_pos_bucket = nullptr;
  8968. lctx.inp_embd_enc = nullptr;
  8969. lctx.inp_KQ_mask_cross = nullptr;
  8970. lctx.inp_cross_attn_state = nullptr;
  8971. }
  8972. void free() {
  8973. if (ctx0) {
  8974. ggml_free(ctx0);
  8975. ctx0 = nullptr;
  8976. }
  8977. }
  8978. struct ggml_cgraph * build_k_shift() {
  8979. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8980. GGML_ASSERT(kv_self.size == n_ctx);
  8981. lctx.inp_K_shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_ctx);
  8982. cb(lctx.inp_K_shift, "K_shift", -1);
  8983. ggml_set_input(lctx.inp_K_shift);
  8984. for (int il = 0; il < n_layer; ++il) {
  8985. const int64_t n_head_kv = hparams.n_head_kv(il);
  8986. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  8987. struct ggml_tensor * rope_factors = build_rope_factors(il);
  8988. struct ggml_tensor * k =
  8989. ggml_view_3d(ctx0, kv_self.k_l[il],
  8990. n_embd_head_k, n_head_kv, n_ctx,
  8991. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  8992. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  8993. 0);
  8994. struct ggml_tensor * tmp;
  8995. if (ggml_is_quantized(k->type)) {
  8996. // dequantize to f32 -> RoPE -> quantize back
  8997. tmp = ggml_cast(ctx0, k, GGML_TYPE_F32);
  8998. cb(tmp, "K_f32", il);
  8999. for (auto * backend : lctx.backends) {
  9000. // Figure out which backend KV cache belongs to
  9001. if (ggml_backend_supports_buft(backend, lctx.model.buft_layer[il].buft)) {
  9002. ggml_backend_sched_set_tensor_backend(lctx.sched, tmp, backend);
  9003. break;
  9004. }
  9005. }
  9006. tmp = ggml_rope_ext_inplace(ctx0, tmp,
  9007. lctx.inp_K_shift, rope_factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9008. ext_factor, attn_factor, beta_fast, beta_slow);
  9009. cb(tmp, "K_shifted_f32", il);
  9010. tmp = ggml_cpy(ctx0, tmp, k);
  9011. } else {
  9012. // we rotate only the first n_rot dimensions
  9013. tmp = ggml_rope_ext_inplace(ctx0, k,
  9014. lctx.inp_K_shift, rope_factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9015. ext_factor, attn_factor, beta_fast, beta_slow);
  9016. }
  9017. cb(tmp, "K_shifted", il);
  9018. ggml_build_forward_expand(gf, tmp);
  9019. }
  9020. return gf;
  9021. }
  9022. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  9023. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9024. for (uint32_t i = 0; i < ids.size(); ++i) {
  9025. const uint32_t id = ids[i];
  9026. if (i == id || id == ids.size()) {
  9027. continue;
  9028. }
  9029. uint32_t nm = 1;
  9030. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  9031. nm++;
  9032. }
  9033. for (int il = 0; il < n_layer; ++il) {
  9034. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  9035. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  9036. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  9037. n_embd_k_gqa, nm,
  9038. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  9039. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  9040. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  9041. n_embd_k_gqa, nm,
  9042. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  9043. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  9044. ggml_tensor * view_v_src;
  9045. ggml_tensor * view_v_dst;
  9046. if (flash_attn) {
  9047. // NOTE: the V cache is not transposed when using flash attention
  9048. view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  9049. n_embd_v_gqa, nm,
  9050. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa),
  9051. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*i));
  9052. view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  9053. n_embd_v_gqa, nm,
  9054. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa),
  9055. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*id));
  9056. } else {
  9057. view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  9058. nm, n_embd_v_gqa,
  9059. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  9060. ggml_row_size(kv_self.v_l[il]->type, i));
  9061. view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  9062. nm, n_embd_v_gqa,
  9063. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  9064. ggml_row_size(kv_self.v_l[il]->type, id));
  9065. }
  9066. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  9067. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  9068. }
  9069. i += nm - 1;
  9070. }
  9071. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  9072. return gf;
  9073. }
  9074. struct ggml_tensor * build_inp_pos() {
  9075. lctx.inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  9076. cb(lctx.inp_pos, "inp_pos", -1);
  9077. ggml_set_input(lctx.inp_pos);
  9078. return lctx.inp_pos;
  9079. }
  9080. struct ggml_tensor * build_rope_factors(int il) {
  9081. // choose long/short freq factors based on the context size
  9082. const auto n_ctx_pre_seq = cparams.n_ctx / cparams.n_seq_max;
  9083. if (model.layers[il].rope_freqs != nullptr) {
  9084. return model.layers[il].rope_freqs;
  9085. }
  9086. if (n_ctx_pre_seq > hparams.n_ctx_orig_yarn) {
  9087. return model.layers[il].rope_long;
  9088. }
  9089. return model.layers[il].rope_short;
  9090. }
  9091. struct ggml_tensor * build_inp_out_ids() {
  9092. lctx.inp_out_ids = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_outputs);
  9093. cb(lctx.inp_out_ids, "inp_out_ids", -1);
  9094. ggml_set_input(lctx.inp_out_ids);
  9095. return lctx.inp_out_ids;
  9096. }
  9097. struct ggml_tensor * build_inp_KQ_mask(bool causal = true) {
  9098. lctx.inp_KQ_mask = causal
  9099. ? ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD))
  9100. : ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  9101. cb(lctx.inp_KQ_mask, "KQ_mask", -1);
  9102. ggml_set_input(lctx.inp_KQ_mask);
  9103. return flash_attn ? ggml_cast(ctx0, lctx.inp_KQ_mask, GGML_TYPE_F16) : lctx.inp_KQ_mask;
  9104. }
  9105. struct ggml_tensor * build_inp_KQ_mask_swa(bool causal = true) {
  9106. GGML_ASSERT(hparams.n_swa > 0);
  9107. lctx.inp_KQ_mask_swa = causal
  9108. ? ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD))
  9109. : ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  9110. cb(lctx.inp_KQ_mask_swa, "KQ_mask_swa", -1);
  9111. ggml_set_input(lctx.inp_KQ_mask_swa);
  9112. return flash_attn ? ggml_cast(ctx0, lctx.inp_KQ_mask_swa, GGML_TYPE_F16) : lctx.inp_KQ_mask_swa;
  9113. }
  9114. struct ggml_tensor * build_inp_mean() {
  9115. lctx.inp_mean = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  9116. cb(lctx.inp_mean, "inp_mean", -1);
  9117. ggml_set_input(lctx.inp_mean);
  9118. return lctx.inp_mean;
  9119. }
  9120. struct ggml_tensor * build_inp_cls() {
  9121. lctx.inp_cls = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  9122. cb(lctx.inp_cls, "inp_cls", -1);
  9123. ggml_set_input(lctx.inp_cls);
  9124. return lctx.inp_cls;
  9125. }
  9126. struct ggml_tensor * build_inp_s_copy() {
  9127. lctx.inp_s_copy = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_kv);
  9128. cb(lctx.inp_s_copy, "inp_s_copy", -1);
  9129. ggml_set_input(lctx.inp_s_copy);
  9130. return lctx.inp_s_copy;
  9131. }
  9132. struct ggml_tensor * build_inp_s_mask() {
  9133. lctx.inp_s_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_kv);
  9134. cb(lctx.inp_s_mask, "inp_s_mask", -1);
  9135. ggml_set_input(lctx.inp_s_mask);
  9136. return lctx.inp_s_mask;
  9137. }
  9138. struct ggml_cgraph * append_pooling(struct ggml_cgraph * gf) {
  9139. // find result_norm tensor for input
  9140. struct ggml_tensor * inp = nullptr;
  9141. for (int i = ggml_graph_n_nodes(gf) - 1; i >= 0; --i) {
  9142. inp = ggml_graph_node(gf, i);
  9143. if (strcmp(inp->name, "result_norm") == 0 || strcmp(inp->name, "result_embd") == 0) {
  9144. break;
  9145. } else {
  9146. inp = nullptr;
  9147. }
  9148. }
  9149. GGML_ASSERT(inp != nullptr && "missing result_norm/result_embd tensor");
  9150. struct ggml_tensor * cur;
  9151. switch (pooling_type) {
  9152. case LLAMA_POOLING_TYPE_NONE:
  9153. {
  9154. cur = inp;
  9155. } break;
  9156. case LLAMA_POOLING_TYPE_MEAN:
  9157. {
  9158. struct ggml_tensor * inp_mean = build_inp_mean();
  9159. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, inp)), inp_mean);
  9160. } break;
  9161. case LLAMA_POOLING_TYPE_CLS:
  9162. case LLAMA_POOLING_TYPE_LAST:
  9163. {
  9164. struct ggml_tensor * inp_cls = build_inp_cls();
  9165. cur = ggml_get_rows(ctx0, inp, inp_cls);
  9166. } break;
  9167. case LLAMA_POOLING_TYPE_RANK:
  9168. {
  9169. struct ggml_tensor * inp_cls = build_inp_cls();
  9170. inp = ggml_get_rows(ctx0, inp, inp_cls);
  9171. // classification head
  9172. // https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/roberta/modeling_roberta.py#L1566
  9173. GGML_ASSERT(model.cls != nullptr);
  9174. GGML_ASSERT(model.cls_b != nullptr);
  9175. cur = ggml_add (ctx0, ggml_mul_mat(ctx0, model.cls, inp), model.cls_b);
  9176. cur = ggml_tanh(ctx0, cur);
  9177. // some models don't have `cls_out`, for example: https://huggingface.co/jinaai/jina-reranker-v1-tiny-en
  9178. // https://huggingface.co/jinaai/jina-reranker-v1-tiny-en/blob/cb5347e43979c3084a890e3f99491952603ae1b7/modeling_bert.py#L884-L896
  9179. if (model.cls_out) {
  9180. GGML_ASSERT(model.cls_out_b != nullptr);
  9181. cur = ggml_add (ctx0, ggml_mul_mat(ctx0, model.cls_out, cur), model.cls_out_b);
  9182. }
  9183. } break;
  9184. default:
  9185. {
  9186. GGML_ABORT("unknown pooling type");
  9187. }
  9188. }
  9189. cb(cur, "result_embd_pooled", -1);
  9190. ggml_build_forward_expand(gf, cur);
  9191. return gf;
  9192. }
  9193. struct ggml_tensor * llm_build_pos_bucket(bool causal) {
  9194. if (causal) {
  9195. lctx.inp_pos_bucket = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  9196. } else {
  9197. lctx.inp_pos_bucket = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_tokens);
  9198. }
  9199. ggml_set_input(lctx.inp_pos_bucket);
  9200. cb(lctx.inp_pos_bucket, "pos_bucket", -1);
  9201. return lctx.inp_pos_bucket;
  9202. }
  9203. struct ggml_tensor * llm_build_pos_bias(struct ggml_tensor * pos_bucket, struct ggml_tensor * attn_rel_b) {
  9204. struct ggml_tensor * pos_bucket_1d = ggml_view_1d(ctx0, pos_bucket, pos_bucket->ne[0] * pos_bucket->ne[1], 0);
  9205. cb(pos_bucket_1d, "pos_bucket_1d", -1);
  9206. struct ggml_tensor * pos_bias = ggml_get_rows(ctx0, attn_rel_b, pos_bucket_1d);
  9207. cb(pos_bias, "pos_bias", -1);
  9208. 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);
  9209. cb(pos_bias, "pos_bias", -1);
  9210. pos_bias = ggml_permute(ctx0, pos_bias, 2, 0, 1, 3);
  9211. cb(pos_bias, "pos_bias", -1);
  9212. pos_bias = ggml_cont(ctx0, pos_bias);
  9213. cb(pos_bias, "pos_bias", -1);
  9214. return pos_bias;
  9215. }
  9216. struct ggml_tensor * llm_build_inp_embd_enc() {
  9217. const int64_t n_embd = hparams.n_embd;
  9218. lctx.inp_embd_enc = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, n_outputs_enc);
  9219. ggml_set_input(lctx.inp_embd_enc);
  9220. cb(lctx.inp_embd_enc, "embd_enc", -1);
  9221. return lctx.inp_embd_enc;
  9222. }
  9223. struct ggml_tensor * llm_build_inp_KQ_mask_cross() {
  9224. lctx.inp_KQ_mask_cross = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_outputs_enc, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  9225. ggml_set_input(lctx.inp_KQ_mask_cross);
  9226. cb(lctx.inp_KQ_mask_cross, "KQ_mask_cross", -1);
  9227. return lctx.inp_KQ_mask_cross;
  9228. }
  9229. struct ggml_cgraph * build_llama() {
  9230. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9231. // mutable variable, needed during the last layer of the computation to skip unused tokens
  9232. int32_t n_tokens = this->n_tokens;
  9233. const int64_t n_embd_head = hparams.n_embd_head_v;
  9234. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9235. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9236. struct ggml_tensor * cur;
  9237. struct ggml_tensor * inpL;
  9238. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9239. // inp_pos - contains the positions
  9240. struct ggml_tensor * inp_pos = build_inp_pos();
  9241. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9242. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9243. const float kq_scale = hparams.f_attention_scale == 0.0f ? 1.0f/sqrtf(float(n_embd_head)) : hparams.f_attention_scale;
  9244. for (int il = 0; il < n_layer; ++il) {
  9245. struct ggml_tensor * inpSA = inpL;
  9246. // norm
  9247. cur = llm_build_norm(ctx0, inpL, hparams,
  9248. model.layers[il].attn_norm, NULL,
  9249. LLM_NORM_RMS, cb, il);
  9250. cb(cur, "attn_norm", il);
  9251. // self-attention
  9252. {
  9253. // rope freq factors for llama3; may return nullptr for llama2 and other models
  9254. struct ggml_tensor * rope_factors = build_rope_factors(il);
  9255. // compute Q and K and RoPE them
  9256. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9257. cb(Qcur, "Qcur", il);
  9258. if (model.layers[il].bq) {
  9259. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9260. cb(Qcur, "Qcur", il);
  9261. }
  9262. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9263. cb(Kcur, "Kcur", il);
  9264. if (model.layers[il].bk) {
  9265. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9266. cb(Kcur, "Kcur", il);
  9267. }
  9268. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9269. cb(Vcur, "Vcur", il);
  9270. if (model.layers[il].bv) {
  9271. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9272. cb(Vcur, "Vcur", il);
  9273. }
  9274. Qcur = ggml_rope_ext(
  9275. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  9276. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9277. ext_factor, attn_factor, beta_fast, beta_slow
  9278. );
  9279. cb(Qcur, "Qcur", il);
  9280. Kcur = ggml_rope_ext(
  9281. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  9282. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9283. ext_factor, attn_factor, beta_fast, beta_slow
  9284. );
  9285. cb(Kcur, "Kcur", il);
  9286. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9287. model.layers[il].wo, model.layers[il].bo,
  9288. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  9289. }
  9290. if (il == n_layer - 1) {
  9291. // skip computing output for unused tokens
  9292. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9293. n_tokens = n_outputs;
  9294. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9295. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9296. }
  9297. // For Granite architecture
  9298. if (hparams.f_residual_scale) {
  9299. cur = ggml_scale(ctx0, cur, hparams.f_residual_scale);
  9300. }
  9301. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9302. cb(ffn_inp, "ffn_inp", il);
  9303. // feed-forward network
  9304. if (model.layers[il].ffn_gate_inp == nullptr) {
  9305. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9306. model.layers[il].ffn_norm, NULL,
  9307. LLM_NORM_RMS, cb, il);
  9308. cb(cur, "ffn_norm", il);
  9309. cur = llm_build_ffn(ctx0, lctx, cur,
  9310. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9311. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  9312. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9313. NULL,
  9314. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9315. cb(cur, "ffn_out", il);
  9316. } else {
  9317. // MoE branch
  9318. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9319. model.layers[il].ffn_norm, NULL,
  9320. LLM_NORM_RMS, cb, il);
  9321. cb(cur, "ffn_norm", il);
  9322. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  9323. model.layers[il].ffn_gate_inp,
  9324. model.layers[il].ffn_up_exps,
  9325. model.layers[il].ffn_gate_exps,
  9326. model.layers[il].ffn_down_exps,
  9327. n_expert, n_expert_used,
  9328. LLM_FFN_SILU, true,
  9329. false, 0.0,
  9330. cb, il);
  9331. cb(cur, "ffn_moe_out", il);
  9332. }
  9333. // For Granite architecture
  9334. if (hparams.f_residual_scale) {
  9335. cur = ggml_scale(ctx0, cur, hparams.f_residual_scale);
  9336. }
  9337. cur = ggml_add(ctx0, cur, ffn_inp);
  9338. cb(cur, "ffn_out", il);
  9339. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9340. cb(cur, "l_out", il);
  9341. // input for next layer
  9342. inpL = cur;
  9343. }
  9344. cur = inpL;
  9345. cur = llm_build_norm(ctx0, cur, hparams,
  9346. model.output_norm, NULL,
  9347. LLM_NORM_RMS, cb, -1);
  9348. cb(cur, "result_norm", -1);
  9349. // lm_head
  9350. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9351. // For Granite architecture
  9352. if (hparams.f_logit_scale) {
  9353. cur = ggml_scale(ctx0, cur, 1.0f / hparams.f_logit_scale);
  9354. }
  9355. cb(cur, "result_output", -1);
  9356. ggml_build_forward_expand(gf, cur);
  9357. return gf;
  9358. }
  9359. struct ggml_cgraph * build_baichuan() {
  9360. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9361. const int64_t n_embd_head = hparams.n_embd_head_v;
  9362. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9363. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9364. struct ggml_tensor * cur;
  9365. struct ggml_tensor * inpL;
  9366. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9367. // inp_pos - contains the positions
  9368. struct ggml_tensor * inp_pos = model.type == MODEL_7B ? build_inp_pos() : nullptr;
  9369. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9370. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9371. for (int il = 0; il < n_layer; ++il) {
  9372. struct ggml_tensor * inpSA = inpL;
  9373. cur = llm_build_norm(ctx0, inpL, hparams,
  9374. model.layers[il].attn_norm, NULL,
  9375. LLM_NORM_RMS, cb, il);
  9376. cb(cur, "attn_norm", il);
  9377. // self-attention
  9378. {
  9379. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9380. cb(Qcur, "Qcur", il);
  9381. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9382. cb(Kcur, "Kcur", il);
  9383. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9384. cb(Vcur, "Vcur", il);
  9385. switch (model.type) {
  9386. case MODEL_7B:
  9387. Qcur = ggml_rope_ext(
  9388. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9389. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9390. ext_factor, attn_factor, beta_fast, beta_slow
  9391. );
  9392. Kcur = ggml_rope_ext(
  9393. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9394. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9395. ext_factor, attn_factor, beta_fast, beta_slow
  9396. );
  9397. break;
  9398. case MODEL_13B:
  9399. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  9400. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  9401. break;
  9402. default:
  9403. GGML_ABORT("fatal error");
  9404. }
  9405. cb(Qcur, "Qcur", il);
  9406. cb(Kcur, "Kcur", il);
  9407. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9408. model.layers[il].wo, NULL,
  9409. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9410. }
  9411. if (il == n_layer - 1) {
  9412. // skip computing output for unused tokens
  9413. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9414. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9415. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9416. }
  9417. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9418. cb(ffn_inp, "ffn_inp", il);
  9419. // feed-forward network
  9420. {
  9421. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9422. model.layers[il].ffn_norm, NULL,
  9423. LLM_NORM_RMS, cb, il);
  9424. cb(cur, "ffn_norm", il);
  9425. cur = llm_build_ffn(ctx0, lctx, cur,
  9426. model.layers[il].ffn_up, NULL, NULL,
  9427. model.layers[il].ffn_gate, NULL, NULL,
  9428. model.layers[il].ffn_down, NULL, NULL,
  9429. NULL,
  9430. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9431. cb(cur, "ffn_out", il);
  9432. }
  9433. cur = ggml_add(ctx0, cur, ffn_inp);
  9434. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9435. cb(cur, "l_out", il);
  9436. // input for next layer
  9437. inpL = cur;
  9438. }
  9439. cur = inpL;
  9440. cur = llm_build_norm(ctx0, cur, hparams,
  9441. model.output_norm, NULL,
  9442. LLM_NORM_RMS, cb, -1);
  9443. cb(cur, "result_norm", -1);
  9444. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9445. cb(cur, "result_output", -1);
  9446. ggml_build_forward_expand(gf, cur);
  9447. return gf;
  9448. }
  9449. struct ggml_cgraph * build_mllama() {
  9450. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9451. // mutable variable, needed during the last layer of the computation to skip unused tokens
  9452. int32_t n_tokens = this->n_tokens;
  9453. const int64_t n_embd_head = hparams.n_embd_head_v;
  9454. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9455. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9456. struct ggml_tensor * cur;
  9457. struct ggml_tensor * inpL;
  9458. struct ggml_tensor * inpCAS;
  9459. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9460. inpCAS = llm_build_inp_cross_attn_state(ctx0, lctx, hparams, cb);
  9461. // inp_pos - contains the positions
  9462. struct ggml_tensor * inp_pos = build_inp_pos();
  9463. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9464. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9465. for (int il = 0; il < n_layer; ++il) {
  9466. struct ggml_tensor * inpSA = inpL;
  9467. // norm
  9468. cur = llm_build_norm(ctx0, inpL, hparams,
  9469. model.layers[il].attn_norm, NULL,
  9470. LLM_NORM_RMS, cb, il);
  9471. cb(cur, "attn_norm", il);
  9472. if (hparams.cross_attention_layer(il)) {
  9473. if (!lctx.cross_attn_state) {
  9474. continue;
  9475. }
  9476. // cross attention layer
  9477. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].cross_attn_q_proj, cur);
  9478. cb(Qcur, "Qcur", il);
  9479. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9480. cb(Qcur, "Qcur", il);
  9481. Qcur = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  9482. cb(Qcur, "Qcur", il);
  9483. // TODO: is this required?
  9484. Qcur = ggml_cont(ctx0, Qcur);
  9485. cb(Qcur, "Qcur", il);
  9486. Qcur = llm_build_norm(ctx0, Qcur, hparams, model.layers[il].cross_attn_q_norm, NULL, LLM_NORM_RMS, cb, il);
  9487. cb(Qcur, "Qcur", il);
  9488. struct ggml_tensor * Kcur;
  9489. if (lctx.cross_attn_state_first_pass) {
  9490. Kcur = ggml_mul_mat(ctx0, model.layers[il].cross_attn_k_proj, inpCAS);
  9491. cb(Kcur, "Kcur", il);
  9492. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, 6404);
  9493. cb(Kcur, "Kcur", il);
  9494. Kcur = ggml_permute(ctx0, Kcur, 0, 2, 1, 3);
  9495. cb(Kcur, "Kcur", il);
  9496. // TODO: is this required?
  9497. Kcur = ggml_cont(ctx0, Kcur);
  9498. cb(Kcur, "Kcur", il);
  9499. Kcur = llm_build_norm(ctx0, Kcur, hparams, model.layers[il].cross_attn_k_norm, NULL, LLM_NORM_RMS, cb, il);
  9500. cb(Kcur, "Kcur", il);
  9501. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, kv_self.k_l[il]));
  9502. } else {
  9503. Kcur = ggml_view_tensor(ctx0, kv_self.k_l[il]);
  9504. cb(Kcur, "Kcur (view)", il);
  9505. }
  9506. struct ggml_tensor * Vcur;
  9507. if (lctx.cross_attn_state_first_pass) {
  9508. Vcur = ggml_mul_mat(ctx0, model.layers[il].cross_attn_v_proj, inpCAS);
  9509. cb(Vcur, "Vcur", il);
  9510. Vcur = ggml_reshape_3d(ctx0, Vcur, n_embd_head, n_head_kv, 6404);
  9511. cb(Vcur, "Vcur", il);
  9512. Vcur = ggml_permute(ctx0, Vcur, 0, 2, 1, 3);
  9513. cb(Vcur, "Vcur", il);
  9514. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, kv_self.v_l[il]));
  9515. } else {
  9516. Vcur = ggml_view_tensor(ctx0, kv_self.v_l[il]);
  9517. cb(Vcur, "Vcur (view)", il);
  9518. }
  9519. struct ggml_tensor * kq = ggml_mul_mat(ctx0, Kcur, Qcur);
  9520. cb(kq, "kq", il);
  9521. kq = ggml_scale_inplace(ctx0, kq, 1.0f/sqrtf(float(n_embd_head)));
  9522. cb(kq, "kq_scaled", il);
  9523. // TODO: apply causal masks
  9524. struct ggml_tensor * kq_soft_max = ggml_soft_max_inplace(ctx0, kq);
  9525. cb(kq_soft_max, "kq_soft_max", il);
  9526. Vcur = ggml_cont(ctx0, ggml_transpose(ctx0, Vcur));
  9527. cb(Vcur, "Vcur", il);
  9528. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, Vcur, kq_soft_max);
  9529. cb(kqv, "kqv", il);
  9530. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  9531. cb(kqv_merged, "kqv_merged", il);
  9532. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_head_v*n_head, n_tokens);
  9533. cb(cur, "kqv_merged_cont", il);
  9534. cur = ggml_mul_mat(ctx0, model.layers[il].cross_attn_o_proj, cur);
  9535. cb(cur, "cur", il);
  9536. // TODO: do this in place once?
  9537. cur = ggml_mul(ctx0, cur, ggml_tanh(ctx0, model.layers[il].cross_attn_attn_gate));
  9538. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9539. cb(ffn_inp, "ffn_inp", il);
  9540. // feed-forward network
  9541. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9542. model.layers[il].ffn_norm, NULL,
  9543. LLM_NORM_RMS, cb, il);
  9544. cb(cur, "ffn_norm", il);
  9545. cur = llm_build_ffn(ctx0, lctx, cur,
  9546. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9547. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  9548. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9549. NULL,
  9550. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9551. cb(cur, "ffn_out", il);
  9552. // TODO: do this inplace once?
  9553. cur = ggml_add_inplace(ctx0, ggml_mul_inplace(ctx0, cur, ggml_tanh(ctx0, model.layers[il].cross_attn_mlp_gate)), ffn_inp);
  9554. cb(cur, "ffn_out", il);
  9555. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9556. cb(cur, "l_out", il);
  9557. // input for next layer
  9558. inpL = cur;
  9559. } else {
  9560. // self attention layer
  9561. // rope freq factors for llama3; may return nullptr for llama2 and other models
  9562. struct ggml_tensor * rope_factors = build_rope_factors(il);
  9563. // compute Q and K and RoPE them
  9564. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9565. cb(Qcur, "Qcur", il);
  9566. if (model.layers[il].bq) {
  9567. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9568. cb(Qcur, "Qcur", il);
  9569. }
  9570. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9571. cb(Kcur, "Kcur", il);
  9572. if (model.layers[il].bk) {
  9573. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9574. cb(Kcur, "Kcur", il);
  9575. }
  9576. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9577. cb(Vcur, "Vcur", il);
  9578. if (model.layers[il].bv) {
  9579. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9580. cb(Vcur, "Vcur", il);
  9581. }
  9582. Qcur = ggml_rope_ext(
  9583. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  9584. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9585. ext_factor, attn_factor, beta_fast, beta_slow
  9586. );
  9587. cb(Qcur, "Qcur", il);
  9588. Kcur = ggml_rope_ext(
  9589. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  9590. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9591. ext_factor, attn_factor, beta_fast, beta_slow
  9592. );
  9593. cb(Kcur, "Kcur", il);
  9594. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9595. model.layers[il].wo, model.layers[il].bo,
  9596. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9597. if (il == n_layer - 1) {
  9598. // skip computing output for unused tokens
  9599. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9600. n_tokens = n_outputs;
  9601. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9602. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9603. }
  9604. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9605. cb(ffn_inp, "ffn_inp", il);
  9606. // feed-forward network
  9607. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9608. model.layers[il].ffn_norm, NULL,
  9609. LLM_NORM_RMS, cb, il);
  9610. cb(cur, "ffn_norm", il);
  9611. cur = llm_build_ffn(ctx0, lctx, cur,
  9612. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9613. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  9614. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9615. NULL,
  9616. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9617. cb(cur, "ffn_out", il);
  9618. cur = ggml_add(ctx0, cur, ffn_inp);
  9619. cb(cur, "ffn_out", il);
  9620. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9621. cb(cur, "l_out", il);
  9622. // input for next layer
  9623. inpL = cur;
  9624. }
  9625. }
  9626. cur = inpL;
  9627. cur = llm_build_norm(ctx0, cur, hparams,
  9628. model.output_norm, NULL,
  9629. LLM_NORM_RMS, cb, -1);
  9630. cb(cur, "result_norm", -1);
  9631. // lm_head
  9632. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9633. cb(cur, "result_output", -1);
  9634. ggml_build_forward_expand(gf, cur);
  9635. return gf;
  9636. }
  9637. struct ggml_cgraph * build_xverse() {
  9638. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  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, batch, 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. for (int il = 0; il < n_layer; ++il) {
  9650. struct ggml_tensor * inpSA = inpL;
  9651. cur = llm_build_norm(ctx0, inpL, hparams,
  9652. model.layers[il].attn_norm, NULL,
  9653. LLM_NORM_RMS, cb, il);
  9654. cb(cur, "attn_norm", il);
  9655. // self-attention
  9656. {
  9657. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9658. cb(Qcur, "Qcur", il);
  9659. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9660. cb(Kcur, "Kcur", il);
  9661. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9662. cb(Vcur, "Vcur", il);
  9663. Qcur = ggml_rope_ext(
  9664. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9665. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9666. ext_factor, attn_factor, beta_fast, beta_slow
  9667. );
  9668. cb(Qcur, "Qcur", il);
  9669. Kcur = ggml_rope_ext(
  9670. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9671. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9672. ext_factor, attn_factor, beta_fast, beta_slow
  9673. );
  9674. cb(Kcur, "Kcur", il);
  9675. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9676. model.layers[il].wo, NULL,
  9677. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9678. }
  9679. if (il == n_layer - 1) {
  9680. // skip computing output for unused tokens
  9681. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9682. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9683. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9684. }
  9685. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9686. cb(ffn_inp, "ffn_inp", il);
  9687. // feed-forward network
  9688. {
  9689. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9690. model.layers[il].ffn_norm, NULL,
  9691. LLM_NORM_RMS, cb, il);
  9692. cb(cur, "ffn_norm", il);
  9693. cur = llm_build_ffn(ctx0, lctx, cur,
  9694. model.layers[il].ffn_up, NULL, NULL,
  9695. model.layers[il].ffn_gate, NULL, NULL,
  9696. model.layers[il].ffn_down, NULL, NULL,
  9697. NULL,
  9698. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9699. cb(cur, "ffn_out", il);
  9700. }
  9701. cur = ggml_add(ctx0, cur, ffn_inp);
  9702. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9703. cb(cur, "l_out", il);
  9704. // input for next layer
  9705. inpL = cur;
  9706. }
  9707. cur = inpL;
  9708. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, NULL, LLM_NORM_RMS, cb, -1);
  9709. cb(cur, "result_norm", -1);
  9710. // lm_head
  9711. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9712. cb(cur, "result_output", -1);
  9713. ggml_build_forward_expand(gf, cur);
  9714. return gf;
  9715. }
  9716. struct ggml_cgraph * build_falcon() {
  9717. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9718. const int64_t n_embd_head = hparams.n_embd_head_v;
  9719. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  9720. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9721. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9722. struct ggml_tensor * cur;
  9723. struct ggml_tensor * inpL;
  9724. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9725. // inp_pos - contains the positions
  9726. struct ggml_tensor * inp_pos = build_inp_pos();
  9727. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9728. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9729. for (int il = 0; il < n_layer; ++il) {
  9730. struct ggml_tensor * attn_norm;
  9731. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  9732. model.layers[il].attn_norm,
  9733. model.layers[il].attn_norm_b,
  9734. LLM_NORM, cb, il);
  9735. cb(attn_norm, "attn_norm", il);
  9736. // self-attention
  9737. {
  9738. if (model.layers[il].attn_norm_2) {
  9739. // Falcon-40B
  9740. cur = llm_build_norm(ctx0, inpL, hparams,
  9741. model.layers[il].attn_norm_2,
  9742. model.layers[il].attn_norm_2_b,
  9743. LLM_NORM, cb, il);
  9744. cb(cur, "attn_norm_2", il);
  9745. } else {
  9746. cur = attn_norm;
  9747. }
  9748. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  9749. cb(cur, "wqkv", il);
  9750. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  9751. 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)));
  9752. 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)));
  9753. cb(Qcur, "Qcur", il);
  9754. cb(Kcur, "Kcur", il);
  9755. cb(Vcur, "Vcur", il);
  9756. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9757. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  9758. // using mode = 2 for neox mode
  9759. Qcur = ggml_rope_ext(
  9760. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  9761. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  9762. );
  9763. cb(Qcur, "Qcur", il);
  9764. Kcur = ggml_rope_ext(
  9765. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  9766. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  9767. );
  9768. cb(Kcur, "Kcur", il);
  9769. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9770. model.layers[il].wo, NULL,
  9771. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9772. }
  9773. if (il == n_layer - 1) {
  9774. // skip computing output for unused tokens
  9775. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9776. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9777. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9778. attn_norm = ggml_get_rows(ctx0, attn_norm, inp_out_ids);
  9779. }
  9780. struct ggml_tensor * ffn_inp = cur;
  9781. // feed forward
  9782. {
  9783. cur = llm_build_ffn(ctx0, lctx, attn_norm, // !! use the attn norm, not the result
  9784. model.layers[il].ffn_up, NULL, NULL,
  9785. NULL, NULL, NULL,
  9786. model.layers[il].ffn_down, NULL, NULL,
  9787. NULL,
  9788. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  9789. cb(cur, "ffn_out", il);
  9790. }
  9791. cur = ggml_add(ctx0, cur, ffn_inp);
  9792. cur = ggml_add(ctx0, cur, inpL);
  9793. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9794. cb(cur, "l_out", il);
  9795. // input for next layer
  9796. inpL = cur;
  9797. }
  9798. cur = inpL;
  9799. // norm
  9800. cur = llm_build_norm(ctx0, cur, hparams,
  9801. model.output_norm,
  9802. model.output_norm_b,
  9803. LLM_NORM, cb, -1);
  9804. cb(cur, "result_norm", -1);
  9805. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9806. cb(cur, "result_output", -1);
  9807. ggml_build_forward_expand(gf, cur);
  9808. return gf;
  9809. }
  9810. struct ggml_cgraph * build_grok() {
  9811. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9812. // mutable variable, needed during the last layer of the computation to skip unused tokens
  9813. int32_t n_tokens = this->n_tokens;
  9814. const int64_t n_embd_head = hparams.n_embd_head_v;
  9815. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9816. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9817. struct ggml_tensor * cur;
  9818. struct ggml_tensor * inpL;
  9819. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9820. // multiply by embedding_multiplier_scale of 78.38367176906169
  9821. inpL = ggml_scale(ctx0, inpL, 78.38367176906169f);
  9822. // inp_pos - contains the positions
  9823. struct ggml_tensor * inp_pos = build_inp_pos();
  9824. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9825. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9826. for (int il = 0; il < n_layer; ++il) {
  9827. struct ggml_tensor * inpSA = inpL;
  9828. // norm
  9829. cur = llm_build_norm(ctx0, inpL, hparams,
  9830. model.layers[il].attn_norm, NULL,
  9831. LLM_NORM_RMS, cb, il);
  9832. cb(cur, "attn_norm", il);
  9833. // self-attention
  9834. {
  9835. // compute Q and K and RoPE them
  9836. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9837. cb(Qcur, "Qcur", il);
  9838. if (model.layers[il].bq) {
  9839. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9840. cb(Qcur, "Qcur", il);
  9841. }
  9842. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9843. cb(Kcur, "Kcur", il);
  9844. if (model.layers[il].bk) {
  9845. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9846. cb(Kcur, "Kcur", il);
  9847. }
  9848. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9849. cb(Vcur, "Vcur", il);
  9850. if (model.layers[il].bv) {
  9851. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9852. cb(Vcur, "Vcur", il);
  9853. }
  9854. Qcur = ggml_rope_ext(
  9855. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9856. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9857. ext_factor, attn_factor, beta_fast, beta_slow
  9858. );
  9859. cb(Qcur, "Qcur", il);
  9860. Kcur = ggml_rope_ext(
  9861. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9862. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9863. ext_factor, attn_factor, beta_fast, beta_slow
  9864. );
  9865. cb(Kcur, "Kcur", il);
  9866. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9867. model.layers[il].wo, model.layers[il].bo,
  9868. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  9869. }
  9870. if (il == n_layer - 1) {
  9871. // skip computing output for unused tokens
  9872. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9873. n_tokens = n_outputs;
  9874. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9875. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9876. }
  9877. // Grok
  9878. // if attn_out_norm is present then apply it before adding the input
  9879. if (model.layers[il].attn_out_norm) {
  9880. cur = llm_build_norm(ctx0, cur, hparams,
  9881. model.layers[il].attn_out_norm, NULL,
  9882. LLM_NORM_RMS, cb, il);
  9883. cb(cur, "attn_out_norm", il);
  9884. }
  9885. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9886. cb(ffn_inp, "ffn_inp", il);
  9887. // feed-forward network
  9888. // MoE branch
  9889. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9890. model.layers[il].ffn_norm, NULL,
  9891. LLM_NORM_RMS, cb, il);
  9892. cb(cur, "ffn_norm", il);
  9893. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  9894. model.layers[il].ffn_gate_inp,
  9895. model.layers[il].ffn_up_exps,
  9896. model.layers[il].ffn_gate_exps,
  9897. model.layers[il].ffn_down_exps,
  9898. n_expert, n_expert_used,
  9899. LLM_FFN_GELU, true,
  9900. false, 0.0,
  9901. cb, il);
  9902. cb(cur, "ffn_moe_out", il);
  9903. // Grok
  9904. // if layer_out_norm is present then apply it before adding the input
  9905. // Idea: maybe ffn_out_norm is a better name
  9906. if (model.layers[il].layer_out_norm) {
  9907. cur = llm_build_norm(ctx0, cur, hparams,
  9908. model.layers[il].layer_out_norm, NULL,
  9909. LLM_NORM_RMS, cb, il);
  9910. cb(cur, "layer_out_norm", il);
  9911. }
  9912. cur = ggml_add(ctx0, cur, ffn_inp);
  9913. cb(cur, "ffn_out", il);
  9914. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9915. cb(cur, "l_out", il);
  9916. // input for next layer
  9917. inpL = cur;
  9918. }
  9919. cur = inpL;
  9920. cur = llm_build_norm(ctx0, cur, hparams,
  9921. model.output_norm, NULL,
  9922. LLM_NORM_RMS, cb, -1);
  9923. cb(cur, "result_norm", -1);
  9924. // lm_head
  9925. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9926. // Grok
  9927. // multiply logits by output_multiplier_scale of 0.5773502691896257
  9928. cur = ggml_scale(ctx0, cur, 0.5773502691896257f);
  9929. cb(cur, "result_output", -1);
  9930. ggml_build_forward_expand(gf, cur);
  9931. return gf;
  9932. }
  9933. struct ggml_cgraph * build_dbrx() {
  9934. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9935. // mutable variable, needed during the last layer of the computation to skip unused tokens
  9936. int32_t n_tokens = this->n_tokens;
  9937. const int64_t n_embd_head = hparams.n_embd_head_v;
  9938. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  9939. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9940. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9941. struct ggml_tensor * cur;
  9942. struct ggml_tensor * inpL;
  9943. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9944. // inp_pos - contains the positions
  9945. struct ggml_tensor * inp_pos = build_inp_pos();
  9946. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9947. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9948. for (int il = 0; il < n_layer; ++il) {
  9949. struct ggml_tensor * inpSA = inpL;
  9950. // norm
  9951. cur = llm_build_norm(ctx0, inpL, hparams,
  9952. model.layers[il].attn_norm, NULL,
  9953. LLM_NORM, cb, il);
  9954. cb(cur, "attn_norm", il);
  9955. // self-attention
  9956. {
  9957. struct ggml_tensor * Qcur = nullptr;
  9958. struct ggml_tensor * Kcur = nullptr;
  9959. struct ggml_tensor * Vcur = nullptr;
  9960. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  9961. cb(cur, "wqkv", il);
  9962. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  9963. cb(cur, "wqkv_clamped", il);
  9964. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  9965. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  9966. 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)));
  9967. cb(Qcur, "Qcur", il);
  9968. cb(Kcur, "Kcur", il);
  9969. cb(Vcur, "Vcur", il);
  9970. Qcur = ggml_rope_ext(
  9971. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9972. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9973. ext_factor, attn_factor, beta_fast, beta_slow
  9974. );
  9975. cb(Qcur, "Qcur", il);
  9976. Kcur = ggml_rope_ext(
  9977. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9978. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9979. ext_factor, attn_factor, beta_fast, beta_slow
  9980. );
  9981. cb(Kcur, "Kcur", il);
  9982. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9983. model.layers[il].wo, NULL,
  9984. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9985. }
  9986. if (il == n_layer - 1) {
  9987. // skip computing output for unused tokens
  9988. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9989. n_tokens = n_outputs;
  9990. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9991. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9992. }
  9993. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9994. cb(ffn_inp, "ffn_inp", il);
  9995. // feed-forward network
  9996. // MoE branch
  9997. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9998. model.layers[il].attn_out_norm, NULL,
  9999. LLM_NORM, cb, il);
  10000. cb(cur, "attn_out_norm", il);
  10001. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  10002. model.layers[il].ffn_gate_inp,
  10003. model.layers[il].ffn_up_exps,
  10004. model.layers[il].ffn_gate_exps,
  10005. model.layers[il].ffn_down_exps,
  10006. n_expert, n_expert_used,
  10007. LLM_FFN_SILU, true,
  10008. false, 0.0,
  10009. cb, il);
  10010. cb(cur, "ffn_moe_out", il);
  10011. cur = ggml_add(ctx0, cur, ffn_inp);
  10012. cb(cur, "ffn_out", il);
  10013. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10014. cb(cur, "l_out", il);
  10015. // input for next layer
  10016. inpL = cur;
  10017. }
  10018. cur = inpL;
  10019. cur = llm_build_norm(ctx0, cur, hparams,
  10020. model.output_norm, NULL,
  10021. LLM_NORM, cb, -1);
  10022. cb(cur, "result_norm", -1);
  10023. // lm_head
  10024. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10025. cb(cur, "result_output", -1);
  10026. ggml_build_forward_expand(gf, cur);
  10027. return gf;
  10028. }
  10029. struct ggml_cgraph * build_starcoder() {
  10030. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10031. const int64_t n_embd_head = hparams.n_embd_head_v;
  10032. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10033. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10034. struct ggml_tensor * cur;
  10035. struct ggml_tensor * inpL;
  10036. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10037. // inp_pos - contains the positions
  10038. struct ggml_tensor * inp_pos = build_inp_pos();
  10039. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10040. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10041. struct ggml_tensor * pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  10042. cb(pos, "pos_embd", -1);
  10043. inpL = ggml_add(ctx0, inpL, pos);
  10044. cb(inpL, "inpL", -1);
  10045. for (int il = 0; il < n_layer; ++il) {
  10046. cur = llm_build_norm(ctx0, inpL, hparams,
  10047. model.layers[il].attn_norm,
  10048. model.layers[il].attn_norm_b,
  10049. LLM_NORM, cb, il);
  10050. cb(cur, "attn_norm", il);
  10051. // self-attention
  10052. {
  10053. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10054. cb(cur, "wqkv", il);
  10055. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10056. cb(cur, "bqkv", il);
  10057. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10058. 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)));
  10059. 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)));
  10060. cb(Qcur, "Qcur", il);
  10061. cb(Kcur, "Kcur", il);
  10062. cb(Vcur, "Vcur", il);
  10063. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10064. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10065. model.layers[il].wo, model.layers[il].bo,
  10066. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10067. }
  10068. if (il == n_layer - 1) {
  10069. // skip computing output for unused tokens
  10070. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10071. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10072. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10073. }
  10074. // add the input
  10075. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10076. cb(ffn_inp, "ffn_inp", il);
  10077. // FF
  10078. {
  10079. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10080. model.layers[il].ffn_norm,
  10081. model.layers[il].ffn_norm_b,
  10082. LLM_NORM, cb, il);
  10083. cb(cur, "ffn_norm", il);
  10084. cur = llm_build_ffn(ctx0, lctx, cur,
  10085. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10086. NULL, NULL, NULL,
  10087. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10088. NULL,
  10089. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10090. cb(cur, "ffn_out", il);
  10091. }
  10092. cur = ggml_add(ctx0, cur, ffn_inp);
  10093. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10094. cb(cur, "l_out", il);
  10095. // input for next layer
  10096. inpL = cur;
  10097. }
  10098. cur = llm_build_norm(ctx0, inpL, hparams,
  10099. model.output_norm,
  10100. model.output_norm_b,
  10101. LLM_NORM, cb, -1);
  10102. cb(cur, "result_norm", -1);
  10103. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10104. cb(cur, "result_output", -1);
  10105. ggml_build_forward_expand(gf, cur);
  10106. return gf;
  10107. }
  10108. struct ggml_cgraph * build_refact() {
  10109. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10110. const int64_t n_embd_head = hparams.n_embd_head_v;
  10111. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10112. struct ggml_tensor * cur;
  10113. struct ggml_tensor * inpL;
  10114. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10115. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10116. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10117. for (int il = 0; il < n_layer; ++il) {
  10118. struct ggml_tensor * inpSA = inpL;
  10119. cur = llm_build_norm(ctx0, inpL, hparams,
  10120. model.layers[il].attn_norm, NULL,
  10121. LLM_NORM_RMS, cb, il);
  10122. cb(cur, "attn_norm", il);
  10123. // self-attention
  10124. {
  10125. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10126. cb(Qcur, "Qcur", il);
  10127. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10128. cb(Kcur, "Kcur", il);
  10129. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10130. cb(Vcur, "Vcur", il);
  10131. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10132. cb(Kcur, "Kcur", il);
  10133. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10134. cb(Qcur, "Qcur", il);
  10135. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10136. model.layers[il].wo, NULL,
  10137. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10138. }
  10139. if (il == n_layer - 1) {
  10140. // skip computing output for unused tokens
  10141. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10142. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10143. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10144. }
  10145. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10146. cb(ffn_inp, "ffn_inp", il);
  10147. // feed-forward network
  10148. {
  10149. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10150. model.layers[il].ffn_norm, NULL,
  10151. LLM_NORM_RMS, cb, il);
  10152. cb(cur, "ffn_norm", il);
  10153. cur = llm_build_ffn(ctx0, lctx, cur,
  10154. model.layers[il].ffn_up, NULL, NULL,
  10155. model.layers[il].ffn_gate, NULL, NULL,
  10156. model.layers[il].ffn_down, NULL, NULL,
  10157. NULL,
  10158. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10159. cb(cur, "ffn_out", il);
  10160. }
  10161. cur = ggml_add(ctx0, cur, ffn_inp);
  10162. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10163. cb(cur, "l_out", il);
  10164. // input for next layer
  10165. inpL = cur;
  10166. }
  10167. cur = inpL;
  10168. cur = llm_build_norm(ctx0, cur, hparams,
  10169. model.output_norm, NULL,
  10170. LLM_NORM_RMS, cb, -1);
  10171. cb(cur, "result_norm", -1);
  10172. // lm_head
  10173. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10174. cb(cur, "result_output", -1);
  10175. ggml_build_forward_expand(gf, cur);
  10176. return gf;
  10177. }
  10178. struct ggml_cgraph * build_bert() {
  10179. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10180. const int64_t n_embd_head = hparams.n_embd_head_v;
  10181. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10182. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10183. struct ggml_tensor * cur;
  10184. struct ggml_tensor * inpL;
  10185. struct ggml_tensor * inp_pos = nullptr;
  10186. if (model.arch != LLM_ARCH_JINA_BERT_V2) {
  10187. inp_pos = build_inp_pos();
  10188. }
  10189. // construct input embeddings (token, type, position)
  10190. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10191. // token types are hardcoded to zero ("Sentence A")
  10192. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  10193. inpL = ggml_add(ctx0, inpL, type_row0);
  10194. if (model.arch == LLM_ARCH_BERT) {
  10195. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  10196. }
  10197. cb(inpL, "inp_embd", -1);
  10198. // embed layer norm
  10199. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  10200. cb(inpL, "inp_norm", -1);
  10201. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10202. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(false);
  10203. // iterate layers
  10204. for (int il = 0; il < n_layer; ++il) {
  10205. struct ggml_tensor * cur = inpL;
  10206. struct ggml_tensor * Qcur;
  10207. struct ggml_tensor * Kcur;
  10208. struct ggml_tensor * Vcur;
  10209. // self-attention
  10210. if (model.arch == LLM_ARCH_BERT || model.arch == LLM_ARCH_JINA_BERT_V2) {
  10211. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  10212. cb(Qcur, "Qcur", il);
  10213. if (model.layers[il].attn_q_norm) {
  10214. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  10215. model.layers[il].attn_q_norm,
  10216. model.layers[il].attn_q_norm_b,
  10217. LLM_NORM, cb, il);
  10218. }
  10219. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  10220. cb(Kcur, "Kcur", il);
  10221. if (model.layers[il].attn_k_norm) {
  10222. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  10223. model.layers[il].attn_k_norm,
  10224. model.layers[il].attn_k_norm_b,
  10225. LLM_NORM, cb, il);
  10226. }
  10227. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  10228. cb(Vcur, "Vcur", il);
  10229. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10230. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10231. } else {
  10232. // compute Q and K and RoPE them
  10233. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10234. cb(cur, "wqkv", il);
  10235. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10236. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  10237. 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)));
  10238. cb(Qcur, "Qcur", il);
  10239. cb(Kcur, "Kcur", il);
  10240. cb(Vcur, "Vcur", il);
  10241. Qcur = ggml_rope_ext(
  10242. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10243. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10244. ext_factor, attn_factor, beta_fast, beta_slow
  10245. );
  10246. cb(Qcur, "Qcur", il);
  10247. Kcur = ggml_rope_ext(
  10248. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10249. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10250. ext_factor, attn_factor, beta_fast, beta_slow
  10251. );
  10252. cb(Kcur, "Kcur", il);
  10253. }
  10254. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  10255. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  10256. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  10257. cb(kq, "kq", il);
  10258. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask, 1.0f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  10259. cb(kq, "kq_soft_max_ext", il);
  10260. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  10261. cb(v, "v", il);
  10262. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  10263. cb(kqv, "kqv", il);
  10264. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  10265. cb(kqv_merged, "kqv_merged", il);
  10266. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  10267. cb(cur, "kqv_merged_cont", il);
  10268. ggml_build_forward_expand(gf, cur);
  10269. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  10270. if (model.layers[il].bo) {
  10271. cb(cur, "kqv_wo", il);
  10272. }
  10273. if (model.layers[il].bo) {
  10274. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  10275. }
  10276. cb(cur, "kqv_out", il);
  10277. if (il == n_layer - 1 && pooling_type == LLAMA_POOLING_TYPE_NONE) {
  10278. // skip computing output for unused tokens
  10279. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10280. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10281. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10282. }
  10283. // re-add the layer input
  10284. cur = ggml_add(ctx0, cur, inpL);
  10285. // attention layer norm
  10286. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  10287. if (model.layers[il].attn_norm_2 != nullptr) {
  10288. cur = ggml_add(ctx0, cur, inpL); // re-add the layer input
  10289. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_norm_2, model.layers[il].attn_norm_2_b, LLM_NORM, cb, il);
  10290. }
  10291. struct ggml_tensor * ffn_inp = cur;
  10292. cb(ffn_inp, "ffn_inp", il);
  10293. // feed-forward network
  10294. if (model.arch == LLM_ARCH_BERT) {
  10295. cur = llm_build_ffn(ctx0, lctx, cur,
  10296. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10297. NULL, NULL, NULL,
  10298. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10299. NULL,
  10300. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10301. } else if (model.arch == LLM_ARCH_JINA_BERT_V2) {
  10302. cur = llm_build_ffn(ctx0, lctx, cur,
  10303. model.layers[il].ffn_up, NULL, NULL,
  10304. model.layers[il].ffn_gate, NULL, NULL,
  10305. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10306. NULL,
  10307. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  10308. } else {
  10309. cur = llm_build_ffn(ctx0, lctx, cur,
  10310. model.layers[il].ffn_up, NULL, NULL,
  10311. model.layers[il].ffn_gate, NULL, NULL,
  10312. model.layers[il].ffn_down, NULL, NULL,
  10313. NULL,
  10314. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10315. }
  10316. cb(cur, "ffn_out", il);
  10317. // attentions bypass the intermediate layer
  10318. cur = ggml_add(ctx0, cur, ffn_inp);
  10319. // output layer norm
  10320. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  10321. // input for next layer
  10322. inpL = cur;
  10323. }
  10324. cur = inpL;
  10325. cb(cur, "result_embd", -1);
  10326. ggml_build_forward_expand(gf, cur);
  10327. return gf;
  10328. }
  10329. struct ggml_cgraph * build_bloom() {
  10330. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10331. const int64_t n_embd_head = hparams.n_embd_head_v;
  10332. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10333. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10334. struct ggml_tensor * cur;
  10335. struct ggml_tensor * inpL;
  10336. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10337. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10338. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10339. inpL = llm_build_norm(ctx0, inpL, hparams,
  10340. model.tok_norm,
  10341. model.tok_norm_b,
  10342. LLM_NORM, cb, -1);
  10343. cb(inpL, "inp_norm", -1);
  10344. for (int il = 0; il < n_layer; ++il) {
  10345. cur = llm_build_norm(ctx0, inpL, hparams,
  10346. model.layers[il].attn_norm,
  10347. model.layers[il].attn_norm_b,
  10348. LLM_NORM, cb, il);
  10349. cb(cur, "attn_norm", il);
  10350. // self-attention
  10351. {
  10352. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10353. cb(cur, "wqkv", il);
  10354. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10355. cb(cur, "bqkv", il);
  10356. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10357. 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)));
  10358. 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)));
  10359. cb(Qcur, "Qcur", il);
  10360. cb(Kcur, "Kcur", il);
  10361. cb(Vcur, "Vcur", il);
  10362. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10363. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10364. model.layers[il].wo, model.layers[il].bo,
  10365. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10366. }
  10367. if (il == n_layer - 1) {
  10368. // skip computing output for unused tokens
  10369. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10370. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10371. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10372. }
  10373. // Add the input
  10374. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10375. cb(ffn_inp, "ffn_inp", il);
  10376. // FF
  10377. {
  10378. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10379. model.layers[il].ffn_norm,
  10380. model.layers[il].ffn_norm_b,
  10381. LLM_NORM, cb, il);
  10382. cb(cur, "ffn_norm", il);
  10383. cur = llm_build_ffn(ctx0, lctx, cur,
  10384. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10385. NULL, NULL, NULL,
  10386. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10387. NULL,
  10388. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10389. cb(cur, "ffn_out", il);
  10390. }
  10391. cur = ggml_add(ctx0, cur, ffn_inp);
  10392. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10393. cb(cur, "l_out", il);
  10394. // input for next layer
  10395. inpL = cur;
  10396. }
  10397. cur = llm_build_norm(ctx0, inpL, hparams,
  10398. model.output_norm,
  10399. model.output_norm_b,
  10400. LLM_NORM, cb, -1);
  10401. cb(cur, "result_norm", -1);
  10402. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10403. cb(cur, "result_output", -1);
  10404. ggml_build_forward_expand(gf, cur);
  10405. return gf;
  10406. }
  10407. struct ggml_cgraph * build_mpt() {
  10408. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10409. const int64_t n_embd_head = hparams.n_embd_head_v;
  10410. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10411. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10412. struct ggml_tensor * cur;
  10413. struct ggml_tensor * pos;
  10414. struct ggml_tensor * inpL;
  10415. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10416. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10417. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10418. if (model.pos_embd) {
  10419. // inp_pos - contains the positions
  10420. struct ggml_tensor * inp_pos = build_inp_pos();
  10421. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  10422. cb(pos, "pos_embd", -1);
  10423. inpL = ggml_add(ctx0, inpL, pos);
  10424. cb(inpL, "inpL", -1);
  10425. }
  10426. for (int il = 0; il < n_layer; ++il) {
  10427. struct ggml_tensor * attn_norm;
  10428. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  10429. model.layers[il].attn_norm,
  10430. model.layers[il].attn_norm_b,
  10431. LLM_NORM, cb, il);
  10432. cb(attn_norm, "attn_norm", il);
  10433. // self-attention
  10434. {
  10435. cur = attn_norm;
  10436. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10437. cb(cur, "wqkv", il);
  10438. if (model.layers[il].bqkv){
  10439. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10440. cb(cur, "bqkv", il);
  10441. }
  10442. if (hparams.f_clamp_kqv > 0.0f) {
  10443. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  10444. cb(cur, "wqkv_clamped", il);
  10445. }
  10446. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10447. 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)));
  10448. 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)));
  10449. cb(Qcur, "Qcur", il);
  10450. cb(Kcur, "Kcur", il);
  10451. cb(Vcur, "Vcur", il);
  10452. // Q/K Layernorm
  10453. if (model.layers[il].attn_q_norm) {
  10454. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  10455. model.layers[il].attn_q_norm,
  10456. model.layers[il].attn_q_norm_b,
  10457. LLM_NORM, cb, il);
  10458. cb(Qcur, "Qcur", il);
  10459. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  10460. model.layers[il].attn_k_norm,
  10461. model.layers[il].attn_k_norm_b,
  10462. LLM_NORM, cb, il);
  10463. cb(Kcur, "Kcur", il);
  10464. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10465. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10466. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10467. model.layers[il].wo, model.layers[il].bo,
  10468. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10469. } else {
  10470. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10471. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10472. model.layers[il].wo, model.layers[il].bo,
  10473. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10474. }
  10475. }
  10476. if (il == n_layer - 1) {
  10477. // skip computing output for unused tokens
  10478. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10479. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10480. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10481. }
  10482. // Add the input
  10483. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10484. cb(ffn_inp, "ffn_inp", il);
  10485. // feed forward
  10486. {
  10487. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10488. model.layers[il].ffn_norm,
  10489. model.layers[il].ffn_norm_b,
  10490. LLM_NORM, cb, il);
  10491. cb(cur, "ffn_norm", il);
  10492. cur = llm_build_ffn(ctx0, lctx, cur,
  10493. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10494. NULL, NULL, NULL,
  10495. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10496. model.layers[il].ffn_act,
  10497. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10498. cb(cur, "ffn_out", il);
  10499. }
  10500. cur = ggml_add(ctx0, cur, ffn_inp);
  10501. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10502. cb(cur, "l_out", il);
  10503. // input for next layer
  10504. inpL = cur;
  10505. }
  10506. cur = inpL;
  10507. cur = llm_build_norm(ctx0, cur, hparams,
  10508. model.output_norm,
  10509. model.output_norm_b,
  10510. LLM_NORM, cb, -1);
  10511. cb(cur, "result_norm", -1);
  10512. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10513. cb(cur, "result_output", -1);
  10514. ggml_build_forward_expand(gf, cur);
  10515. return gf;
  10516. }
  10517. struct ggml_cgraph * build_stablelm() {
  10518. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  10519. const int64_t n_embd_head = hparams.n_embd_head_v;
  10520. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10521. struct ggml_tensor * cur;
  10522. struct ggml_tensor * inpL;
  10523. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10524. // inp_pos - contains the positions
  10525. struct ggml_tensor * inp_pos = build_inp_pos();
  10526. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10527. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10528. for (int il = 0; il < n_layer; ++il) {
  10529. // norm
  10530. cur = llm_build_norm(ctx0, inpL, hparams,
  10531. model.layers[il].attn_norm,
  10532. model.layers[il].attn_norm_b,
  10533. LLM_NORM, cb, il);
  10534. cb(cur, "attn_norm", il);
  10535. struct ggml_tensor * inpSA = cur;
  10536. // self-attention
  10537. {
  10538. // compute Q and K and RoPE them
  10539. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10540. cb(Qcur, "Qcur", il);
  10541. if (model.layers[il].bq) {
  10542. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10543. cb(Qcur, "Qcur", il);
  10544. }
  10545. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10546. cb(Kcur, "Kcur", il);
  10547. if (model.layers[il].bk) {
  10548. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10549. cb(Kcur, "Kcur", il);
  10550. }
  10551. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10552. cb(Vcur, "Vcur", il);
  10553. if (model.layers[il].bv) {
  10554. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  10555. cb(Vcur, "Vcur", il);
  10556. }
  10557. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10558. cb(Qcur, "Qcur", il);
  10559. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10560. cb(Kcur, "Kcur", il);
  10561. if (model.layers[il].attn_q_norm) {
  10562. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  10563. model.layers[il].attn_q_norm,
  10564. NULL,
  10565. LLM_NORM, cb, il);
  10566. cb(Qcur, "Qcur", il);
  10567. }
  10568. if (model.layers[il].attn_k_norm) {
  10569. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  10570. model.layers[il].attn_k_norm,
  10571. NULL,
  10572. LLM_NORM, cb, il);
  10573. cb(Kcur, "Kcur", il);
  10574. }
  10575. Qcur = ggml_rope_ext(
  10576. ctx0, Qcur, inp_pos, nullptr,
  10577. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10578. ext_factor, attn_factor, beta_fast, beta_slow
  10579. );
  10580. cb(Qcur, "Qcur", il);
  10581. Kcur = ggml_rope_ext(
  10582. ctx0, Kcur, inp_pos, nullptr,
  10583. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10584. ext_factor, attn_factor, beta_fast, beta_slow
  10585. );
  10586. cb(Kcur, "Kcur", il);
  10587. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10588. model.layers[il].wo, NULL,
  10589. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10590. }
  10591. if (il == n_layer - 1) {
  10592. // skip computing output for unused tokens
  10593. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10594. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10595. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10596. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10597. }
  10598. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10599. cb(ffn_inp, "ffn_inp", il);
  10600. // feed-forward network
  10601. {
  10602. if (model.layers[il].ffn_norm) {
  10603. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10604. model.layers[il].ffn_norm,
  10605. model.layers[il].ffn_norm_b,
  10606. LLM_NORM, cb, il);
  10607. cb(cur, "ffn_norm", il);
  10608. } else {
  10609. // parallel residual
  10610. cur = inpSA;
  10611. }
  10612. cur = llm_build_ffn(ctx0, lctx, cur,
  10613. model.layers[il].ffn_up, NULL, NULL,
  10614. model.layers[il].ffn_gate, NULL, NULL,
  10615. model.layers[il].ffn_down, NULL, NULL,
  10616. NULL,
  10617. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10618. cb(cur, "ffn_out", il);
  10619. }
  10620. cur = ggml_add(ctx0, cur, ffn_inp);
  10621. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10622. cb(cur, "l_out", il);
  10623. // input for next layer
  10624. inpL = cur;
  10625. }
  10626. cur = inpL;
  10627. cur = llm_build_norm(ctx0, cur, hparams,
  10628. model.output_norm,
  10629. model.output_norm_b,
  10630. LLM_NORM, cb, -1);
  10631. cb(cur, "result_norm", -1);
  10632. // lm_head
  10633. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10634. cb(cur, "result_output", -1);
  10635. ggml_build_forward_expand(gf, cur);
  10636. return gf;
  10637. }
  10638. struct ggml_cgraph * build_qwen() {
  10639. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10640. const int64_t n_embd_head = hparams.n_embd_head_v;
  10641. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10642. struct ggml_tensor * cur;
  10643. struct ggml_tensor * inpL;
  10644. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10645. // inp_pos - contains the positions
  10646. struct ggml_tensor * inp_pos = build_inp_pos();
  10647. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10648. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10649. for (int il = 0; il < n_layer; ++il) {
  10650. struct ggml_tensor * inpSA = inpL;
  10651. cur = llm_build_norm(ctx0, inpL, hparams,
  10652. model.layers[il].attn_norm, NULL,
  10653. LLM_NORM_RMS, cb, il);
  10654. cb(cur, "attn_norm", il);
  10655. // self-attention
  10656. {
  10657. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10658. cb(cur, "wqkv", il);
  10659. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10660. cb(cur, "bqkv", il);
  10661. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10662. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  10663. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  10664. cb(Qcur, "Qcur", il);
  10665. cb(Kcur, "Kcur", il);
  10666. cb(Vcur, "Vcur", il);
  10667. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10668. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10669. // using mode = 2 for neox mode
  10670. Qcur = ggml_rope_ext(
  10671. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  10672. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  10673. );
  10674. cb(Qcur, "Qcur", il);
  10675. Kcur = ggml_rope_ext(
  10676. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  10677. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  10678. );
  10679. cb(Kcur, "Kcur", il);
  10680. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10681. model.layers[il].wo, NULL,
  10682. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10683. }
  10684. if (il == n_layer - 1) {
  10685. // skip computing output for unused tokens
  10686. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10687. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10688. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10689. }
  10690. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10691. cb(ffn_inp, "ffn_inp", il);
  10692. // feed-forward forward
  10693. {
  10694. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10695. model.layers[il].ffn_norm, NULL,
  10696. LLM_NORM_RMS, cb, il);
  10697. cb(cur, "ffn_norm", il);
  10698. cur = llm_build_ffn(ctx0, lctx, cur,
  10699. model.layers[il].ffn_up, NULL, NULL,
  10700. model.layers[il].ffn_gate, NULL, NULL,
  10701. model.layers[il].ffn_down, NULL, NULL,
  10702. NULL,
  10703. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10704. cb(cur, "ffn_out", il);
  10705. }
  10706. cur = ggml_add(ctx0, cur, ffn_inp);
  10707. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10708. cb(cur, "l_out", il);
  10709. // input for next layer
  10710. inpL = cur;
  10711. }
  10712. cur = inpL;
  10713. cur = llm_build_norm(ctx0, cur, hparams,
  10714. model.output_norm, NULL,
  10715. LLM_NORM_RMS, cb, -1);
  10716. cb(cur, "result_norm", -1);
  10717. // lm_head
  10718. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10719. cb(cur, "result_output", -1);
  10720. ggml_build_forward_expand(gf, cur);
  10721. return gf;
  10722. }
  10723. struct ggml_cgraph * build_qwen2() {
  10724. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10725. const int64_t n_embd_head = hparams.n_embd_head_v;
  10726. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10727. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10728. struct ggml_tensor * cur;
  10729. struct ggml_tensor * inpL;
  10730. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10731. // inp_pos - contains the positions
  10732. struct ggml_tensor * inp_pos = build_inp_pos();
  10733. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10734. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10735. for (int il = 0; il < n_layer; ++il) {
  10736. struct ggml_tensor * inpSA = inpL;
  10737. // norm
  10738. cur = llm_build_norm(ctx0, inpL, hparams,
  10739. model.layers[il].attn_norm, NULL,
  10740. LLM_NORM_RMS, cb, il);
  10741. cb(cur, "attn_norm", il);
  10742. // self-attention
  10743. {
  10744. // compute Q and K and RoPE them
  10745. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10746. cb(Qcur, "Qcur", il);
  10747. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10748. cb(Qcur, "Qcur", il);
  10749. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10750. cb(Kcur, "Kcur", il);
  10751. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10752. cb(Kcur, "Kcur", il);
  10753. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10754. cb(Vcur, "Vcur", il);
  10755. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  10756. cb(Vcur, "Vcur", il);
  10757. Qcur = ggml_rope_ext(
  10758. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10759. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10760. ext_factor, attn_factor, beta_fast, beta_slow
  10761. );
  10762. cb(Qcur, "Qcur", il);
  10763. Kcur = ggml_rope_ext(
  10764. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10765. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10766. ext_factor, attn_factor, beta_fast, beta_slow
  10767. );
  10768. cb(Kcur, "Kcur", il);
  10769. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10770. model.layers[il].wo, model.layers[il].bo,
  10771. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10772. }
  10773. if (il == n_layer - 1) {
  10774. // skip computing output for unused tokens
  10775. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10776. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10777. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10778. }
  10779. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10780. cb(ffn_inp, "ffn_inp", il);
  10781. // feed-forward network
  10782. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10783. model.layers[il].ffn_norm, NULL,
  10784. LLM_NORM_RMS, cb, il);
  10785. cb(cur, "ffn_norm", il);
  10786. cur = llm_build_ffn(ctx0, lctx, cur,
  10787. model.layers[il].ffn_up, NULL, NULL,
  10788. model.layers[il].ffn_gate, NULL, NULL,
  10789. model.layers[il].ffn_down, NULL, NULL,
  10790. NULL,
  10791. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10792. cb(cur, "ffn_out", il);
  10793. cur = ggml_add(ctx0, cur, ffn_inp);
  10794. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10795. cb(cur, "l_out", il);
  10796. // input for next layer
  10797. inpL = cur;
  10798. }
  10799. cur = inpL;
  10800. cur = llm_build_norm(ctx0, cur, hparams,
  10801. model.output_norm, NULL,
  10802. LLM_NORM_RMS, cb, -1);
  10803. cb(cur, "result_norm", -1);
  10804. // lm_head
  10805. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10806. cb(cur, "result_output", -1);
  10807. ggml_build_forward_expand(gf, cur);
  10808. return gf;
  10809. }
  10810. struct ggml_cgraph * build_qwen2moe() {
  10811. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10812. // mutable variable, needed during the last layer of the computation to skip unused tokens
  10813. int32_t n_tokens = this->n_tokens;
  10814. const int64_t n_embd_head = hparams.n_embd_head_v;
  10815. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10816. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10817. struct ggml_tensor * cur;
  10818. struct ggml_tensor * inpL;
  10819. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10820. // inp_pos - contains the positions
  10821. struct ggml_tensor * inp_pos = build_inp_pos();
  10822. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10823. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10824. for (int il = 0; il < n_layer; ++il) {
  10825. struct ggml_tensor * inpSA = inpL;
  10826. // norm
  10827. cur = llm_build_norm(ctx0, inpL, hparams,
  10828. model.layers[il].attn_norm, NULL,
  10829. LLM_NORM_RMS, cb, il);
  10830. cb(cur, "attn_norm", il);
  10831. // self_attention
  10832. {
  10833. // compute Q and K and RoPE them
  10834. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10835. cb(Qcur, "Qcur", il);
  10836. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10837. cb(Qcur, "Qcur", il);
  10838. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10839. cb(Kcur, "Kcur", il);
  10840. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10841. cb(Kcur, "Kcur", il);
  10842. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10843. cb(Vcur, "Vcur", il);
  10844. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  10845. cb(Vcur, "Vcur", il);
  10846. Qcur = ggml_rope_ext(
  10847. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10848. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10849. ext_factor, attn_factor, beta_fast, beta_slow
  10850. );
  10851. cb(Qcur, "Qcur", il);
  10852. Kcur = ggml_rope_ext(
  10853. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10854. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10855. ext_factor, attn_factor, beta_fast, beta_slow
  10856. );
  10857. cb(Kcur, "Kcur", il);
  10858. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10859. model.layers[il].wo, model.layers[il].bo,
  10860. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10861. }
  10862. if (il == n_layer - 1) {
  10863. // skip computing output for unused tokens
  10864. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10865. n_tokens = n_outputs;
  10866. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10867. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10868. }
  10869. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10870. cb(ffn_inp, "ffn_inp", il);
  10871. // MoE branch
  10872. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10873. model.layers[il].ffn_norm, NULL,
  10874. LLM_NORM_RMS, cb, il);
  10875. cb(cur, "ffn_norm", il);
  10876. ggml_tensor * moe_out =
  10877. llm_build_moe_ffn(ctx0, lctx, cur,
  10878. model.layers[il].ffn_gate_inp,
  10879. model.layers[il].ffn_up_exps,
  10880. model.layers[il].ffn_gate_exps,
  10881. model.layers[il].ffn_down_exps,
  10882. n_expert, n_expert_used,
  10883. LLM_FFN_SILU, false,
  10884. false, 0.0,
  10885. cb, il);
  10886. cb(cur, "ffn_moe_out", il);
  10887. // FFN shared expert
  10888. {
  10889. ggml_tensor * cur_gate_inp = llm_build_lora_mm(lctx, ctx0, model.layers[il].ffn_gate_inp_shexp, cur);
  10890. cb(cur_gate_inp, "ffn_shexp_gate_inp", il);
  10891. // sigmoid
  10892. ggml_tensor * cur_gate = ggml_div(ctx0, ggml_silu(ctx0, cur_gate_inp), cur_gate_inp);
  10893. cb(cur_gate, "ffn_shexp_gate", il);
  10894. ggml_tensor * cur_ffn = llm_build_ffn(ctx0, lctx, cur,
  10895. model.layers[il].ffn_up_shexp, NULL, NULL,
  10896. model.layers[il].ffn_gate_shexp, NULL, NULL,
  10897. model.layers[il].ffn_down_shexp, NULL, NULL,
  10898. NULL,
  10899. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10900. cb(cur_ffn, "ffn_shexp", il);
  10901. ggml_tensor * ffn_shexp_out = ggml_mul(ctx0, cur_ffn, cur_gate);
  10902. cb(ffn_shexp_out, "ffn_shexp_out", il);
  10903. moe_out = ggml_add(ctx0, moe_out, ffn_shexp_out);
  10904. cb(moe_out, "ffn_out", il);
  10905. cur = moe_out;
  10906. }
  10907. cur = ggml_add(ctx0, cur, ffn_inp);
  10908. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10909. cb(cur, "l_out", il);
  10910. // input for next layer
  10911. inpL = cur;
  10912. }
  10913. cur = inpL;
  10914. cur = llm_build_norm(ctx0, cur, hparams,
  10915. model.output_norm, NULL,
  10916. LLM_NORM_RMS, cb, -1);
  10917. cb(cur, "result_norm", -1);
  10918. // lm_head
  10919. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10920. cb(cur, "result_output", -1);
  10921. ggml_build_forward_expand(gf, cur);
  10922. return gf;
  10923. }
  10924. struct ggml_cgraph * build_phi2() {
  10925. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10926. const int64_t n_embd_head = hparams.n_embd_head_v;
  10927. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10928. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10929. struct ggml_tensor * cur;
  10930. struct ggml_tensor * attn_norm_output;
  10931. struct ggml_tensor * ffn_output;
  10932. struct ggml_tensor * inpL;
  10933. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10934. // inp_pos - contains the positions
  10935. struct ggml_tensor * inp_pos = build_inp_pos();
  10936. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10937. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10938. for (int il = 0; il < n_layer; ++il) {
  10939. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  10940. model.layers[il].attn_norm,
  10941. model.layers[il].attn_norm_b,
  10942. LLM_NORM, cb, il);
  10943. cb(attn_norm_output, "attn_norm", il);
  10944. // self-attention
  10945. {
  10946. struct ggml_tensor * Qcur = nullptr;
  10947. struct ggml_tensor * Kcur = nullptr;
  10948. struct ggml_tensor * Vcur = nullptr;
  10949. if (model.layers[il].wqkv) {
  10950. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, attn_norm_output);
  10951. cb(cur, "wqkv", il);
  10952. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10953. cb(cur, "bqkv", il);
  10954. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10955. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  10956. 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)));
  10957. } else {
  10958. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  10959. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  10960. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  10961. }
  10962. cb(Qcur, "Qcur", il);
  10963. cb(Kcur, "Kcur", il);
  10964. cb(Vcur, "Vcur", il);
  10965. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10966. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10967. Qcur = ggml_rope_ext(
  10968. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  10969. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  10970. );
  10971. cb(Qcur, "Qcur", il);
  10972. // with phi2, we scale the Q to avoid precision issues
  10973. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  10974. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  10975. cb(Qcur, "Qcur", il);
  10976. Kcur = ggml_rope_ext(
  10977. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  10978. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  10979. );
  10980. cb(Kcur, "Kcur", il);
  10981. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10982. model.layers[il].wo, model.layers[il].bo,
  10983. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  10984. }
  10985. if (il == n_layer - 1) {
  10986. // skip computing output for unused tokens
  10987. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10988. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10989. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10990. attn_norm_output = ggml_get_rows(ctx0, attn_norm_output, inp_out_ids);
  10991. }
  10992. // FF
  10993. {
  10994. ffn_output = llm_build_ffn(ctx0, lctx, attn_norm_output,
  10995. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10996. NULL, NULL, NULL,
  10997. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10998. NULL,
  10999. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  11000. cb(ffn_output, "ffn_out", il);
  11001. }
  11002. cur = ggml_add(ctx0, cur, ffn_output);
  11003. cur = ggml_add(ctx0, cur, inpL);
  11004. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11005. cb(cur, "l_out", il);
  11006. // input for next layer
  11007. inpL = cur;
  11008. }
  11009. cur = llm_build_norm(ctx0, inpL, hparams,
  11010. model.output_norm,
  11011. model.output_norm_b,
  11012. LLM_NORM, cb, -1);
  11013. cb(cur, "result_norm", -1);
  11014. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11015. cb(cur, "result_output_no_bias", -1);
  11016. cur = ggml_add(ctx0, cur, model.output_b);
  11017. cb(cur, "result_output", -1);
  11018. ggml_build_forward_expand(gf, cur);
  11019. return gf;
  11020. }
  11021. struct ggml_cgraph * build_phi3() {
  11022. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11023. const int64_t n_embd_head = hparams.n_embd_head_v;
  11024. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11025. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11026. struct ggml_tensor * cur;
  11027. struct ggml_tensor * inpL;
  11028. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11029. // inp_pos - contains the positions
  11030. struct ggml_tensor * inp_pos = build_inp_pos();
  11031. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11032. struct ggml_tensor * KQ_mask_swa = build_inp_KQ_mask_swa();
  11033. for (int il = 0; il < n_layer; ++il) {
  11034. auto residual = inpL;
  11035. // self-attention
  11036. {
  11037. // rope freq factors for 128k context
  11038. struct ggml_tensor * rope_factors = build_rope_factors(il);
  11039. struct ggml_tensor* attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  11040. model.layers[il].attn_norm,
  11041. NULL,
  11042. LLM_NORM_RMS, cb, il);
  11043. cb(attn_norm_output, "attn_norm", il);
  11044. struct ggml_tensor * Qcur = nullptr;
  11045. struct ggml_tensor * Kcur = nullptr;
  11046. struct ggml_tensor * Vcur = nullptr;
  11047. if (model.layers[il].wqkv) {
  11048. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, attn_norm_output);
  11049. cb(cur, "wqkv", il);
  11050. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0 * sizeof(float) * (n_embd)));
  11051. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1 * sizeof(float) * (n_embd)));
  11052. 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)));
  11053. }
  11054. else {
  11055. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  11056. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  11057. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  11058. }
  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. Qcur = ggml_rope_ext(
  11065. ctx0, Qcur, inp_pos, rope_factors, n_rot, rope_type, n_ctx_orig,
  11066. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  11067. );
  11068. cb(Qcur, "Qcur", il);
  11069. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head)));
  11070. cb(Qcur, "Qcur", il);
  11071. Kcur = ggml_rope_ext(
  11072. ctx0, Kcur, inp_pos, rope_factors, n_rot, rope_type, n_ctx_orig,
  11073. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  11074. );
  11075. cb(Kcur, "Kcur", il);
  11076. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11077. model.layers[il].wo, model.layers[il].bo,
  11078. Kcur, Vcur, Qcur, KQ_mask_swa, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  11079. }
  11080. if (il == n_layer - 1) {
  11081. // skip computing output for unused tokens
  11082. struct ggml_tensor* inp_out_ids = build_inp_out_ids();
  11083. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11084. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  11085. }
  11086. cur = ggml_add(ctx0, cur, residual);
  11087. residual = cur;
  11088. cur = llm_build_norm(ctx0, cur, hparams,
  11089. model.layers[il].ffn_norm, NULL,
  11090. LLM_NORM_RMS, cb, il);
  11091. cb(cur, "ffn_norm", il);
  11092. // FF
  11093. // special-case: the up and gate tensors are merged into a single tensor
  11094. // TOOD: support into llm_build_ffn
  11095. {
  11096. cur = llm_build_ffn(ctx0, lctx, cur,
  11097. model.layers[il].ffn_up, NULL, NULL,
  11098. NULL, NULL, NULL,
  11099. model.layers[il].ffn_down, NULL, NULL,
  11100. NULL,
  11101. LLM_FFN_SWIGLU, LLM_FFN_SEQ, cb, il);
  11102. cb(cur, "ffn_out", il);
  11103. }
  11104. cur = ggml_add(ctx0, residual, cur);
  11105. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11106. cb(cur, "l_out", il);
  11107. // input for next layer
  11108. inpL = cur;
  11109. }
  11110. cur = llm_build_norm(ctx0, inpL, hparams,
  11111. model.output_norm,
  11112. NULL,
  11113. LLM_NORM_RMS, cb, -1);
  11114. cb(cur, "result_norm", -1);
  11115. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11116. cb(cur, "result_output", -1);
  11117. ggml_build_forward_expand(gf, cur);
  11118. return gf;
  11119. }
  11120. struct ggml_cgraph * build_plamo() {
  11121. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  11122. const int64_t n_embd_head = hparams.n_embd_head_v;
  11123. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11124. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11125. struct ggml_tensor * cur;
  11126. struct ggml_tensor * inpL;
  11127. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11128. // inp_pos - contains the positions
  11129. struct ggml_tensor * inp_pos = build_inp_pos();
  11130. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11131. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11132. for (int il = 0; il < n_layer; ++il) {
  11133. // norm
  11134. cur = llm_build_norm(ctx0, inpL, hparams,
  11135. model.layers[il].attn_norm, NULL,
  11136. LLM_NORM_RMS, cb, il);
  11137. cb(cur, "attn_norm", il);
  11138. struct ggml_tensor * attention_norm = cur;
  11139. // self-attention
  11140. {
  11141. // compute Q and K and RoPE them
  11142. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  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. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11147. cb(Vcur, "Vcur", il);
  11148. Qcur = ggml_rope_ext(
  11149. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos, nullptr,
  11150. n_embd_head, rope_type, n_ctx_orig, freq_base, freq_scale,
  11151. ext_factor, attn_factor, beta_fast, beta_slow);
  11152. cb(Qcur, "Qcur", il);
  11153. Kcur = ggml_rope_ext(
  11154. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos, nullptr,
  11155. n_embd_head, rope_type, n_ctx_orig, freq_base, freq_scale,
  11156. ext_factor, attn_factor, beta_fast, beta_slow);
  11157. cb(Kcur, "Kcur", il);
  11158. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11159. model.layers[il].wo, NULL,
  11160. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11161. }
  11162. struct ggml_tensor * sa_out = cur;
  11163. cur = attention_norm;
  11164. if (il == n_layer - 1) {
  11165. // skip computing output for unused tokens
  11166. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11167. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11168. sa_out = ggml_get_rows(ctx0, sa_out, inp_out_ids);
  11169. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11170. }
  11171. // feed-forward network
  11172. {
  11173. cur = llm_build_ffn(ctx0, lctx, cur,
  11174. model.layers[il].ffn_up, NULL, NULL,
  11175. model.layers[il].ffn_gate, NULL, NULL,
  11176. model.layers[il].ffn_down, NULL, NULL,
  11177. NULL,
  11178. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11179. cb(cur, "ffn_out", il);
  11180. }
  11181. cur = ggml_add(ctx0, cur, sa_out);
  11182. cur = ggml_add(ctx0, cur, inpL);
  11183. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11184. cb(cur, "l_out", il);
  11185. // input for next layer
  11186. inpL = cur;
  11187. }
  11188. cur = inpL;
  11189. cur = llm_build_norm(ctx0, cur, hparams,
  11190. model.output_norm, NULL,
  11191. LLM_NORM_RMS, cb, -1);
  11192. cb(cur, "result_norm", -1);
  11193. // lm_head
  11194. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11195. cb(cur, "result_output", -1);
  11196. ggml_build_forward_expand(gf, cur);
  11197. return gf;
  11198. }
  11199. struct ggml_cgraph * build_gpt2() {
  11200. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11201. const int64_t n_embd_head = hparams.n_embd_head_v;
  11202. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11203. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11204. struct ggml_tensor * cur;
  11205. struct ggml_tensor * pos;
  11206. struct ggml_tensor * inpL;
  11207. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11208. // inp_pos - contains the positions
  11209. struct ggml_tensor * inp_pos = build_inp_pos();
  11210. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11211. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11212. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  11213. cb(pos, "pos_embd", -1);
  11214. inpL = ggml_add(ctx0, inpL, pos);
  11215. cb(inpL, "inpL", -1);
  11216. for (int il = 0; il < n_layer; ++il) {
  11217. cur = llm_build_norm(ctx0, inpL, hparams,
  11218. model.layers[il].attn_norm,
  11219. model.layers[il].attn_norm_b,
  11220. LLM_NORM, cb, il);
  11221. cb(cur, "attn_norm", il);
  11222. // self-attention
  11223. {
  11224. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  11225. cb(cur, "wqkv", il);
  11226. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  11227. cb(cur, "bqkv", il);
  11228. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  11229. 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)));
  11230. 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)));
  11231. cb(Qcur, "Qcur", il);
  11232. cb(Kcur, "Kcur", il);
  11233. cb(Vcur, "Vcur", il);
  11234. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11235. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11236. model.layers[il].wo, model.layers[il].bo,
  11237. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11238. }
  11239. if (il == n_layer - 1) {
  11240. // skip computing output for unused tokens
  11241. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11242. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11243. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11244. }
  11245. // add the input
  11246. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  11247. cb(ffn_inp, "ffn_inp", il);
  11248. // FF
  11249. {
  11250. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11251. model.layers[il].ffn_norm,
  11252. model.layers[il].ffn_norm_b,
  11253. LLM_NORM, cb, il);
  11254. cb(cur, "ffn_norm", il);
  11255. cur = llm_build_ffn(ctx0, lctx, cur,
  11256. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  11257. NULL, NULL, NULL,
  11258. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  11259. NULL,
  11260. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  11261. cb(cur, "ffn_out", il);
  11262. }
  11263. cur = ggml_add(ctx0, cur, ffn_inp);
  11264. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11265. cb(cur, "l_out", il);
  11266. // input for next layer
  11267. inpL = cur;
  11268. }
  11269. cur = llm_build_norm(ctx0, inpL, hparams,
  11270. model.output_norm,
  11271. model.output_norm_b,
  11272. LLM_NORM, cb, -1);
  11273. cb(cur, "result_norm", -1);
  11274. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11275. cb(cur, "result_output", -1);
  11276. ggml_build_forward_expand(gf, cur);
  11277. return gf;
  11278. }
  11279. struct ggml_cgraph * build_codeshell() {
  11280. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11281. const int64_t n_embd_head = hparams.n_embd_head_v;
  11282. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11283. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11284. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11285. struct ggml_tensor * cur;
  11286. struct ggml_tensor * inpL;
  11287. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11288. // inp_pos - contains the positions
  11289. struct ggml_tensor * inp_pos = build_inp_pos();
  11290. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11291. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11292. for (int il = 0; il < n_layer; ++il) {
  11293. cur = llm_build_norm(ctx0, inpL, hparams,
  11294. model.layers[il].attn_norm,
  11295. model.layers[il].attn_norm_b,
  11296. LLM_NORM, cb, il);
  11297. cb(cur, "attn_norm", il);
  11298. // self-attention
  11299. {
  11300. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  11301. cb(cur, "wqkv", il);
  11302. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  11303. cb(cur, "bqkv", il);
  11304. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  11305. 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)));
  11306. 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)));
  11307. cb(tmpq, "tmpq", il);
  11308. cb(tmpk, "tmpk", il);
  11309. cb(Vcur, "Vcur", il);
  11310. struct ggml_tensor * Qcur = ggml_rope_ext(
  11311. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11312. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11313. ext_factor, attn_factor, beta_fast, beta_slow
  11314. );
  11315. cb(Qcur, "Qcur", il);
  11316. struct ggml_tensor * Kcur = ggml_rope_ext(
  11317. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11318. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11319. ext_factor, attn_factor, beta_fast, beta_slow
  11320. );
  11321. cb(Kcur, "Kcur", il);
  11322. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11323. model.layers[il].wo, model.layers[il].bo,
  11324. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11325. }
  11326. if (il == n_layer - 1) {
  11327. // skip computing output for unused tokens
  11328. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11329. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11330. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11331. }
  11332. // add the input
  11333. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  11334. cb(ffn_inp, "ffn_inp", il);
  11335. // FF
  11336. {
  11337. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11338. model.layers[il].ffn_norm,
  11339. model.layers[il].ffn_norm_b,
  11340. LLM_NORM, cb, il);
  11341. cb(cur, "ffn_norm", il);
  11342. cur = llm_build_ffn(ctx0, lctx, cur,
  11343. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  11344. NULL, NULL, NULL,
  11345. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  11346. NULL,
  11347. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  11348. cb(cur, "ffn_out", il);
  11349. }
  11350. cur = ggml_add(ctx0, cur, ffn_inp);
  11351. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11352. cb(cur, "l_out", il);
  11353. // input for next layer
  11354. inpL = cur;
  11355. }
  11356. cur = llm_build_norm(ctx0, inpL, hparams,
  11357. model.output_norm,
  11358. model.output_norm_b,
  11359. LLM_NORM, cb, -1);
  11360. cb(cur, "result_norm", -1);
  11361. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11362. cb(cur, "result_output", -1);
  11363. ggml_build_forward_expand(gf, cur);
  11364. return gf;
  11365. }
  11366. struct ggml_cgraph * build_orion() {
  11367. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11368. const int64_t n_embd_head = hparams.n_embd_head_v;
  11369. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11370. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11371. struct ggml_tensor * cur;
  11372. struct ggml_tensor * inpL;
  11373. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11374. // inp_pos - contains the positions
  11375. struct ggml_tensor * inp_pos = build_inp_pos();
  11376. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11377. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11378. for (int il = 0; il < n_layer; ++il) {
  11379. struct ggml_tensor * inpSA = inpL;
  11380. // norm
  11381. cur = llm_build_norm(ctx0, inpL, hparams,
  11382. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  11383. LLM_NORM, cb, il);
  11384. cb(cur, "attn_norm", il);
  11385. // self-attention
  11386. {
  11387. // compute Q and K and RoPE them
  11388. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11389. cb(Qcur, "Qcur", il);
  11390. // if (model.layers[il].bq) {
  11391. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  11392. // cb(Qcur, "Qcur", il);
  11393. // }
  11394. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11395. cb(Kcur, "Kcur", il);
  11396. // if (model.layers[il].bk) {
  11397. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  11398. // cb(Kcur, "Kcur", il);
  11399. // }
  11400. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11401. cb(Vcur, "Vcur", il);
  11402. // if (model.layers[il].bv) {
  11403. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11404. // cb(Vcur, "Vcur", il);
  11405. // }
  11406. Qcur = ggml_rope_ext(
  11407. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11408. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11409. ext_factor, attn_factor, beta_fast, beta_slow
  11410. );
  11411. cb(Qcur, "Qcur", il);
  11412. Kcur = ggml_rope_ext(
  11413. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11414. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11415. ext_factor, attn_factor, beta_fast, beta_slow
  11416. );
  11417. cb(Kcur, "Kcur", il);
  11418. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11419. model.layers[il].wo, NULL,
  11420. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11421. }
  11422. if (il == n_layer - 1) {
  11423. // skip computing output for unused tokens
  11424. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11425. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11426. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11427. }
  11428. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11429. cb(ffn_inp, "ffn_inp", il);
  11430. // feed-forward network
  11431. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11432. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  11433. LLM_NORM, cb, il);
  11434. cb(cur, "ffn_norm", il);
  11435. cur = llm_build_ffn(ctx0, lctx, cur,
  11436. model.layers[il].ffn_up, NULL, NULL,
  11437. model.layers[il].ffn_gate, NULL, NULL,
  11438. model.layers[il].ffn_down, NULL, NULL,
  11439. NULL,
  11440. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11441. cb(cur, "ffn_out", il);
  11442. cur = ggml_add(ctx0, cur, ffn_inp);
  11443. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11444. cb(cur, "l_out", il);
  11445. // input for next layer
  11446. inpL = cur;
  11447. }
  11448. cur = inpL;
  11449. cur = llm_build_norm(ctx0, cur, hparams,
  11450. model.output_norm, model.output_norm_b,
  11451. LLM_NORM, cb, -1);
  11452. cb(cur, "result_norm", -1);
  11453. // lm_head
  11454. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11455. cb(cur, "result_output", -1);
  11456. ggml_build_forward_expand(gf, cur);
  11457. return gf;
  11458. }
  11459. struct ggml_cgraph * build_internlm2() {
  11460. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11461. const int64_t n_embd_head = hparams.n_embd_head_v;
  11462. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11463. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11464. struct ggml_tensor * cur;
  11465. struct ggml_tensor * inpL;
  11466. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11467. // inp_pos - contains the positions
  11468. struct ggml_tensor * inp_pos = build_inp_pos();
  11469. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11470. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11471. for (int il = 0; il < n_layer; ++il) {
  11472. struct ggml_tensor * inpSA = inpL;
  11473. // norm
  11474. cur = llm_build_norm(ctx0, inpL, hparams,
  11475. model.layers[il].attn_norm, NULL,
  11476. LLM_NORM_RMS, cb, il);
  11477. cb(cur, "attn_norm", il);
  11478. // self-attention
  11479. {
  11480. // compute Q and K and RoPE them
  11481. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11482. cb(Qcur, "Qcur", il);
  11483. if (model.layers[il].bq) {
  11484. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  11485. cb(Qcur, "Qcur", il);
  11486. }
  11487. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11488. cb(Kcur, "Kcur", il);
  11489. if (model.layers[il].bk) {
  11490. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  11491. cb(Kcur, "Kcur", il);
  11492. }
  11493. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11494. cb(Vcur, "Vcur", il);
  11495. if (model.layers[il].bv) {
  11496. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11497. cb(Vcur, "Vcur", il);
  11498. }
  11499. Qcur = ggml_rope_ext(
  11500. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11501. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11502. ext_factor, attn_factor, beta_fast, beta_slow
  11503. );
  11504. cb(Qcur, "Qcur", il);
  11505. Kcur = ggml_rope_ext(
  11506. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11507. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11508. ext_factor, attn_factor, beta_fast, beta_slow
  11509. );
  11510. cb(Kcur, "Kcur", il);
  11511. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11512. model.layers[il].wo, model.layers[il].bo,
  11513. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11514. }
  11515. if (il == n_layer - 1) {
  11516. // skip computing output for unused tokens
  11517. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11518. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11519. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11520. }
  11521. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11522. cb(ffn_inp, "ffn_inp", il);
  11523. // feed-forward network
  11524. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11525. model.layers[il].ffn_norm, NULL,
  11526. LLM_NORM_RMS, cb, il);
  11527. cb(cur, "ffn_norm", il);
  11528. cur = llm_build_ffn(ctx0, lctx, cur,
  11529. model.layers[il].ffn_up, NULL, NULL,
  11530. model.layers[il].ffn_gate, NULL, NULL,
  11531. model.layers[il].ffn_down, NULL, NULL,
  11532. NULL,
  11533. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11534. cb(cur, "ffn_out", il);
  11535. cur = ggml_add(ctx0, cur, ffn_inp);
  11536. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11537. cb(cur, "l_out", il);
  11538. // input for next layer
  11539. inpL = cur;
  11540. }
  11541. cur = inpL;
  11542. cur = llm_build_norm(ctx0, cur, hparams,
  11543. model.output_norm, NULL,
  11544. LLM_NORM_RMS, cb, -1);
  11545. cb(cur, "result_norm", -1);
  11546. // lm_head
  11547. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11548. cb(cur, "result_output", -1);
  11549. ggml_build_forward_expand(gf, cur);
  11550. return gf;
  11551. }
  11552. // ref: https://arxiv.org/abs/2203.03466
  11553. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  11554. // based on the original build_llama() function
  11555. struct ggml_cgraph * build_minicpm() {
  11556. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11557. const int64_t n_embd_head = hparams.n_embd_head_v;
  11558. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11559. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11560. const int64_t n_embd = hparams.n_embd;
  11561. //TODO: if the model varies, these parameters need to be read from the model
  11562. const int64_t n_embd_base = 256;
  11563. const float scale_embd = 12.0f;
  11564. const float scale_depth = 1.4f;
  11565. struct ggml_tensor * cur;
  11566. struct ggml_tensor * inpL;
  11567. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11568. // scale the input embeddings
  11569. inpL = ggml_scale(ctx0, inpL, scale_embd);
  11570. cb(inpL, "inp_scaled", -1);
  11571. // inp_pos - contains the positions
  11572. struct ggml_tensor * inp_pos = build_inp_pos();
  11573. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11574. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11575. for (int il = 0; il < n_layer; ++il) {
  11576. struct ggml_tensor * inpSA = inpL;
  11577. // norm
  11578. cur = llm_build_norm(ctx0, inpL, hparams,
  11579. model.layers[il].attn_norm, NULL,
  11580. LLM_NORM_RMS, cb, il);
  11581. cb(cur, "attn_norm", il);
  11582. // self-attention
  11583. {
  11584. // compute Q and K and RoPE them
  11585. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11586. cb(Qcur, "Qcur", il);
  11587. if (model.layers[il].bq) {
  11588. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  11589. cb(Qcur, "Qcur", il);
  11590. }
  11591. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11592. cb(Kcur, "Kcur", il);
  11593. if (model.layers[il].bk) {
  11594. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  11595. cb(Kcur, "Kcur", il);
  11596. }
  11597. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11598. cb(Vcur, "Vcur", il);
  11599. if (model.layers[il].bv) {
  11600. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11601. cb(Vcur, "Vcur", il);
  11602. }
  11603. Qcur = ggml_rope_ext(
  11604. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11605. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11606. ext_factor, attn_factor, beta_fast, beta_slow
  11607. );
  11608. cb(Qcur, "Qcur", il);
  11609. Kcur = ggml_rope_ext(
  11610. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11611. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11612. ext_factor, attn_factor, beta_fast, beta_slow
  11613. );
  11614. cb(Kcur, "Kcur", il);
  11615. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11616. model.layers[il].wo, model.layers[il].bo,
  11617. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11618. }
  11619. if (il == n_layer - 1) {
  11620. // skip computing output for unused tokens
  11621. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11622. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11623. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11624. }
  11625. // scale_res - scale the hidden states for residual connection
  11626. const float scale_res = scale_depth/sqrtf(float(n_layer));
  11627. cur = ggml_scale(ctx0, cur, scale_res);
  11628. cb(cur, "hidden_scaled", -1);
  11629. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11630. cb(ffn_inp, "ffn_inp", il);
  11631. // feed-forward network
  11632. {
  11633. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11634. model.layers[il].ffn_norm, NULL,
  11635. LLM_NORM_RMS, cb, il);
  11636. cb(cur, "ffn_norm", il);
  11637. cur = llm_build_ffn(ctx0, lctx, cur,
  11638. model.layers[il].ffn_up, NULL, NULL,
  11639. model.layers[il].ffn_gate, NULL, NULL,
  11640. model.layers[il].ffn_down, NULL, NULL,
  11641. NULL,
  11642. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11643. cb(cur, "ffn_out", il);
  11644. }
  11645. // scale the hidden states for residual connection
  11646. cur = ggml_scale(ctx0, cur, scale_res);
  11647. cb(cur, "hidden_scaled_ffn", -1);
  11648. cur = ggml_add(ctx0, cur, ffn_inp);
  11649. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11650. cb(cur, "l_out", il);
  11651. // input for next layer
  11652. inpL = cur;
  11653. }
  11654. cur = inpL;
  11655. cur = llm_build_norm(ctx0, cur, hparams,
  11656. model.output_norm, NULL,
  11657. LLM_NORM_RMS, cb, -1);
  11658. cb(cur, "result_norm", -1);
  11659. // lm_head scaling
  11660. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  11661. cur = ggml_scale(ctx0, cur, scale_lmhead);
  11662. cb(cur, "lmhead_scaling", -1);
  11663. // lm_head
  11664. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11665. cb(cur, "result_output", -1);
  11666. ggml_build_forward_expand(gf, cur);
  11667. return gf;
  11668. }
  11669. struct ggml_cgraph * build_minicpm3() {
  11670. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11671. //TODO: if the model varies, these parameters need to be read from the model
  11672. const int64_t n_embd_base = 256;
  11673. const float scale_embd = 12.0f;
  11674. const float scale_depth = 1.4f;
  11675. const float kq_scale = 1.0f / sqrtf(float(hparams.n_embd_head_k));
  11676. const uint32_t n_embd_head_qk_rope = hparams.n_rot;
  11677. const uint32_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  11678. const uint32_t kv_lora_rank = hparams.n_lora_kv;
  11679. struct ggml_tensor * cur;
  11680. struct ggml_tensor * inpL;
  11681. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11682. // scale the input embeddings
  11683. inpL = ggml_scale(ctx0, inpL, scale_embd);
  11684. cb(inpL, "inp_scaled", -1);
  11685. // inp_pos - contains the positions
  11686. struct ggml_tensor * inp_pos = build_inp_pos();
  11687. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11688. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11689. for (int il = 0; il < n_layer; ++il) {
  11690. struct ggml_tensor * inpSA = inpL;
  11691. struct ggml_tensor * rope_factors = build_rope_factors(il);
  11692. // norm
  11693. cur = llm_build_norm(ctx0, inpL, hparams,
  11694. model.layers[il].attn_norm, NULL,
  11695. LLM_NORM_RMS, cb, il);
  11696. cb(cur, "attn_norm", il);
  11697. // self_attention
  11698. {
  11699. struct ggml_tensor * q = NULL;
  11700. // {n_embd, q_lora_rank} * {n_embd, n_tokens} -> {q_lora_rank, n_tokens}
  11701. q = ggml_mul_mat(ctx0, model.layers[il].wq_a, cur);
  11702. cb(q, "q", il);
  11703. q = llm_build_norm(ctx0, q, hparams,
  11704. model.layers[il].attn_q_a_norm, NULL,
  11705. LLM_NORM_RMS, cb, il);
  11706. cb(q, "q", il);
  11707. // {q_lora_rank, n_head * hparams.n_embd_head_k} * {q_lora_rank, n_tokens} -> {n_head * hparams.n_embd_head_k, n_tokens}
  11708. q = ggml_mul_mat(ctx0, model.layers[il].wq_b, q);
  11709. cb(q, "q", il);
  11710. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  11711. struct ggml_tensor * q_nope = ggml_view_3d(ctx0, q, n_embd_head_qk_nope, n_head, n_tokens,
  11712. ggml_row_size(q->type, hparams.n_embd_head_k),
  11713. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  11714. 0);
  11715. cb(q_nope, "q_nope", il);
  11716. // and {n_head * n_embd_head_qk_rope, n_tokens}
  11717. struct ggml_tensor * q_pe = ggml_view_3d(ctx0, q, n_embd_head_qk_rope, n_head, n_tokens,
  11718. ggml_row_size(q->type, hparams.n_embd_head_k),
  11719. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  11720. ggml_row_size(q->type, n_embd_head_qk_nope));
  11721. cb(q_pe, "q_pe", il);
  11722. // {n_embd, kv_lora_rank + n_embd_head_qk_rope} * {n_embd, n_tokens} -> {kv_lora_rank + n_embd_head_qk_rope, n_tokens}
  11723. struct ggml_tensor * kv_pe_compresseed = ggml_mul_mat(ctx0, model.layers[il].wkv_a_mqa, cur);
  11724. cb(kv_pe_compresseed, "kv_pe_compresseed", il);
  11725. // split into {kv_lora_rank, n_tokens}
  11726. struct ggml_tensor * kv_compressed = ggml_view_2d(ctx0, kv_pe_compresseed, kv_lora_rank, n_tokens,
  11727. kv_pe_compresseed->nb[1],
  11728. 0);
  11729. cb(kv_compressed, "kv_compressed", il);
  11730. // and {n_embd_head_qk_rope, n_tokens}
  11731. struct ggml_tensor * k_pe = ggml_view_3d(ctx0, kv_pe_compresseed, n_embd_head_qk_rope, 1, n_tokens,
  11732. kv_pe_compresseed->nb[1],
  11733. kv_pe_compresseed->nb[1],
  11734. ggml_row_size(kv_pe_compresseed->type, kv_lora_rank));
  11735. cb(k_pe, "k_pe", il);
  11736. kv_compressed = ggml_cont(ctx0, kv_compressed); // TODO: the CUDA backend does not support non-contiguous norm
  11737. kv_compressed = llm_build_norm(ctx0, kv_compressed, hparams,
  11738. model.layers[il].attn_kv_a_norm, NULL,
  11739. LLM_NORM_RMS, cb, il);
  11740. cb(kv_compressed, "kv_compressed", il);
  11741. // {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}
  11742. struct ggml_tensor * kv = ggml_mul_mat(ctx0, model.layers[il].wkv_b, kv_compressed);
  11743. cb(kv, "kv", il);
  11744. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  11745. struct ggml_tensor * k_nope = ggml_view_3d(ctx0, kv, n_embd_head_qk_nope, n_head, n_tokens,
  11746. ggml_row_size(kv->type, n_embd_head_qk_nope + hparams.n_embd_head_v),
  11747. ggml_row_size(kv->type, n_head * (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  11748. 0);
  11749. cb(k_nope, "k_nope", il);
  11750. // and {n_head * n_embd_head_v, n_tokens}
  11751. struct ggml_tensor * v_states = ggml_view_3d(ctx0, kv, hparams.n_embd_head_v, n_head, n_tokens,
  11752. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  11753. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)*n_head),
  11754. ggml_row_size(kv->type, (n_embd_head_qk_nope)));
  11755. cb(v_states, "v_states", il);
  11756. v_states = ggml_cont(ctx0, v_states);
  11757. cb(v_states, "v_states", il);
  11758. v_states = ggml_view_2d(ctx0, v_states, hparams.n_embd_head_v * n_head, n_tokens,
  11759. ggml_row_size(kv->type, hparams.n_embd_head_v * n_head),
  11760. 0);
  11761. cb(v_states, "v_states", il);
  11762. q_pe = ggml_cont(ctx0, q_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  11763. q_pe = ggml_rope_ext(
  11764. ctx0, q_pe, inp_pos, rope_factors,
  11765. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11766. ext_factor, attn_factor, beta_fast, beta_slow
  11767. );
  11768. cb(q_pe, "q_pe", il);
  11769. // shared RoPE key
  11770. k_pe = ggml_cont(ctx0, k_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  11771. k_pe = ggml_rope_ext(
  11772. ctx0, k_pe, inp_pos, rope_factors,
  11773. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11774. ext_factor, attn_factor, beta_fast, beta_slow
  11775. );
  11776. cb(k_pe, "k_pe", il);
  11777. struct ggml_tensor * q_states = ggml_concat(ctx0, q_nope, q_pe, 0);
  11778. cb(q_states, "q_states", il);
  11779. struct ggml_tensor * k_states = ggml_concat(ctx0, k_nope, ggml_repeat(ctx0, k_pe, q_pe), 0);
  11780. cb(k_states, "k_states", il);
  11781. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11782. model.layers[il].wo, NULL,
  11783. k_states, v_states, q_states, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  11784. }
  11785. if (il == n_layer - 1) {
  11786. // skip computing output for unused tokens
  11787. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11788. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11789. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11790. }
  11791. // scale_res - scale the hidden states for residual connection
  11792. const float scale_res = scale_depth/sqrtf(float(n_layer));
  11793. cur = ggml_scale(ctx0, cur, scale_res);
  11794. cb(cur, "hidden_scaled", il);
  11795. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11796. cb(ffn_inp, "ffn_inp", il);
  11797. // feed-forward network
  11798. {
  11799. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11800. model.layers[il].ffn_norm, NULL,
  11801. LLM_NORM_RMS, cb, il);
  11802. cb(cur, "ffn_norm", il);
  11803. cur = llm_build_ffn(ctx0, lctx, cur,
  11804. model.layers[il].ffn_up, NULL, NULL,
  11805. model.layers[il].ffn_gate, NULL, NULL,
  11806. model.layers[il].ffn_down, NULL, NULL,
  11807. NULL,
  11808. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11809. cb(cur, "ffn_out", il);
  11810. }
  11811. // scale the hidden states for residual connection
  11812. cur = ggml_scale(ctx0, cur, scale_res);
  11813. cb(cur, "hidden_scaled_ffn", il);
  11814. cur = ggml_add(ctx0, cur, ffn_inp);
  11815. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11816. cb(cur, "l_out", il);
  11817. // input for next layer
  11818. inpL = cur;
  11819. }
  11820. cur = inpL;
  11821. cur = llm_build_norm(ctx0, cur, hparams,
  11822. model.output_norm, NULL,
  11823. LLM_NORM_RMS, cb, -1);
  11824. cb(cur, "result_norm", -1);
  11825. // lm_head scaling
  11826. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  11827. cur = ggml_scale(ctx0, cur, scale_lmhead);
  11828. cb(cur, "lmhead_scaling", -1);
  11829. // lm_head
  11830. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11831. cb(cur, "result_output", -1);
  11832. ggml_build_forward_expand(gf, cur);
  11833. return gf;
  11834. }
  11835. struct ggml_cgraph * build_gemma() {
  11836. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11837. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  11838. struct ggml_tensor * cur;
  11839. struct ggml_tensor * inpL;
  11840. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11841. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  11842. cb(inpL, "inp_scaled", -1);
  11843. // inp_pos - contains the positions
  11844. struct ggml_tensor * inp_pos = build_inp_pos();
  11845. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11846. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11847. for (int il = 0; il < n_layer; ++il) {
  11848. // norm
  11849. cur = llm_build_norm(ctx0, inpL, hparams,
  11850. model.layers[il].attn_norm, NULL,
  11851. LLM_NORM_RMS, cb, il);
  11852. cb(cur, "attn_norm", il);
  11853. // self-attention
  11854. {
  11855. // compute Q and K and RoPE them
  11856. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11857. cb(Qcur, "Qcur", il);
  11858. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11859. cb(Kcur, "Kcur", il);
  11860. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11861. cb(Vcur, "Vcur", il);
  11862. Qcur = ggml_rope_ext(
  11863. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos, nullptr,
  11864. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11865. ext_factor, attn_factor, beta_fast, beta_slow);
  11866. cb(Qcur, "Qcur", il);
  11867. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  11868. cb(Qcur, "Qcur_scaled", il);
  11869. Kcur = ggml_rope_ext(
  11870. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos, nullptr,
  11871. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11872. ext_factor, attn_factor, beta_fast, beta_slow);
  11873. cb(Kcur, "Kcur", il);
  11874. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11875. model.layers[il].wo, NULL,
  11876. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  11877. }
  11878. if (il == n_layer - 1) {
  11879. // skip computing output for unused tokens
  11880. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11881. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11882. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11883. }
  11884. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  11885. cb(sa_out, "sa_out", il);
  11886. cur = llm_build_norm(ctx0, sa_out, hparams,
  11887. model.layers[il].ffn_norm, NULL,
  11888. LLM_NORM_RMS, cb, il);
  11889. cb(cur, "ffn_norm", il);
  11890. // feed-forward network
  11891. {
  11892. cur = llm_build_ffn(ctx0, lctx, cur,
  11893. model.layers[il].ffn_up, NULL, NULL,
  11894. model.layers[il].ffn_gate, NULL, NULL,
  11895. model.layers[il].ffn_down, NULL, NULL,
  11896. NULL,
  11897. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  11898. cb(cur, "ffn_out", il);
  11899. }
  11900. cur = ggml_add(ctx0, cur, sa_out);
  11901. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11902. cb(cur, "l_out", il);
  11903. // input for next layer
  11904. inpL = cur;
  11905. }
  11906. cur = inpL;
  11907. cur = llm_build_norm(ctx0, cur, hparams,
  11908. model.output_norm, NULL,
  11909. LLM_NORM_RMS, cb, -1);
  11910. cb(cur, "result_norm", -1);
  11911. // lm_head
  11912. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11913. cb(cur, "result_output", -1);
  11914. ggml_build_forward_expand(gf, cur);
  11915. return gf;
  11916. }
  11917. struct ggml_cgraph * build_gemma2() {
  11918. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11919. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  11920. struct ggml_tensor * cur;
  11921. struct ggml_tensor * inpL;
  11922. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11923. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  11924. cb(inpL, "inp_scaled", -1);
  11925. // inp_pos - contains the positions
  11926. struct ggml_tensor * inp_pos = build_inp_pos();
  11927. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11928. // gemma 2 requires different mask for layers using sliding window (SWA)
  11929. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(true);
  11930. struct ggml_tensor * KQ_mask_swa = build_inp_KQ_mask_swa(true);
  11931. for (int il = 0; il < n_layer; ++il) {
  11932. // (il % 2) layers use SWA
  11933. struct ggml_tensor * KQ_mask_l = (il % 2 == 0) ? KQ_mask_swa : KQ_mask;
  11934. // norm
  11935. cur = llm_build_norm(ctx0, inpL, hparams,
  11936. model.layers[il].attn_norm, NULL,
  11937. LLM_NORM_RMS, cb, il);
  11938. cb(cur, "attn_norm", il);
  11939. // self-attention
  11940. {
  11941. // compute Q and K and RoPE them
  11942. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11943. cb(Qcur, "Qcur", il);
  11944. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11945. cb(Kcur, "Kcur", il);
  11946. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11947. cb(Vcur, "Vcur", il);
  11948. Qcur = ggml_rope_ext(
  11949. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos, nullptr,
  11950. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11951. ext_factor, attn_factor, beta_fast, beta_slow);
  11952. cb(Qcur, "Qcur", il);
  11953. // ref: https://github.com/google/gemma_pytorch/commit/03e657582d17cb5a8617ebf333c1c16f3694670e
  11954. switch (model.type) {
  11955. case e_model::MODEL_2B:
  11956. case e_model::MODEL_9B: Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k))); break;
  11957. case e_model::MODEL_27B: Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd / n_head))); break;
  11958. default: GGML_ABORT("fatal error");
  11959. };
  11960. cb(Qcur, "Qcur_scaled", il);
  11961. Kcur = ggml_rope_ext(
  11962. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos, nullptr,
  11963. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11964. ext_factor, attn_factor, beta_fast, beta_slow);
  11965. cb(Kcur, "Kcur", il);
  11966. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11967. model.layers[il].wo, NULL,
  11968. Kcur, Vcur, Qcur, KQ_mask_l, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  11969. }
  11970. cur = llm_build_norm(ctx0, cur, hparams,
  11971. model.layers[il].attn_post_norm, NULL,
  11972. LLM_NORM_RMS, cb, il);
  11973. cb(cur, "attn_post_norm", il);
  11974. if (il == n_layer - 1) {
  11975. // skip computing output for unused tokens
  11976. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11977. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11978. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11979. }
  11980. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  11981. cb(sa_out, "sa_out", il);
  11982. cur = llm_build_norm(ctx0, sa_out, hparams,
  11983. model.layers[il].ffn_norm, NULL,
  11984. LLM_NORM_RMS, cb, il);
  11985. cb(cur, "ffn_norm", il);
  11986. // feed-forward network
  11987. {
  11988. cur = llm_build_ffn(ctx0, lctx, cur,
  11989. model.layers[il].ffn_up, NULL, NULL,
  11990. model.layers[il].ffn_gate, NULL, NULL,
  11991. model.layers[il].ffn_down, NULL, NULL,
  11992. NULL,
  11993. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  11994. cb(cur, "ffn_out", il);
  11995. }
  11996. cur = llm_build_norm(ctx0, cur, hparams,
  11997. model.layers[il].ffn_post_norm, NULL,
  11998. LLM_NORM_RMS, cb, -1);
  11999. cb(cur, "ffn_post_norm", -1);
  12000. cur = ggml_add(ctx0, cur, sa_out);
  12001. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12002. cb(cur, "l_out", il);
  12003. // input for next layer
  12004. inpL = cur;
  12005. }
  12006. cur = inpL;
  12007. cur = llm_build_norm(ctx0, cur, hparams,
  12008. model.output_norm, NULL,
  12009. LLM_NORM_RMS, cb, -1);
  12010. cb(cur, "result_norm", -1);
  12011. // lm_head
  12012. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12013. // final logit soft-capping
  12014. cur = ggml_scale(ctx0, cur, 1.0f / hparams.f_final_logit_softcapping);
  12015. cur = ggml_tanh(ctx0, cur);
  12016. cur = ggml_scale(ctx0, cur, hparams.f_final_logit_softcapping);
  12017. cb(cur, "result_output", -1);
  12018. ggml_build_forward_expand(gf, cur);
  12019. return gf;
  12020. }
  12021. struct ggml_cgraph * build_starcoder2() {
  12022. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12023. const int64_t n_embd_head = hparams.n_embd_head_v;
  12024. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12025. GGML_ASSERT(n_embd_head == hparams.n_rot);
  12026. struct ggml_tensor * cur;
  12027. struct ggml_tensor * inpL;
  12028. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12029. // inp_pos - contains the positions
  12030. struct ggml_tensor * inp_pos = build_inp_pos();
  12031. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12032. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12033. for (int il = 0; il < n_layer; ++il) {
  12034. struct ggml_tensor * inpSA = inpL;
  12035. // norm
  12036. cur = llm_build_norm(ctx0, inpL, hparams,
  12037. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  12038. LLM_NORM, cb, il);
  12039. cb(cur, "attn_norm", il);
  12040. // self-attention
  12041. {
  12042. // compute Q and K and RoPE them
  12043. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12044. cb(Qcur, "Qcur", il);
  12045. if (model.layers[il].bq) {
  12046. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  12047. cb(Qcur, "Qcur", il);
  12048. }
  12049. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12050. cb(Kcur, "Kcur", il);
  12051. if (model.layers[il].bk) {
  12052. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  12053. cb(Kcur, "Kcur", il);
  12054. }
  12055. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12056. cb(Vcur, "Vcur", il);
  12057. if (model.layers[il].bv) {
  12058. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  12059. cb(Vcur, "Vcur", il);
  12060. }
  12061. Qcur = ggml_rope_ext(
  12062. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  12063. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12064. ext_factor, attn_factor, beta_fast, beta_slow
  12065. );
  12066. cb(Qcur, "Qcur", il);
  12067. Kcur = ggml_rope_ext(
  12068. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  12069. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12070. ext_factor, attn_factor, beta_fast, beta_slow
  12071. );
  12072. cb(Kcur, "Kcur", il);
  12073. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12074. model.layers[il].wo, model.layers[il].bo,
  12075. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12076. }
  12077. if (il == n_layer - 1) {
  12078. // skip computing output for unused tokens
  12079. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12080. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12081. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12082. }
  12083. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12084. cb(ffn_inp, "ffn_inp", il);
  12085. // feed-forward network
  12086. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12087. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  12088. LLM_NORM, cb, il);
  12089. cb(cur, "ffn_norm", il);
  12090. cur = llm_build_ffn(ctx0, lctx, cur,
  12091. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  12092. NULL, NULL, NULL,
  12093. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  12094. NULL,
  12095. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  12096. cb(cur, "ffn_out", il);
  12097. cur = ggml_add(ctx0, cur, ffn_inp);
  12098. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12099. cb(cur, "l_out", il);
  12100. // input for next layer
  12101. inpL = cur;
  12102. }
  12103. cur = inpL;
  12104. cur = llm_build_norm(ctx0, cur, hparams,
  12105. model.output_norm, model.output_norm_b,
  12106. LLM_NORM, cb, -1);
  12107. cb(cur, "result_norm", -1);
  12108. // lm_head
  12109. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12110. cb(cur, "result_output", -1);
  12111. ggml_build_forward_expand(gf, cur);
  12112. return gf;
  12113. }
  12114. struct ggml_cgraph * build_mamba() {
  12115. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12116. struct ggml_tensor * cur;
  12117. struct ggml_tensor * inpL;
  12118. // {n_embd, n_tokens}
  12119. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12120. struct ggml_tensor * state_copy = build_inp_s_copy();
  12121. struct ggml_tensor * state_mask = build_inp_s_mask();
  12122. for (int il = 0; il < n_layer; ++il) {
  12123. // norm
  12124. cur = llm_build_norm(ctx0, inpL, hparams,
  12125. model.layers[il].attn_norm, NULL,
  12126. LLM_NORM_RMS, cb, il);
  12127. cb(cur, "attn_norm", il);
  12128. cur = llm_build_mamba(ctx0, lctx, batch, gf, cur,
  12129. state_copy, state_mask,
  12130. kv_head, n_kv, cb, il);
  12131. if (il == n_layer - 1) {
  12132. // skip computing output for unused tokens
  12133. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12134. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12135. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  12136. }
  12137. // residual
  12138. cur = ggml_add(ctx0, cur, inpL);
  12139. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12140. cb(cur, "l_out", il);
  12141. // input for next layer
  12142. inpL = cur;
  12143. }
  12144. // final rmsnorm
  12145. cur = llm_build_norm(ctx0, inpL, hparams,
  12146. model.output_norm, NULL,
  12147. LLM_NORM_RMS, cb, -1);
  12148. cb(cur, "result_norm", -1);
  12149. // lm_head
  12150. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12151. cb(cur, "result_output", -1);
  12152. ggml_build_forward_expand(gf, cur);
  12153. return gf;
  12154. }
  12155. struct ggml_cgraph * build_command_r() {
  12156. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12157. const int64_t n_embd_head = hparams.n_embd_head_v;
  12158. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12159. const float f_logit_scale = hparams.f_logit_scale;
  12160. struct ggml_tensor * cur;
  12161. struct ggml_tensor * inpL;
  12162. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12163. // inp_pos - contains the positions
  12164. struct ggml_tensor * inp_pos = build_inp_pos();
  12165. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12166. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12167. for (int il = 0; il < n_layer; ++il) {
  12168. // norm
  12169. cur = llm_build_norm(ctx0, inpL, hparams,
  12170. model.layers[il].attn_norm, NULL,
  12171. LLM_NORM, cb, il);
  12172. cb(cur, "attn_norm", il);
  12173. struct ggml_tensor * ffn_inp = cur;
  12174. // self-attention
  12175. {
  12176. // compute Q and K and RoPE them
  12177. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12178. cb(Qcur, "Qcur", il);
  12179. if (model.layers[il].bq) {
  12180. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  12181. cb(Qcur, "Qcur", il);
  12182. }
  12183. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12184. cb(Kcur, "Kcur", il);
  12185. if (model.layers[il].bk) {
  12186. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  12187. cb(Kcur, "Kcur", il);
  12188. }
  12189. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12190. cb(Vcur, "Vcur", il);
  12191. if (model.layers[il].bv) {
  12192. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  12193. cb(Vcur, "Vcur", il);
  12194. }
  12195. if (model.layers[il].attn_q_norm) {
  12196. Qcur = ggml_view_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens,
  12197. ggml_element_size(Qcur) * n_embd_head,
  12198. ggml_element_size(Qcur) * n_embd_head * n_head,
  12199. 0);
  12200. cb(Qcur, "Qcur", il);
  12201. Kcur = ggml_view_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens,
  12202. ggml_element_size(Kcur) * n_embd_head,
  12203. ggml_element_size(Kcur) * n_embd_head * n_head_kv,
  12204. 0);
  12205. cb(Kcur, "Kcur", il);
  12206. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  12207. model.layers[il].attn_q_norm,
  12208. NULL,
  12209. LLM_NORM, cb, il);
  12210. cb(Qcur, "Qcur", il);
  12211. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  12212. model.layers[il].attn_k_norm,
  12213. NULL,
  12214. LLM_NORM, cb, il);
  12215. cb(Kcur, "Kcur", il);
  12216. }
  12217. Qcur = ggml_rope_ext(
  12218. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  12219. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12220. ext_factor, attn_factor, beta_fast, beta_slow
  12221. );
  12222. cb(Qcur, "Qcur", il);
  12223. Kcur = ggml_rope_ext(
  12224. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  12225. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12226. ext_factor, attn_factor, beta_fast, beta_slow
  12227. );
  12228. cb(Kcur, "Kcur", il);
  12229. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12230. model.layers[il].wo, model.layers[il].bo,
  12231. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12232. }
  12233. if (il == n_layer - 1) {
  12234. // skip computing output for unused tokens
  12235. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12236. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12237. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  12238. ffn_inp = ggml_get_rows(ctx0, ffn_inp, inp_out_ids);
  12239. }
  12240. struct ggml_tensor * attn_out = cur;
  12241. // feed-forward network
  12242. {
  12243. cur = llm_build_ffn(ctx0, lctx, ffn_inp,
  12244. model.layers[il].ffn_up, NULL, NULL,
  12245. model.layers[il].ffn_gate, NULL, NULL,
  12246. model.layers[il].ffn_down, NULL, NULL,
  12247. NULL,
  12248. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12249. cb(cur, "ffn_out", il);
  12250. }
  12251. // add together residual + FFN + self-attention
  12252. cur = ggml_add(ctx0, cur, inpL);
  12253. cur = ggml_add(ctx0, cur, attn_out);
  12254. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12255. cb(cur, "l_out", il);
  12256. // input for next layer
  12257. inpL = cur;
  12258. }
  12259. cur = inpL;
  12260. cur = llm_build_norm(ctx0, cur, hparams,
  12261. model.output_norm, NULL,
  12262. LLM_NORM, cb, -1);
  12263. cb(cur, "result_norm", -1);
  12264. // lm_head
  12265. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12266. if (f_logit_scale) {
  12267. cur = ggml_scale(ctx0, cur, f_logit_scale);
  12268. }
  12269. cb(cur, "result_output", -1);
  12270. ggml_build_forward_expand(gf, cur);
  12271. return gf;
  12272. }
  12273. // ref: https://allenai.org/olmo
  12274. // based on the original build_llama() function, changes:
  12275. // * non-parametric layer norm
  12276. // * clamp qkv
  12277. // * removed bias
  12278. // * removed MoE
  12279. struct ggml_cgraph * build_olmo() {
  12280. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12281. // mutable variable, needed during the last layer of the computation to skip unused tokens
  12282. int32_t n_tokens = this->n_tokens;
  12283. const int64_t n_embd_head = hparams.n_embd_head_v;
  12284. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12285. GGML_ASSERT(n_embd_head == hparams.n_rot);
  12286. struct ggml_tensor * cur;
  12287. struct ggml_tensor * inpL;
  12288. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12289. // inp_pos - contains the positions
  12290. struct ggml_tensor * inp_pos = build_inp_pos();
  12291. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12292. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12293. for (int il = 0; il < n_layer; ++il) {
  12294. struct ggml_tensor * inpSA = inpL;
  12295. // norm
  12296. cur = llm_build_norm(ctx0, inpL, hparams,
  12297. NULL, NULL,
  12298. LLM_NORM, cb, il);
  12299. cb(cur, "attn_norm", il);
  12300. // self-attention
  12301. {
  12302. // compute Q and K and RoPE them
  12303. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12304. cb(Qcur, "Qcur", il);
  12305. if (hparams.f_clamp_kqv > 0.0f) {
  12306. Qcur = ggml_clamp(ctx0, Qcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  12307. cb(Qcur, "Qcur", il);
  12308. }
  12309. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12310. cb(Kcur, "Kcur", il);
  12311. if (hparams.f_clamp_kqv > 0.0f) {
  12312. Kcur = ggml_clamp(ctx0, Kcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  12313. cb(Kcur, "Kcur", il);
  12314. }
  12315. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12316. cb(Vcur, "Vcur", il);
  12317. if (hparams.f_clamp_kqv > 0.0f) {
  12318. Vcur = ggml_clamp(ctx0, Vcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  12319. cb(Vcur, "Vcur", il);
  12320. }
  12321. Qcur = ggml_rope_ext(
  12322. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  12323. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12324. ext_factor, attn_factor, beta_fast, beta_slow
  12325. );
  12326. cb(Qcur, "Qcur", il);
  12327. Kcur = ggml_rope_ext(
  12328. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  12329. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12330. ext_factor, attn_factor, beta_fast, beta_slow
  12331. );
  12332. cb(Kcur, "Kcur", il);
  12333. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12334. model.layers[il].wo, nullptr,
  12335. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12336. }
  12337. if (il == n_layer - 1) {
  12338. // skip computing output for unused tokens
  12339. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12340. n_tokens = n_outputs;
  12341. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12342. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12343. }
  12344. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12345. cb(ffn_inp, "ffn_inp", il);
  12346. // feed-forward network
  12347. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12348. NULL, NULL,
  12349. LLM_NORM, cb, il);
  12350. cb(cur, "ffn_norm", il);
  12351. cur = llm_build_ffn(ctx0, lctx, cur,
  12352. model.layers[il].ffn_up, NULL, NULL,
  12353. model.layers[il].ffn_gate, NULL, NULL,
  12354. model.layers[il].ffn_down, NULL, NULL,
  12355. NULL,
  12356. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12357. cb(cur, "ffn_out", il);
  12358. cur = ggml_add(ctx0, cur, ffn_inp);
  12359. cb(cur, "ffn_out", il);
  12360. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12361. cb(cur, "l_out", il);
  12362. // input for next layer
  12363. inpL = cur;
  12364. }
  12365. cur = inpL;
  12366. cur = llm_build_norm(ctx0, cur, hparams,
  12367. NULL, NULL,
  12368. LLM_NORM, cb, -1);
  12369. cb(cur, "result_norm", -1);
  12370. // lm_head
  12371. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12372. cb(cur, "result_output", -1);
  12373. ggml_build_forward_expand(gf, cur);
  12374. return gf;
  12375. }
  12376. // based on the build_qwen2moe() function, changes:
  12377. // * removed shared experts
  12378. // * removed bias
  12379. // * added q, k norm
  12380. struct ggml_cgraph * build_olmoe() {
  12381. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12382. // mutable variable, needed during the last layer of the computation to skip unused tokens
  12383. int32_t n_tokens = this->n_tokens;
  12384. const int64_t n_embd_head = hparams.n_embd_head_v;
  12385. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12386. GGML_ASSERT(n_embd_head == hparams.n_rot);
  12387. struct ggml_tensor * cur;
  12388. struct ggml_tensor * inpL;
  12389. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12390. // inp_pos - contains the positions
  12391. struct ggml_tensor * inp_pos = build_inp_pos();
  12392. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12393. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12394. for (int il = 0; il < n_layer; ++il) {
  12395. struct ggml_tensor * inpSA = inpL;
  12396. // norm
  12397. cur = llm_build_norm(ctx0, inpL, hparams,
  12398. model.layers[il].attn_norm, NULL,
  12399. LLM_NORM_RMS, cb, il);
  12400. cb(cur, "attn_norm", il);
  12401. // self_attention
  12402. {
  12403. // compute Q and K and RoPE them
  12404. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12405. cb(Qcur, "Qcur", il);
  12406. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12407. cb(Kcur, "Kcur", il);
  12408. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12409. cb(Vcur, "Vcur", il);
  12410. Qcur = llm_build_norm(ctx0, Qcur, hparams, model.layers[il].attn_q_norm, NULL,
  12411. LLM_NORM_RMS, cb, il);
  12412. cb(Qcur, "Qcur_normed", il);
  12413. Kcur = llm_build_norm(ctx0, Kcur, hparams, model.layers[il].attn_k_norm, NULL,
  12414. LLM_NORM_RMS, cb, il);
  12415. cb(Kcur, "Kcur_normed", il);
  12416. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  12417. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  12418. Qcur = ggml_rope_ext(
  12419. ctx0, Qcur, inp_pos, nullptr,
  12420. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12421. ext_factor, attn_factor, beta_fast, beta_slow
  12422. );
  12423. cb(Qcur, "Qcur_rope", il);
  12424. Kcur = ggml_rope_ext(
  12425. ctx0, Kcur, inp_pos, nullptr,
  12426. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12427. ext_factor, attn_factor, beta_fast, beta_slow
  12428. );
  12429. cb(Kcur, "Kcur_rope", il);
  12430. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12431. model.layers[il].wo, NULL,
  12432. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12433. }
  12434. if (il == n_layer - 1) {
  12435. // skip computing output for unused tokens
  12436. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12437. n_tokens = n_outputs;
  12438. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12439. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12440. }
  12441. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12442. cb(ffn_inp, "ffn_inp", il);
  12443. // MoE branch
  12444. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12445. model.layers[il].ffn_norm, NULL,
  12446. LLM_NORM_RMS, cb, il);
  12447. cb(cur, "ffn_norm", il);
  12448. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  12449. model.layers[il].ffn_gate_inp,
  12450. model.layers[il].ffn_up_exps,
  12451. model.layers[il].ffn_gate_exps,
  12452. model.layers[il].ffn_down_exps,
  12453. n_expert, n_expert_used,
  12454. LLM_FFN_SILU, false,
  12455. false, 0.0,
  12456. cb, il);
  12457. cb(cur, "ffn_moe_out", il);
  12458. cur = ggml_add(ctx0, cur, ffn_inp);
  12459. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12460. cb(cur, "l_out", il);
  12461. // input for next layer
  12462. inpL = cur;
  12463. }
  12464. cur = inpL;
  12465. cur = llm_build_norm(ctx0, cur, hparams,
  12466. model.output_norm, NULL,
  12467. LLM_NORM_RMS, cb, -1);
  12468. cb(cur, "result_norm", -1);
  12469. // lm_head
  12470. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12471. cb(cur, "result_output", -1);
  12472. ggml_build_forward_expand(gf, cur);
  12473. return gf;
  12474. }
  12475. struct ggml_cgraph * build_openelm() {
  12476. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12477. const int64_t n_embd_head = hparams.n_embd_head_v;
  12478. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12479. struct ggml_tensor * cur;
  12480. struct ggml_tensor * inpL;
  12481. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12482. // inp_pos - contains the positions
  12483. struct ggml_tensor * inp_pos = build_inp_pos();
  12484. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12485. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12486. for (int il = 0; il < n_layer; ++il) {
  12487. const int64_t n_head = hparams.n_head(il);
  12488. const int64_t n_head_kv = hparams.n_head_kv(il);
  12489. const int64_t n_head_qkv = 2*n_head_kv + n_head;
  12490. cur = inpL;
  12491. struct ggml_tensor * residual = cur;
  12492. // norm
  12493. cur = llm_build_norm(ctx0, inpL, hparams,
  12494. model.layers[il].attn_norm, NULL,
  12495. LLM_NORM_RMS, cb, il);
  12496. cb(cur, "attn_norm", il);
  12497. // self-attention
  12498. {
  12499. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  12500. cb(cur, "wqkv", il);
  12501. cur = ggml_reshape_3d(ctx0, cur, n_embd_head_k, n_head_qkv, n_tokens);
  12502. 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));
  12503. cb(Qcur, "Qcur", il);
  12504. 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));
  12505. cb(Kcur, "Kcur", il);
  12506. 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)));
  12507. cb(Vcur, "Vcur", il);
  12508. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  12509. model.layers[il].attn_q_norm, NULL,
  12510. LLM_NORM_RMS, cb, il);
  12511. cb(Qcur, "Qcur", il);
  12512. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  12513. model.layers[il].attn_k_norm, NULL,
  12514. LLM_NORM_RMS, cb, il);
  12515. cb(Kcur, "Kcur", il);
  12516. Qcur = ggml_rope_ext(
  12517. ctx0, Qcur, inp_pos, NULL, n_rot, rope_type, n_ctx_orig,
  12518. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  12519. );
  12520. cb(Qcur, "Qcur", il);
  12521. Kcur = ggml_rope_ext(
  12522. ctx0, Kcur, inp_pos, NULL, n_rot, rope_type, n_ctx_orig,
  12523. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  12524. );
  12525. cb(Kcur, "Kcur", il);
  12526. Vcur = ggml_reshape_2d(ctx0, Vcur, n_embd_head * n_head_kv, n_tokens);
  12527. cb(Qcur, "Vcur", il);
  12528. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12529. model.layers[il].wo, NULL,
  12530. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12531. }
  12532. if (il == n_layer - 1) {
  12533. // skip computing output for unused tokens
  12534. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12535. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  12536. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12537. }
  12538. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  12539. cb(ffn_inp, "ffn_inp", il);
  12540. // feed-forward network
  12541. {
  12542. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12543. model.layers[il].ffn_norm, NULL,
  12544. LLM_NORM_RMS, cb, il);
  12545. cb(cur, "ffn_norm", il);
  12546. cur = llm_build_ffn(ctx0, lctx, cur,
  12547. model.layers[il].ffn_up, NULL, NULL,
  12548. model.layers[il].ffn_gate, NULL, NULL,
  12549. model.layers[il].ffn_down, NULL, NULL,
  12550. NULL,
  12551. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12552. cb(cur, "ffn_out", il);
  12553. }
  12554. cur = ggml_add(ctx0, cur, ffn_inp);
  12555. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12556. cb(cur, "l_out", il);
  12557. inpL = cur;
  12558. }
  12559. cur = inpL;
  12560. // norm
  12561. cur = llm_build_norm(ctx0, cur, hparams,
  12562. model.output_norm, NULL,
  12563. LLM_NORM_RMS, cb, -1);
  12564. cb(cur, "result_norm", -1);
  12565. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12566. cb(cur, "result_output", -1);
  12567. ggml_build_forward_expand(gf, cur);
  12568. return gf;
  12569. }
  12570. struct ggml_cgraph * build_gptneox() {
  12571. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12572. const int64_t n_embd_head = hparams.n_embd_head_v;
  12573. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  12574. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12575. struct ggml_tensor * cur;
  12576. struct ggml_tensor * inpL;
  12577. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12578. // inp_pos - contains the positions
  12579. struct ggml_tensor * inp_pos = build_inp_pos();
  12580. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12581. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12582. for (int il = 0; il < n_layer; ++il) {
  12583. cur = llm_build_norm(ctx0, inpL, hparams,
  12584. model.layers[il].attn_norm,
  12585. model.layers[il].attn_norm_b,
  12586. LLM_NORM, cb, il);
  12587. cb(cur, "attn_norm", il);
  12588. // self-attention
  12589. {
  12590. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  12591. cb(cur, "wqkv", il);
  12592. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  12593. cb(cur, "bqkv", il);
  12594. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  12595. 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)));
  12596. 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)));
  12597. cb(Qcur, "Qcur", il);
  12598. cb(Kcur, "Kcur", il);
  12599. cb(Vcur, "Vcur", il);
  12600. Qcur = ggml_rope_ext(
  12601. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  12602. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12603. ext_factor, attn_factor, beta_fast, beta_slow
  12604. );
  12605. cb(Qcur, "Qcur", il);
  12606. Kcur = ggml_rope_ext(
  12607. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  12608. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12609. ext_factor, attn_factor, beta_fast, beta_slow
  12610. );
  12611. cb(Kcur, "Kcur", il);
  12612. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12613. model.layers[il].wo, model.layers[il].bo,
  12614. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12615. }
  12616. if (il == n_layer - 1) {
  12617. // skip computing output for unused tokens
  12618. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12619. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12620. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  12621. }
  12622. // ffn
  12623. if (hparams.use_par_res) {
  12624. // attention and ffn are computed in parallel
  12625. // x = x + attn(ln1(x)) + ffn(ln2(x))
  12626. struct ggml_tensor * attn_out = cur;
  12627. cur = llm_build_norm(ctx0, inpL, hparams,
  12628. model.layers[il].ffn_norm,
  12629. model.layers[il].ffn_norm_b,
  12630. LLM_NORM, cb, il);
  12631. cb(cur, "ffn_norm", il);
  12632. cur = llm_build_ffn(ctx0, lctx, cur,
  12633. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  12634. NULL, NULL, NULL,
  12635. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  12636. NULL,
  12637. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  12638. cb(cur, "ffn_out", il);
  12639. cur = ggml_add(ctx0, cur, inpL);
  12640. cb(cur, "ffn_out", il);
  12641. cur = ggml_add(ctx0, cur, attn_out);
  12642. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12643. cb(cur, "l_out", il);
  12644. // input for next layer
  12645. inpL = cur;
  12646. } else {
  12647. // attention and ffn are computed sequentially
  12648. // x = x + attn(ln1(x))
  12649. // x = x + ffn(ln2(x))
  12650. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  12651. cb(ffn_inp, "ffn_inp", il);
  12652. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12653. model.layers[il].ffn_norm,
  12654. model.layers[il].ffn_norm_b,
  12655. LLM_NORM, cb, il);
  12656. cb(cur, "ffn_norm", il);
  12657. cur = llm_build_ffn(ctx0, lctx, cur,
  12658. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  12659. NULL, NULL, NULL,
  12660. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  12661. NULL,
  12662. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  12663. cb(cur, "ffn_out", il);
  12664. cur = ggml_add(ctx0, cur, ffn_inp);
  12665. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12666. cb(cur, "l_out", il);
  12667. // input for next layer
  12668. inpL = cur;
  12669. }
  12670. }
  12671. cur = llm_build_norm(ctx0, inpL, hparams,
  12672. model.output_norm,
  12673. model.output_norm_b,
  12674. LLM_NORM, cb, -1);
  12675. cb(cur, "result_norm", -1);
  12676. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12677. cb(cur, "result_output", -1);
  12678. ggml_build_forward_expand(gf, cur);
  12679. return gf;
  12680. }
  12681. struct ggml_cgraph * build_arctic() {
  12682. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12683. // mutable variable, needed during the last layer of the computation to skip unused tokens
  12684. int32_t n_tokens = this->n_tokens;
  12685. const int64_t n_embd_head = hparams.n_embd_head_v;
  12686. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12687. GGML_ASSERT(n_embd_head == hparams.n_rot);
  12688. struct ggml_tensor * cur;
  12689. struct ggml_tensor * inpL;
  12690. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12691. // inp_pos - contains the positions
  12692. struct ggml_tensor * inp_pos = build_inp_pos();
  12693. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12694. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12695. for (int il = 0; il < n_layer; ++il) {
  12696. struct ggml_tensor * inpSA = inpL;
  12697. // norm
  12698. cur = llm_build_norm(ctx0, inpL, hparams,
  12699. model.layers[il].attn_norm, NULL,
  12700. LLM_NORM_RMS, cb, il);
  12701. cb(cur, "attn_norm", il);
  12702. // self-attention
  12703. {
  12704. // compute Q and K and RoPE them
  12705. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12706. cb(Qcur, "Qcur", il);
  12707. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12708. cb(Kcur, "Kcur", il);
  12709. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12710. cb(Vcur, "Vcur", il);
  12711. Qcur = ggml_rope_ext(
  12712. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  12713. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12714. ext_factor, attn_factor, beta_fast, beta_slow
  12715. );
  12716. cb(Qcur, "Qcur", il);
  12717. Kcur = ggml_rope_ext(
  12718. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  12719. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12720. ext_factor, attn_factor, beta_fast, beta_slow
  12721. );
  12722. cb(Kcur, "Kcur", il);
  12723. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12724. model.layers[il].wo, NULL,
  12725. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12726. }
  12727. if (il == n_layer - 1) {
  12728. // skip computing output for unused tokens
  12729. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12730. n_tokens = n_outputs;
  12731. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12732. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12733. }
  12734. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12735. cb(ffn_inp, "ffn_inp", il);
  12736. // feed-forward network
  12737. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12738. model.layers[il].ffn_norm, NULL,
  12739. LLM_NORM_RMS, cb, il);
  12740. cb(cur, "ffn_norm", il);
  12741. cur = llm_build_ffn(ctx0, lctx, cur,
  12742. model.layers[il].ffn_up, NULL, NULL,
  12743. model.layers[il].ffn_gate, NULL, NULL,
  12744. model.layers[il].ffn_down, NULL, NULL,
  12745. NULL,
  12746. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12747. cb(cur, "ffn_out", il);
  12748. struct ggml_tensor * ffn_out = ggml_add(ctx0, cur, ffn_inp);
  12749. cb(ffn_out, "ffn_out", il);
  12750. // MoE
  12751. cur = llm_build_norm(ctx0, inpSA, hparams,
  12752. model.layers[il].ffn_norm_exps, NULL,
  12753. LLM_NORM_RMS, cb, il);
  12754. cb(cur, "ffn_norm_exps", il);
  12755. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  12756. model.layers[il].ffn_gate_inp,
  12757. model.layers[il].ffn_up_exps,
  12758. model.layers[il].ffn_gate_exps,
  12759. model.layers[il].ffn_down_exps,
  12760. n_expert, n_expert_used,
  12761. LLM_FFN_SILU, true,
  12762. false, 0.0,
  12763. cb, il);
  12764. cb(cur, "ffn_moe_out", il);
  12765. cur = ggml_add(ctx0, cur, ffn_out);
  12766. cb(cur, "ffn_out", il);
  12767. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12768. cb(cur, "l_out", il);
  12769. // input for next layer
  12770. inpL = cur;
  12771. }
  12772. cur = inpL;
  12773. cur = llm_build_norm(ctx0, cur, hparams,
  12774. model.output_norm, NULL,
  12775. LLM_NORM_RMS, cb, -1);
  12776. cb(cur, "result_norm", -1);
  12777. // lm_head
  12778. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12779. cb(cur, "result_output", -1);
  12780. ggml_build_forward_expand(gf, cur);
  12781. return gf;
  12782. }
  12783. struct ggml_cgraph * build_deepseek2() {
  12784. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12785. // mutable variable, needed during the last layer of the computation to skip unused tokens
  12786. int32_t n_tokens = this->n_tokens;
  12787. bool is_lite = (hparams.n_layer == 27);
  12788. // We have to pre-scale kq_scale and attn_factor to make the YaRN RoPE work correctly.
  12789. // See https://github.com/ggerganov/llama.cpp/discussions/7416 for detailed explanation.
  12790. const float mscale = attn_factor * (1.0f + hparams.rope_yarn_log_mul * logf(1.0f / freq_scale));
  12791. const float kq_scale = 1.0f*mscale*mscale/sqrtf(float(hparams.n_embd_head_k));
  12792. const float attn_factor_scaled = 1.0f / (1.0f + 0.1f * logf(1.0f / freq_scale));
  12793. const uint32_t n_embd_head_qk_rope = hparams.n_rot;
  12794. const uint32_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  12795. const uint32_t kv_lora_rank = hparams.n_lora_kv;
  12796. struct ggml_tensor * cur;
  12797. struct ggml_tensor * inpL;
  12798. // {n_embd, n_tokens}
  12799. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12800. // inp_pos - contains the positions
  12801. struct ggml_tensor * inp_pos = build_inp_pos();
  12802. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12803. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12804. for (int il = 0; il < n_layer; ++il) {
  12805. struct ggml_tensor * inpSA = inpL;
  12806. // norm
  12807. cur = llm_build_norm(ctx0, inpL, hparams,
  12808. model.layers[il].attn_norm, NULL,
  12809. LLM_NORM_RMS, cb, il);
  12810. cb(cur, "attn_norm", il);
  12811. // self_attention
  12812. {
  12813. struct ggml_tensor * q = NULL;
  12814. if (!is_lite) {
  12815. // {n_embd, q_lora_rank} * {n_embd, n_tokens} -> {q_lora_rank, n_tokens}
  12816. q = ggml_mul_mat(ctx0, model.layers[il].wq_a, cur);
  12817. cb(q, "q", il);
  12818. q = llm_build_norm(ctx0, q, hparams,
  12819. model.layers[il].attn_q_a_norm, NULL,
  12820. LLM_NORM_RMS, cb, il);
  12821. cb(q, "q", il);
  12822. // {q_lora_rank, n_head * hparams.n_embd_head_k} * {q_lora_rank, n_tokens} -> {n_head * hparams.n_embd_head_k, n_tokens}
  12823. q = ggml_mul_mat(ctx0, model.layers[il].wq_b, q);
  12824. cb(q, "q", il);
  12825. } else {
  12826. q = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  12827. cb(q, "q", il);
  12828. }
  12829. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  12830. struct ggml_tensor * q_nope = ggml_view_3d(ctx0, q, n_embd_head_qk_nope, n_head, n_tokens,
  12831. ggml_row_size(q->type, hparams.n_embd_head_k),
  12832. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  12833. 0);
  12834. cb(q_nope, "q_nope", il);
  12835. // and {n_head * n_embd_head_qk_rope, n_tokens}
  12836. struct ggml_tensor * q_pe = ggml_view_3d(ctx0, q, n_embd_head_qk_rope, n_head, n_tokens,
  12837. ggml_row_size(q->type, hparams.n_embd_head_k),
  12838. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  12839. ggml_row_size(q->type, n_embd_head_qk_nope));
  12840. cb(q_pe, "q_pe", il);
  12841. // {n_embd, kv_lora_rank + n_embd_head_qk_rope} * {n_embd, n_tokens} -> {kv_lora_rank + n_embd_head_qk_rope, n_tokens}
  12842. struct ggml_tensor * kv_pe_compresseed = ggml_mul_mat(ctx0, model.layers[il].wkv_a_mqa, cur);
  12843. cb(kv_pe_compresseed, "kv_pe_compresseed", il);
  12844. // split into {kv_lora_rank, n_tokens}
  12845. struct ggml_tensor * kv_compressed = ggml_view_2d(ctx0, kv_pe_compresseed, kv_lora_rank, n_tokens,
  12846. kv_pe_compresseed->nb[1],
  12847. 0);
  12848. cb(kv_compressed, "kv_compressed", il);
  12849. // and {n_embd_head_qk_rope, n_tokens}
  12850. struct ggml_tensor * k_pe = ggml_view_3d(ctx0, kv_pe_compresseed, n_embd_head_qk_rope, 1, n_tokens,
  12851. kv_pe_compresseed->nb[1],
  12852. kv_pe_compresseed->nb[1],
  12853. ggml_row_size(kv_pe_compresseed->type, kv_lora_rank));
  12854. cb(k_pe, "k_pe", il);
  12855. kv_compressed = ggml_cont(ctx0, kv_compressed); // TODO: the CUDA backend does not support non-contiguous norm
  12856. kv_compressed = llm_build_norm(ctx0, kv_compressed, hparams,
  12857. model.layers[il].attn_kv_a_norm, NULL,
  12858. LLM_NORM_RMS, cb, il);
  12859. cb(kv_compressed, "kv_compressed", il);
  12860. // {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}
  12861. struct ggml_tensor * kv = ggml_mul_mat(ctx0, model.layers[il].wkv_b, kv_compressed);
  12862. cb(kv, "kv", il);
  12863. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  12864. struct ggml_tensor * k_nope = ggml_view_3d(ctx0, kv, n_embd_head_qk_nope, n_head, n_tokens,
  12865. ggml_row_size(kv->type, n_embd_head_qk_nope + hparams.n_embd_head_v),
  12866. ggml_row_size(kv->type, n_head * (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  12867. 0);
  12868. cb(k_nope, "k_nope", il);
  12869. // and {n_head * n_embd_head_v, n_tokens}
  12870. struct ggml_tensor * v_states = ggml_view_3d(ctx0, kv, hparams.n_embd_head_v, n_head, n_tokens,
  12871. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  12872. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)*n_head),
  12873. ggml_row_size(kv->type, (n_embd_head_qk_nope)));
  12874. cb(v_states, "v_states", il);
  12875. v_states = ggml_cont(ctx0, v_states);
  12876. cb(v_states, "v_states", il);
  12877. v_states = ggml_view_2d(ctx0, v_states, hparams.n_embd_head_v * n_head, n_tokens,
  12878. ggml_row_size(kv->type, hparams.n_embd_head_v * n_head),
  12879. 0);
  12880. cb(v_states, "v_states", il);
  12881. q_pe = ggml_cont(ctx0, q_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  12882. q_pe = ggml_rope_ext(
  12883. ctx0, q_pe, inp_pos, nullptr,
  12884. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12885. ext_factor, attn_factor_scaled, beta_fast, beta_slow
  12886. );
  12887. cb(q_pe, "q_pe", il);
  12888. // shared RoPE key
  12889. k_pe = ggml_cont(ctx0, k_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  12890. k_pe = ggml_rope_ext(
  12891. ctx0, k_pe, inp_pos, nullptr,
  12892. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12893. ext_factor, attn_factor_scaled, beta_fast, beta_slow
  12894. );
  12895. cb(k_pe, "k_pe", il);
  12896. struct ggml_tensor * q_states = ggml_concat(ctx0, q_nope, q_pe, 0);
  12897. cb(q_states, "q_states", il);
  12898. struct ggml_tensor * k_states = ggml_concat(ctx0, k_nope, ggml_repeat(ctx0, k_pe, q_pe), 0);
  12899. cb(k_states, "k_states", il);
  12900. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12901. model.layers[il].wo, NULL,
  12902. k_states, v_states, q_states, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  12903. }
  12904. if (il == n_layer - 1) {
  12905. // skip computing output for unused tokens
  12906. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12907. n_tokens = n_outputs;
  12908. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12909. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12910. }
  12911. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12912. cb(ffn_inp, "ffn_inp", il);
  12913. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12914. model.layers[il].ffn_norm, NULL,
  12915. LLM_NORM_RMS, cb, il);
  12916. cb(cur, "ffn_norm", il);
  12917. if ((uint32_t) il < hparams.n_layer_dense_lead) {
  12918. cur = llm_build_ffn(ctx0, lctx, cur,
  12919. model.layers[il].ffn_up, NULL, NULL,
  12920. model.layers[il].ffn_gate, NULL, NULL,
  12921. model.layers[il].ffn_down, NULL, NULL,
  12922. NULL,
  12923. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12924. cb(cur, "ffn_out", il);
  12925. } else {
  12926. // MoE branch
  12927. ggml_tensor * moe_out =
  12928. llm_build_moe_ffn(ctx0, lctx, cur,
  12929. model.layers[il].ffn_gate_inp,
  12930. model.layers[il].ffn_up_exps,
  12931. model.layers[il].ffn_gate_exps,
  12932. model.layers[il].ffn_down_exps,
  12933. n_expert, n_expert_used,
  12934. LLM_FFN_SILU, false,
  12935. true, hparams.expert_weights_scale,
  12936. cb, il);
  12937. cb(moe_out, "ffn_moe_out", il);
  12938. // FFN shared expert
  12939. {
  12940. ggml_tensor * ffn_shexp = llm_build_ffn(ctx0, lctx, cur,
  12941. model.layers[il].ffn_up_shexp, NULL, NULL,
  12942. model.layers[il].ffn_gate_shexp, NULL, NULL,
  12943. model.layers[il].ffn_down_shexp, NULL, NULL,
  12944. NULL,
  12945. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12946. cb(ffn_shexp, "ffn_shexp", il);
  12947. cur = ggml_add(ctx0, moe_out, ffn_shexp);
  12948. cb(cur, "ffn_out", il);
  12949. }
  12950. }
  12951. cur = ggml_add(ctx0, cur, ffn_inp);
  12952. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12953. cb(cur, "l_out", il);
  12954. // input for next layer
  12955. inpL = cur;
  12956. }
  12957. cur = inpL;
  12958. cur = llm_build_norm(ctx0, cur, hparams,
  12959. model.output_norm, NULL,
  12960. LLM_NORM_RMS, cb, -1);
  12961. cb(cur, "result_norm", -1);
  12962. // lm_head
  12963. cur = ggml_mul_mat(ctx0, model.output, cur);
  12964. cb(cur, "result_output", -1);
  12965. ggml_build_forward_expand(gf, cur);
  12966. return gf;
  12967. }
  12968. struct ggml_cgraph * build_bitnet() {
  12969. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12970. const int64_t n_embd_head = hparams.n_embd_head_v;
  12971. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12972. struct ggml_tensor * cur;
  12973. struct ggml_tensor * inpL;
  12974. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12975. // inp_pos - contains the positions
  12976. struct ggml_tensor * inp_pos = build_inp_pos();
  12977. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12978. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12979. for (int il = 0; il < n_layer; ++il) {
  12980. struct ggml_tensor * inpSA = inpL;
  12981. cur = llm_build_norm(ctx0, inpL, hparams,
  12982. model.layers[il].attn_norm, NULL,
  12983. LLM_NORM_RMS, cb, il);
  12984. cb(cur, "attn_norm", il);
  12985. // self-attention
  12986. {
  12987. // compute Q and K and RoPE them
  12988. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12989. if (model.layers[il].wq_scale) {
  12990. Qcur = ggml_mul(ctx0, Qcur, model.layers[il].wq_scale);
  12991. }
  12992. cb(Qcur, "Qcur", il);
  12993. if (model.layers[il].bq) {
  12994. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  12995. cb(Qcur, "Qcur", il);
  12996. }
  12997. // B1.K
  12998. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12999. if (model.layers[il].wk_scale) {
  13000. Kcur = ggml_mul(ctx0, Kcur, model.layers[il].wk_scale);
  13001. }
  13002. cb(Kcur, "Kcur", il);
  13003. if (model.layers[il].bk) {
  13004. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  13005. cb(Kcur, "Kcur", il);
  13006. }
  13007. // B1.V
  13008. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  13009. if (model.layers[il].wv_scale) {
  13010. Vcur = ggml_mul(ctx0, Vcur, model.layers[il].wv_scale);
  13011. }
  13012. cb(Vcur, "Vcur", il);
  13013. if (model.layers[il].bv) {
  13014. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  13015. cb(Vcur, "Vcur", il);
  13016. }
  13017. Qcur = ggml_rope_ext(
  13018. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  13019. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13020. ext_factor, attn_factor, beta_fast, beta_slow
  13021. );
  13022. cb(Qcur, "Qcur", il);
  13023. Kcur = ggml_rope_ext(
  13024. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  13025. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13026. ext_factor, attn_factor, beta_fast, beta_slow
  13027. );
  13028. cb(Kcur, "Kcur", il);
  13029. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13030. NULL, NULL,
  13031. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13032. cur = llm_build_norm(ctx0, cur, hparams,
  13033. model.layers[il].attn_sub_norm, NULL,
  13034. LLM_NORM_RMS, cb, il);
  13035. cb(cur, "attn_sub_norm", il);
  13036. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  13037. if (model.layers[il].wo_scale) {
  13038. cur = ggml_mul(ctx0, cur, model.layers[il].wo_scale);
  13039. }
  13040. if (model.layers[il].bo) {
  13041. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  13042. }
  13043. cb(cur, "attn_o_out", il);
  13044. }
  13045. if (il == n_layer - 1) {
  13046. // skip computing output for unused tokens
  13047. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13048. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13049. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13050. }
  13051. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13052. cb(ffn_inp, "ffn_inp", il);
  13053. // feed-forward forward
  13054. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13055. model.layers[il].ffn_norm, NULL,
  13056. LLM_NORM_RMS, cb, il);
  13057. cb(cur, "ffn_norm", il);
  13058. cur = llm_build_ffn(ctx0, lctx, cur,
  13059. model.layers[il].ffn_up, NULL, model.layers[il].ffn_up_scale,
  13060. model.layers[il].ffn_gate, NULL, model.layers[il].ffn_gate_scale,
  13061. NULL, NULL, NULL,
  13062. NULL,
  13063. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13064. cb(cur, "ffn_sub_out", il);
  13065. cur = llm_build_norm(ctx0, cur, hparams,
  13066. model.layers[il].ffn_sub_norm, NULL,
  13067. LLM_NORM_RMS, cb, il);
  13068. cb(cur, "ffn_sub_norm", il);
  13069. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].ffn_down, cur);
  13070. if (model.layers[il].ffn_down_scale) {
  13071. cur = ggml_mul(ctx0, cur, model.layers[il].ffn_down_scale);
  13072. }
  13073. cb(cur, "ffn_down", il);
  13074. cur = ggml_add(ctx0, cur, ffn_inp);
  13075. cb(cur, "l_out", il);
  13076. // input for next layer
  13077. inpL = cur;
  13078. }
  13079. cur = inpL;
  13080. cur = llm_build_norm(ctx0, cur, hparams,
  13081. model.output_norm, NULL,
  13082. LLM_NORM_RMS, cb, -1);
  13083. cb(cur, "result_norm", -1);
  13084. // lm_head
  13085. cur = llm_build_lora_mm(lctx, ctx0, model.tok_embd, cur);
  13086. cb(cur, "result_output", -1);
  13087. ggml_build_forward_expand(gf, cur);
  13088. return gf;
  13089. }
  13090. struct ggml_cgraph * build_t5_encoder() {
  13091. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13092. // mutable variable, needed during the last layer of the computation to skip unused tokens
  13093. int32_t n_tokens = this->n_tokens;
  13094. const int64_t n_embd_head = hparams.n_embd_head_v;
  13095. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  13096. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13097. struct ggml_tensor * cur;
  13098. struct ggml_tensor * inpL;
  13099. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  13100. GGML_ASSERT(lctx.is_encoding);
  13101. struct ggml_tensor * pos_bucket_enc = llm_build_pos_bucket(false);
  13102. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13103. struct ggml_tensor * KQ_mask_enc = build_inp_KQ_mask(false);
  13104. for (int il = 0; il < n_layer; ++il) {
  13105. struct ggml_tensor * inpSA = inpL;
  13106. // norm
  13107. cur = llm_build_norm(ctx0, inpL, hparams,
  13108. model.layers[il].attn_norm_enc, NULL,
  13109. LLM_NORM_RMS, cb, il);
  13110. cb(cur, "attn_norm", il);
  13111. // self-attention
  13112. {
  13113. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq_enc, cur);
  13114. cb(Qcur, "Qcur", il);
  13115. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk_enc, cur);
  13116. cb(Kcur, "Kcur", il);
  13117. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv_enc, cur);
  13118. cb(Vcur, "Vcur", il);
  13119. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  13120. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  13121. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  13122. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  13123. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  13124. cb(kq, "kq", il);
  13125. 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;
  13126. struct ggml_tensor * pos_bias = llm_build_pos_bias(pos_bucket_enc, attn_rel_b);
  13127. struct ggml_tensor * kq_b = ggml_add(ctx0, kq, pos_bias);
  13128. cb(kq_b, "kq_b", il);
  13129. kq = ggml_soft_max_ext(ctx0, kq_b, KQ_mask_enc, 1.0f, hparams.f_max_alibi_bias);
  13130. cb(kq, "kq_soft_max_ext", il);
  13131. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  13132. cb(v, "v", il);
  13133. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  13134. cb(kqv, "kqv", il);
  13135. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  13136. cb(kqv_merged, "kqv_merged", il);
  13137. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  13138. cb(cur, "kqv_merged_cont", il);
  13139. ggml_build_forward_expand(gf, cur);
  13140. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo_enc, cur);
  13141. cb(cur, "kqv_out", il);
  13142. }
  13143. if (il == n_layer - 1) {
  13144. // skip computing output for unused tokens
  13145. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13146. n_tokens = n_outputs;
  13147. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13148. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13149. }
  13150. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13151. cb(ffn_inp, "ffn_inp", il);
  13152. // feed-forward network
  13153. {
  13154. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13155. model.layers[il].ffn_norm_enc, NULL,
  13156. LLM_NORM_RMS, cb, il);
  13157. cb(cur, "ffn_norm", il);
  13158. // T5 uses relu, flan-T5 uses gelu-gated
  13159. cur = llm_build_ffn(ctx0, lctx, cur,
  13160. model.layers[il].ffn_up_enc, NULL, NULL,
  13161. model.layers[il].ffn_gate_enc, NULL, NULL,
  13162. model.layers[il].ffn_down_enc, NULL, NULL,
  13163. NULL,
  13164. model.layers[il].ffn_gate_enc ? LLM_FFN_GELU : LLM_FFN_RELU,
  13165. model.layers[il].ffn_gate_enc ? LLM_FFN_PAR : LLM_FFN_SEQ,
  13166. cb, il);
  13167. cb(cur, "ffn_out", il);
  13168. }
  13169. cur = ggml_add(ctx0, cur, ffn_inp);
  13170. cb(cur, "ffn_out", il);
  13171. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  13172. if (layer_dir != nullptr) {
  13173. cur = ggml_add(ctx0, cur, layer_dir);
  13174. }
  13175. cb(cur, "l_out", il);
  13176. // input for next layer
  13177. inpL = cur;
  13178. }
  13179. cur = inpL;
  13180. cb(cur, "result_embd", -1);
  13181. cur = llm_build_norm(ctx0, cur, hparams,
  13182. model.output_norm_enc, NULL,
  13183. LLM_NORM_RMS, cb, -1);
  13184. cb(cur, "result_norm", -1);
  13185. ggml_build_forward_expand(gf, cur);
  13186. return gf;
  13187. }
  13188. struct ggml_cgraph * build_t5_decoder() {
  13189. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13190. // mutable variable, needed during the last layer of the computation to skip unused tokens
  13191. int32_t n_tokens = this->n_tokens;
  13192. const int64_t n_embd_head = hparams.n_embd_head_v;
  13193. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  13194. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13195. struct ggml_tensor * cur;
  13196. struct ggml_tensor * inpL;
  13197. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  13198. GGML_ASSERT(!lctx.is_encoding);
  13199. GGML_ASSERT(n_outputs_enc > 0 && "call llama_encode() first");
  13200. struct ggml_tensor * embd_enc = llm_build_inp_embd_enc();
  13201. struct ggml_tensor * pos_bucket_dec = llm_build_pos_bucket(true);
  13202. struct ggml_tensor * KQ_mask_dec = build_inp_KQ_mask();
  13203. struct ggml_tensor * KQ_mask_cross = llm_build_inp_KQ_mask_cross();
  13204. for (int il = 0; il < n_layer; ++il) {
  13205. struct ggml_tensor * inpSA = inpL;
  13206. // norm
  13207. cur = llm_build_norm(ctx0, inpL, hparams,
  13208. model.layers[il].attn_norm, NULL,
  13209. LLM_NORM_RMS, cb, il);
  13210. cb(cur, "attn_norm", il);
  13211. // self-attention
  13212. {
  13213. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  13214. cb(Qcur, "Qcur", il);
  13215. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  13216. cb(Kcur, "Kcur", il);
  13217. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  13218. cb(Vcur, "Vcur", il);
  13219. llm_build_kv_store(ctx0, hparams, cparams, kv_self, gf, Kcur, Vcur, n_tokens, kv_head, cb, il);
  13220. struct ggml_tensor * k =
  13221. ggml_view_3d(ctx0, kv_self.k_l[il],
  13222. n_embd_head_k, n_kv, n_head_kv,
  13223. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  13224. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  13225. 0);
  13226. cb(k, "k", il);
  13227. struct ggml_tensor * v =
  13228. ggml_view_3d(ctx0, kv_self.v_l[il],
  13229. n_kv, n_embd_head_v, n_head_kv,
  13230. ggml_element_size(kv_self.v_l[il])*n_ctx,
  13231. ggml_element_size(kv_self.v_l[il])*n_ctx*n_embd_head_v,
  13232. 0);
  13233. cb(v, "v", il);
  13234. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  13235. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  13236. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  13237. cb(kq, "kq", il);
  13238. struct ggml_tensor * attn_rel_b = model.layers[il].attn_rel_b ? model.layers[il].attn_rel_b : model.layers[0].attn_rel_b;
  13239. struct ggml_tensor * pos_bias = llm_build_pos_bias(pos_bucket_dec, attn_rel_b);
  13240. struct ggml_tensor * kq_b = ggml_add(ctx0, kq, pos_bias);
  13241. cb(kq_b, "kq_b", il);
  13242. kq = ggml_soft_max_ext(ctx0, kq_b, KQ_mask_dec, 1.0f, hparams.f_max_alibi_bias);
  13243. cb(kq, "kq_soft_max_ext", il);
  13244. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, v, kq);
  13245. cb(kqv, "kqv", il);
  13246. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  13247. cb(kqv_merged, "kqv_merged", il);
  13248. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  13249. cb(cur, "kqv_merged_cont", il);
  13250. ggml_build_forward_expand(gf, cur);
  13251. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  13252. cb(cur, "kqv_out", il);
  13253. }
  13254. cur = ggml_add(ctx0, cur, inpSA);
  13255. cb(cur, "cross_inp", il);
  13256. struct ggml_tensor * inpCA = cur;
  13257. // norm
  13258. cur = llm_build_norm(ctx0, cur, hparams,
  13259. model.layers[il].attn_norm_cross, NULL,
  13260. LLM_NORM_RMS, cb, il);
  13261. cb(cur, "attn_norm_cross", il);
  13262. // cross-attention
  13263. {
  13264. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq_cross, cur);
  13265. cb(Qcur, "Qcur", il);
  13266. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk_cross, embd_enc);
  13267. cb(Kcur, "Kcur", il);
  13268. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv_cross, embd_enc);
  13269. cb(Vcur, "Vcur", il);
  13270. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  13271. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_outputs_enc);
  13272. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  13273. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  13274. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  13275. cb(kq, "kq", il);
  13276. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask_cross, 1.0f, hparams.f_max_alibi_bias);
  13277. cb(kq, "kq_soft_max_ext", il);
  13278. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_outputs_enc)));
  13279. cb(v, "v", il);
  13280. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_outputs_enc, n_embd_head, n_head_kv), kq);
  13281. cb(kqv, "kqv", il);
  13282. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  13283. cb(kqv_merged, "kqv_merged", il);
  13284. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  13285. cb(cur, "kqv_merged_cont", il);
  13286. ggml_build_forward_expand(gf, cur);
  13287. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo_cross, cur);
  13288. cb(cur, "kqv_out", il);
  13289. }
  13290. if (il == n_layer - 1) {
  13291. // skip computing output for unused tokens
  13292. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13293. n_tokens = n_outputs;
  13294. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13295. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13296. inpCA = ggml_get_rows(ctx0, inpCA, inp_out_ids);
  13297. }
  13298. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpCA);
  13299. cb(ffn_inp, "ffn_inp", il);
  13300. // feed-forward network
  13301. {
  13302. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13303. model.layers[il].ffn_norm, NULL,
  13304. LLM_NORM_RMS, cb, il);
  13305. cb(cur, "ffn_norm", il);
  13306. // T5 uses relu, flan-T5 uses gelu-gated
  13307. cur = llm_build_ffn(ctx0, lctx, cur,
  13308. model.layers[il].ffn_up, NULL, NULL,
  13309. model.layers[il].ffn_gate, NULL, NULL,
  13310. model.layers[il].ffn_down, NULL, NULL,
  13311. NULL,
  13312. model.layers[il].ffn_gate_enc ? LLM_FFN_GELU : LLM_FFN_RELU,
  13313. model.layers[il].ffn_gate_enc ? LLM_FFN_PAR : LLM_FFN_SEQ,
  13314. cb, il);
  13315. cb(cur, "ffn_out", il);
  13316. }
  13317. cur = ggml_add(ctx0, cur, ffn_inp);
  13318. cb(cur, "ffn_out", il);
  13319. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  13320. if (layer_dir != nullptr) {
  13321. cur = ggml_add(ctx0, cur, layer_dir);
  13322. }
  13323. cb(cur, "l_out", il);
  13324. // input for next layer
  13325. inpL = cur;
  13326. }
  13327. cur = inpL;
  13328. cb(cur, "result_embd", -1);
  13329. cur = llm_build_norm(ctx0, cur, hparams,
  13330. model.output_norm, NULL,
  13331. LLM_NORM_RMS, cb, -1);
  13332. cb(cur, "result_norm", -1);
  13333. // lm_head
  13334. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13335. cb(cur, "result_output", -1);
  13336. ggml_build_forward_expand(gf, cur);
  13337. return gf;
  13338. }
  13339. struct ggml_cgraph * build_jais() {
  13340. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13341. const int64_t n_embd_head = hparams.n_embd_head_v;
  13342. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  13343. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13344. struct ggml_tensor * cur;
  13345. struct ggml_tensor * inpL;
  13346. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  13347. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13348. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13349. for (int il = 0; il < n_layer; ++il) {
  13350. cur = llm_build_norm(ctx0, inpL, hparams,
  13351. model.layers[il].attn_norm,
  13352. model.layers[il].attn_norm_b,
  13353. LLM_NORM, cb, il);
  13354. cb(cur, "attn_norm", il);
  13355. // self-attention
  13356. {
  13357. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  13358. cb(cur, "wqkv", il);
  13359. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  13360. cb(cur, "bqkv", il);
  13361. 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)));
  13362. 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)));
  13363. 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)));
  13364. cb(Qcur, "Qcur", il);
  13365. cb(Kcur, "Kcur", il);
  13366. cb(Vcur, "Vcur", il);
  13367. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  13368. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13369. model.layers[il].wo, model.layers[il].bo,
  13370. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/float(n_embd_head), cb, il);
  13371. }
  13372. if (il == n_layer - 1) {
  13373. // skip computing output for unused tokens
  13374. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13375. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13376. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  13377. }
  13378. // add the input
  13379. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  13380. cb(ffn_inp, "ffn_inp", il);
  13381. // FF
  13382. {
  13383. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13384. model.layers[il].ffn_norm,
  13385. model.layers[il].ffn_norm_b,
  13386. LLM_NORM, cb, il);
  13387. cb(cur, "ffn_norm", il);
  13388. cur = llm_build_ffn(ctx0, lctx, cur,
  13389. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  13390. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  13391. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  13392. NULL,
  13393. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13394. cb(cur, "ffn_out", il);
  13395. }
  13396. inpL = ggml_add(ctx0, cur, ffn_inp);
  13397. cb(inpL, "l_out", il);
  13398. }
  13399. cur = llm_build_norm(ctx0, inpL, hparams,
  13400. model.output_norm,
  13401. model.output_norm_b,
  13402. LLM_NORM, cb, -1);
  13403. cb(cur, "result_norm", -1);
  13404. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13405. cb(cur, "result_output", -1);
  13406. ggml_build_forward_expand(gf, cur);
  13407. return gf;
  13408. }
  13409. struct ggml_cgraph * build_chatglm() {
  13410. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13411. const int64_t n_embd_head = hparams.n_embd_head_v;
  13412. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  13413. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13414. struct ggml_tensor * cur;
  13415. struct ggml_tensor * inpL;
  13416. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  13417. // inp_pos - contains the positions
  13418. struct ggml_tensor * inp_pos = build_inp_pos();
  13419. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13420. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13421. for (int il = 0; il < n_layer; ++il) {
  13422. struct ggml_tensor * inpSA = inpL;
  13423. cur = llm_build_norm(ctx0, inpL, hparams,
  13424. model.layers[il].attn_norm,
  13425. NULL,
  13426. LLM_NORM_RMS, cb, il);
  13427. cb(cur, "attn_norm", il);
  13428. // self-attention
  13429. {
  13430. struct ggml_tensor * Qcur = nullptr;
  13431. struct ggml_tensor * Kcur = nullptr;
  13432. struct ggml_tensor * Vcur = nullptr;
  13433. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  13434. cb(cur, "wqkv", il);
  13435. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  13436. cb(cur, "bqkv", il);
  13437. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  13438. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  13439. 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)));
  13440. cb(Qcur, "Qcur", il);
  13441. cb(Kcur, "Kcur", il);
  13442. cb(Vcur, "Vcur", il);
  13443. //printf("freq_base: %f freq_scale: %f ext_factor: %f attn_factor: %f\n", freq_base, freq_scale, ext_factor, attn_factor);
  13444. Qcur = ggml_rope_ext(
  13445. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  13446. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13447. ext_factor, attn_factor, beta_fast, beta_slow
  13448. );
  13449. cb(Qcur, "Qcur_rope", il);
  13450. Kcur = ggml_rope_ext(
  13451. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  13452. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13453. ext_factor, attn_factor, beta_fast, beta_slow
  13454. );
  13455. cb(Kcur, "Kcur_rope", il);
  13456. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13457. model.layers[il].wo, NULL,
  13458. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13459. }
  13460. if (il == n_layer - 1) {
  13461. // skip computing output for unused tokens
  13462. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13463. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13464. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13465. }
  13466. // Add the input
  13467. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13468. cb(ffn_inp, "ffn_inp", il);
  13469. // FF
  13470. {
  13471. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13472. model.layers[il].ffn_norm,
  13473. NULL,
  13474. LLM_NORM_RMS, cb, il);
  13475. cb(cur, "ffn_norm", il);
  13476. cur = llm_build_ffn(ctx0, lctx, cur,
  13477. model.layers[il].ffn_up, NULL, NULL,
  13478. NULL, NULL, NULL,
  13479. model.layers[il].ffn_down, NULL, NULL,
  13480. NULL,
  13481. LLM_FFN_SWIGLU, LLM_FFN_SEQ, cb, il);
  13482. cb(cur, "ffn_out", il);
  13483. }
  13484. inpL = ggml_add(ctx0, cur, ffn_inp);
  13485. cb(inpL, "l_out", il);
  13486. }
  13487. cur = llm_build_norm(ctx0, inpL, hparams,
  13488. model.output_norm,
  13489. NULL,
  13490. LLM_NORM_RMS, cb, -1);
  13491. cb(cur, "result_norm", -1);
  13492. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13493. cb(cur, "result_output", -1);
  13494. ggml_build_forward_expand(gf, cur);
  13495. return gf;
  13496. }
  13497. struct ggml_cgraph * build_nemotron() {
  13498. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13499. const int64_t n_embd_head = hparams.n_embd_head_v;
  13500. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13501. //GGML_ASSERT(n_embd_head == hparams.n_rot);
  13502. struct ggml_tensor * cur;
  13503. struct ggml_tensor * inpL;
  13504. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  13505. // inp_pos - contains the positions
  13506. struct ggml_tensor * inp_pos = build_inp_pos();
  13507. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13508. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13509. for (int il = 0; il < n_layer; ++il) {
  13510. struct ggml_tensor * inpSA = inpL;
  13511. // norm
  13512. cur = llm_build_norm(ctx0, inpL, hparams,
  13513. model.layers[il].attn_norm,
  13514. model.layers[il].attn_norm_b,
  13515. LLM_NORM, cb, il);
  13516. cb(cur, "attn_norm", il);
  13517. // self-attention
  13518. {
  13519. // compute Q and K and RoPE them
  13520. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  13521. cb(Qcur, "Qcur", il);
  13522. if (model.layers[il].bq) {
  13523. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  13524. cb(Qcur, "Qcur", il);
  13525. }
  13526. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  13527. cb(Kcur, "Kcur", il);
  13528. if (model.layers[il].bk) {
  13529. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  13530. cb(Kcur, "Kcur", il);
  13531. }
  13532. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  13533. cb(Vcur, "Vcur", il);
  13534. if (model.layers[il].bv) {
  13535. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  13536. cb(Vcur, "Vcur", il);
  13537. }
  13538. Qcur = ggml_rope_ext(
  13539. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  13540. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13541. ext_factor, attn_factor, beta_fast, beta_slow
  13542. );
  13543. cb(Qcur, "Qcur", il);
  13544. Kcur = ggml_rope_ext(
  13545. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  13546. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13547. ext_factor, attn_factor, beta_fast, beta_slow
  13548. );
  13549. cb(Kcur, "Kcur", il);
  13550. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13551. model.layers[il].wo, model.layers[il].bo,
  13552. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13553. }
  13554. if (il == n_layer - 1) {
  13555. // skip computing output for unused tokens
  13556. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13557. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13558. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13559. }
  13560. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13561. cb(ffn_inp, "ffn_inp", il);
  13562. // feed-forward network
  13563. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13564. model.layers[il].ffn_norm,
  13565. model.layers[il].ffn_norm_b,
  13566. LLM_NORM, cb, il);
  13567. cb(cur, "ffn_norm", il);
  13568. cur = llm_build_ffn(ctx0, lctx, cur,
  13569. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  13570. NULL, NULL, NULL,
  13571. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  13572. NULL,
  13573. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  13574. cur = ggml_add(ctx0, cur, ffn_inp);
  13575. cb(cur, "ffn_out", il);
  13576. cur = lctx.cvec.apply_to(ctx0, cur, il);
  13577. cb(cur, "l_out", il);
  13578. // input for next layer
  13579. inpL = cur;
  13580. }
  13581. cur = inpL;
  13582. cur = llm_build_norm(ctx0, cur, hparams,
  13583. model.output_norm, model.output_norm_b,
  13584. LLM_NORM, cb, -1);
  13585. cb(cur, "result_norm", -1);
  13586. // lm_head
  13587. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13588. cb(cur, "result_output", -1);
  13589. ggml_build_forward_expand(gf, cur);
  13590. return gf;
  13591. }
  13592. struct ggml_cgraph * build_exaone() {
  13593. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13594. // mutable variable, needed during the last layer of the computation to skip unused tokens
  13595. int32_t n_tokens = this->n_tokens;
  13596. const int64_t n_embd_head = hparams.n_embd_head_v;
  13597. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13598. GGML_ASSERT(n_embd_head == hparams.n_rot);
  13599. struct ggml_tensor * cur;
  13600. struct ggml_tensor * inpL;
  13601. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  13602. // inp_pos - contains the positions
  13603. struct ggml_tensor * inp_pos = build_inp_pos();
  13604. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13605. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13606. for (int il = 0; il < n_layer; ++il) {
  13607. struct ggml_tensor * inpSA = inpL;
  13608. // norm
  13609. cur = llm_build_norm(ctx0, inpL, hparams,
  13610. model.layers[il].attn_norm, NULL,
  13611. LLM_NORM_RMS, cb, il);
  13612. cb(cur, "attn_norm", il);
  13613. // self-attention
  13614. {
  13615. // rope freq factors for llama3; may return nullptr for llama2 and other models
  13616. struct ggml_tensor * rope_factors = build_rope_factors(il);
  13617. // compute Q and K and RoPE them
  13618. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  13619. cb(Qcur, "Qcur", il);
  13620. if (model.layers[il].bq) {
  13621. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  13622. cb(Qcur, "Qcur", il);
  13623. }
  13624. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  13625. cb(Kcur, "Kcur", il);
  13626. if (model.layers[il].bk) {
  13627. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  13628. cb(Kcur, "Kcur", il);
  13629. }
  13630. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  13631. cb(Vcur, "Vcur", il);
  13632. if (model.layers[il].bv) {
  13633. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  13634. cb(Vcur, "Vcur", il);
  13635. }
  13636. Qcur = ggml_rope_ext(
  13637. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  13638. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13639. ext_factor, attn_factor, beta_fast, beta_slow
  13640. );
  13641. cb(Qcur, "Qcur", il);
  13642. Kcur = ggml_rope_ext(
  13643. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  13644. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13645. ext_factor, attn_factor, beta_fast, beta_slow
  13646. );
  13647. cb(Kcur, "Kcur", il);
  13648. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13649. model.layers[il].wo, model.layers[il].bo,
  13650. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13651. }
  13652. if (il == n_layer - 1) {
  13653. // skip computing output for unused tokens
  13654. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13655. n_tokens = n_outputs;
  13656. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13657. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13658. }
  13659. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13660. cb(ffn_inp, "ffn_inp", il);
  13661. // feed-forward network
  13662. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13663. model.layers[il].ffn_norm, NULL,
  13664. LLM_NORM_RMS, cb, il);
  13665. cb(cur, "ffn_norm", il);
  13666. cur = llm_build_ffn(ctx0, lctx, cur,
  13667. model.layers[il].ffn_up, NULL, NULL,
  13668. model.layers[il].ffn_gate, NULL, NULL,
  13669. model.layers[il].ffn_down, NULL, NULL,
  13670. NULL,
  13671. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13672. cb(cur, "ffn_out", il);
  13673. cur = ggml_add(ctx0, cur, ffn_inp);
  13674. cb(cur, "ffn_out", il);
  13675. cur = lctx.cvec.apply_to(ctx0, cur, il);
  13676. cb(cur, "l_out", il);
  13677. // input for next layer
  13678. inpL = cur;
  13679. }
  13680. cur = inpL;
  13681. cur = llm_build_norm(ctx0, cur, hparams,
  13682. model.output_norm, NULL,
  13683. LLM_NORM_RMS, cb, -1);
  13684. cb(cur, "result_norm", -1);
  13685. // lm_head
  13686. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13687. cb(cur, "result_output", -1);
  13688. ggml_build_forward_expand(gf, cur);
  13689. return gf;
  13690. }
  13691. ggml_cgraph * build_rwkv6() {
  13692. ggml_cgraph *gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13693. // Token shift state dimensions should be 2 * n_emb
  13694. GGML_ASSERT(n_embd == hparams.n_embd_k_s() / 2);
  13695. const int64_t n_seqs = batch.n_seqs;
  13696. const int64_t n_seq_tokens = batch.n_seq_tokens;
  13697. const int64_t n_tokens = batch.n_tokens;
  13698. GGML_ASSERT(n_seqs != 0);
  13699. GGML_ASSERT(batch.equal_seqs);
  13700. GGML_ASSERT(n_tokens == n_seq_tokens * n_seqs);
  13701. struct ggml_tensor * cur;
  13702. struct ggml_tensor * inpL;
  13703. struct ggml_tensor * state_copy = build_inp_s_copy();
  13704. struct ggml_tensor * state_mask = build_inp_s_mask();
  13705. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  13706. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  13707. for (int il = 0; il < n_layer; ++il) {
  13708. const llama_layer * layer = &model.layers[il];
  13709. // (ab)using the KV cache to store the states
  13710. struct ggml_tensor * token_shift = llm_build_copy_mask_state(ctx0,
  13711. gf, kv_self.k_l[il], state_copy, state_mask,
  13712. hparams.n_embd_k_s(), kv_self.size, kv_head, n_kv, n_seqs);
  13713. struct ggml_tensor * wkv_states = llm_build_copy_mask_state(ctx0,
  13714. gf, kv_self.v_l[il], state_copy, state_mask,
  13715. hparams.n_embd_v_s(), kv_self.size, kv_head, n_kv, n_seqs);
  13716. cur = ggml_reshape_3d(ctx0, inpL, n_embd, n_seq_tokens, n_seqs);
  13717. token_shift = ggml_reshape_3d(ctx0, token_shift, n_embd, 2, n_seqs);
  13718. 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);
  13719. 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));
  13720. struct ggml_tensor * x_norm_att = llm_build_norm(ctx0, cur, hparams, layer->attn_norm, layer->attn_norm_b, LLM_NORM, cb, il);
  13721. struct ggml_tensor * x_prev = ggml_concat(
  13722. ctx0,
  13723. att_shift,
  13724. 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),
  13725. 1
  13726. );
  13727. cur = ggml_add(ctx0, cur, llm_build_rwkv6_time_mix(lctx, ctx0, layer, x_norm_att, x_prev, &wkv_states));
  13728. ggml_build_forward_expand(gf, cur);
  13729. ggml_build_forward_expand(
  13730. gf,
  13731. ggml_cpy(
  13732. ctx0,
  13733. wkv_states,
  13734. ggml_view_1d(
  13735. ctx0,
  13736. kv_self.v_l[il],
  13737. hparams.n_embd_v_s() * n_seqs,
  13738. hparams.n_embd_v_s() * kv_head * ggml_element_size(kv_self.v_l[il])
  13739. )
  13740. )
  13741. );
  13742. 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);
  13743. x_prev = ggml_concat(
  13744. ctx0,
  13745. ffn_shift,
  13746. 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),
  13747. 1
  13748. );
  13749. cur = ggml_add(ctx0, cur, llm_build_rwkv6_channel_mix(lctx, ctx0, layer, x_norm_ffn, x_prev));
  13750. ggml_build_forward_expand(gf, cur);
  13751. 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));
  13752. 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));
  13753. token_shift = ggml_concat(ctx0, last_norm_att, last_norm_ffn, 1);
  13754. ggml_build_forward_expand(
  13755. gf,
  13756. ggml_cpy(
  13757. ctx0,
  13758. ggml_view_1d(ctx0, token_shift, n_embd * n_seqs * 2, 0),
  13759. 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]))
  13760. )
  13761. );
  13762. if (hparams.rescale_every_n_layers != 0 && (il + 1) % hparams.rescale_every_n_layers == 0) {
  13763. cur = ggml_scale(ctx0, cur, 0.5F);
  13764. }
  13765. cur = lctx.cvec.apply_to(ctx0, cur, il);
  13766. cb(cur, "l_out", il);
  13767. // input for next layer
  13768. inpL = cur;
  13769. }
  13770. cur = inpL;
  13771. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13772. cur = ggml_reshape_2d(ctx0, cur, n_embd, n_tokens);
  13773. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13774. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, model.output_norm_b, LLM_NORM, cb, -1);
  13775. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13776. cb(cur, "result_output", -1);
  13777. ggml_build_forward_expand(gf, cur);
  13778. return gf;
  13779. }
  13780. // ref: https://github.com/facebookresearch/chameleon
  13781. // based on the original build_llama() function, changes:
  13782. // * qk-norm
  13783. // * swin-norm
  13784. // * removed bias
  13785. // * removed MoE
  13786. struct ggml_cgraph * build_chameleon() {
  13787. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13788. // mutable variable, needed during the last layer of the computation to skip unused tokens
  13789. int32_t n_tokens = this->n_tokens;
  13790. const int64_t n_embd_head = hparams.n_embd_head_v;
  13791. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13792. GGML_ASSERT(n_embd_head == hparams.n_rot);
  13793. struct ggml_tensor * cur;
  13794. struct ggml_tensor * inpL;
  13795. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  13796. // inp_pos - contains the positions
  13797. struct ggml_tensor * inp_pos = build_inp_pos();
  13798. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13799. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13800. for (int il = 0; il < n_layer; ++il) {
  13801. struct ggml_tensor * inpSA = inpL;
  13802. // norm
  13803. if (hparams.swin_norm) {
  13804. cur = inpL;
  13805. } else {
  13806. cur = llm_build_norm(ctx0, inpL, hparams,
  13807. model.layers[il].attn_norm, NULL,
  13808. LLM_NORM_RMS, cb, il);
  13809. cb(cur, "attn_norm", il);
  13810. }
  13811. // self-attention
  13812. {
  13813. // compute Q and K and RoPE them
  13814. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  13815. cb(Qcur, "Qcur", il);
  13816. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  13817. cb(Kcur, "Kcur", il);
  13818. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  13819. cb(Vcur, "Vcur", il);
  13820. if (model.layers[il].attn_q_norm) {
  13821. Qcur = ggml_view_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens,
  13822. ggml_element_size(Qcur) * n_embd_head,
  13823. ggml_element_size(Qcur) * n_embd_head * n_head,
  13824. 0);
  13825. cb(Qcur, "Qcur", il);
  13826. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  13827. model.layers[il].attn_q_norm,
  13828. model.layers[il].attn_q_norm_b,
  13829. LLM_NORM, cb, il);
  13830. cb(Qcur, "Qcur", il);
  13831. }
  13832. if (model.layers[il].attn_k_norm) {
  13833. Kcur = ggml_view_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens,
  13834. ggml_element_size(Kcur) * n_embd_head,
  13835. ggml_element_size(Kcur) * n_embd_head * n_head_kv,
  13836. 0);
  13837. cb(Kcur, "Kcur", il);
  13838. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  13839. model.layers[il].attn_k_norm,
  13840. model.layers[il].attn_k_norm_b,
  13841. LLM_NORM, cb, il);
  13842. cb(Kcur, "Kcur", il);
  13843. }
  13844. Qcur = ggml_rope_ext(
  13845. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  13846. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13847. ext_factor, attn_factor, beta_fast, beta_slow
  13848. );
  13849. cb(Qcur, "Qcur", il);
  13850. Kcur = ggml_rope_ext(
  13851. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  13852. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13853. ext_factor, attn_factor, beta_fast, beta_slow
  13854. );
  13855. cb(Kcur, "Kcur", il);
  13856. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13857. model.layers[il].wo, nullptr,
  13858. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13859. if (hparams.swin_norm) {
  13860. cur = llm_build_norm(ctx0, cur, hparams,
  13861. model.layers[il].attn_norm, NULL,
  13862. LLM_NORM_RMS, cb, il);
  13863. }
  13864. }
  13865. if (il == n_layer - 1) {
  13866. // skip computing output for unused tokens
  13867. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13868. n_tokens = n_outputs;
  13869. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13870. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13871. }
  13872. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13873. cb(ffn_inp, "ffn_inp", il);
  13874. // feed-forward network
  13875. if (!hparams.swin_norm) {
  13876. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13877. model.layers[il].ffn_norm, NULL,
  13878. LLM_NORM_RMS, cb, il);
  13879. cb(cur, "ffn_norm", il);
  13880. }
  13881. cur = llm_build_ffn(ctx0, lctx, cur,
  13882. model.layers[il].ffn_up, NULL, NULL,
  13883. model.layers[il].ffn_gate, NULL, NULL,
  13884. model.layers[il].ffn_down, NULL, NULL,
  13885. NULL,
  13886. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13887. cb(cur, "ffn_out", il);
  13888. if (hparams.swin_norm) {
  13889. cur = llm_build_norm(ctx0, cur, hparams,
  13890. model.layers[il].ffn_norm, NULL,
  13891. LLM_NORM_RMS, cb, il);
  13892. cb(cur, "ffn_norm", il);
  13893. }
  13894. cur = ggml_add(ctx0, cur, ffn_inp);
  13895. cb(cur, "ffn_out", il);
  13896. cur = lctx.cvec.apply_to(ctx0, cur, il);
  13897. cb(cur, "l_out", il);
  13898. // input for next layer
  13899. inpL = cur;
  13900. }
  13901. cur = inpL;
  13902. cur = llm_build_norm(ctx0, cur, hparams,
  13903. model.output_norm, NULL,
  13904. LLM_NORM_RMS, cb, -1);
  13905. cb(cur, "result_norm", -1);
  13906. // lm_head
  13907. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13908. cb(cur, "result_output_with_img_logits", -1);
  13909. // TODO: this suppresses the output of image tokens, which is required to enable text-only outputs.
  13910. // Needs to be removed once image outputs are supported.
  13911. int img_token_end_idx = 8196;
  13912. int img_token_start_idx = 4;
  13913. int num_img_tokens = img_token_end_idx - img_token_start_idx;
  13914. // creates 1d tensor of size num_img_tokens and values -FLT_MAX,
  13915. // which ensures that text token values are always at least larger than image token values
  13916. struct ggml_tensor * img_logits = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, num_img_tokens);
  13917. img_logits = ggml_clamp(ctx0, img_logits, -FLT_MAX, -FLT_MAX);
  13918. cb(img_logits, "img_logits", -1);
  13919. cur = ggml_set_1d(ctx0, cur, img_logits, ggml_element_size(cur) * img_token_start_idx);
  13920. cb(cur, "result_output", -1);
  13921. ggml_build_forward_expand(gf, cur);
  13922. return gf;
  13923. }
  13924. ggml_cgraph * build_solar() {
  13925. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13926. // mutable variable, needed during the last layer of the computation to skip unused tokens
  13927. int32_t n_tokens = this->n_tokens;
  13928. const int64_t n_embd_head = hparams.n_embd_head_v;
  13929. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13930. GGML_ASSERT(n_embd_head == hparams.n_rot);
  13931. struct ggml_tensor * cur;
  13932. struct ggml_tensor * inpL;
  13933. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  13934. // inp_pos - contains the positions
  13935. struct ggml_tensor * inp_pos = build_inp_pos();
  13936. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13937. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13938. struct ggml_tensor * bskcn_1;
  13939. struct ggml_tensor * bskcn_2;
  13940. for (int il = 0; il < n_layer; ++il) {
  13941. struct ggml_tensor * inpSA = inpL;
  13942. if (hparams.n_bskcn(0, il)) {
  13943. bskcn_1 = inpSA;
  13944. }
  13945. if (hparams.n_bskcn(1, il)) {
  13946. bskcn_2 = inpSA;
  13947. }
  13948. if (hparams.n_bskcn(2, il)) {
  13949. inpSA = ggml_add(
  13950. ctx0,
  13951. ggml_mul(ctx0, bskcn_1, ggml_view_1d(ctx0, model.layers[il].bskcn_tv, 1, 0)),
  13952. ggml_mul(ctx0, inpSA, ggml_view_1d(ctx0, model.layers[il].bskcn_tv, 1, ggml_element_size(model.layers[il].bskcn_tv))));
  13953. }
  13954. if (hparams.n_bskcn(3, il)) {
  13955. inpSA = ggml_add(
  13956. ctx0,
  13957. ggml_mul(ctx0, bskcn_2, ggml_view_1d(ctx0, model.layers[il].bskcn_tv, 1, 0)),
  13958. ggml_mul(ctx0, inpSA, ggml_view_1d(ctx0, model.layers[il].bskcn_tv, 1, ggml_element_size(model.layers[il].bskcn_tv))));
  13959. }
  13960. // norm
  13961. cur = llm_build_norm(ctx0, inpL, hparams,
  13962. model.layers[il].attn_norm, NULL,
  13963. LLM_NORM_RMS, cb, il);
  13964. cb(cur, "attn_norm", il);
  13965. // self-attention
  13966. {
  13967. // rope freq factors for llama3; may return nullptr for llama2 and other models
  13968. struct ggml_tensor * rope_factors = build_rope_factors(il);
  13969. // compute Q and K and RoPE them
  13970. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  13971. cb(Qcur, "Qcur", il);
  13972. if (model.layers[il].bq) {
  13973. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  13974. cb(Qcur, "Qcur", il);
  13975. }
  13976. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  13977. cb(Kcur, "Kcur", il);
  13978. if (model.layers[il].bk) {
  13979. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  13980. cb(Kcur, "Kcur", il);
  13981. }
  13982. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  13983. cb(Vcur, "Vcur", il);
  13984. if (model.layers[il].bv) {
  13985. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  13986. cb(Vcur, "Vcur", il);
  13987. }
  13988. Qcur = ggml_rope_ext(
  13989. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  13990. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13991. ext_factor, attn_factor, beta_fast, beta_slow
  13992. );
  13993. cb(Qcur, "Qcur", il);
  13994. Kcur = ggml_rope_ext(
  13995. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  13996. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13997. ext_factor, attn_factor, beta_fast, beta_slow
  13998. );
  13999. cb(Kcur, "Kcur", il);
  14000. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  14001. model.layers[il].wo, model.layers[il].bo,
  14002. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  14003. }
  14004. if (il == n_layer - 1) {
  14005. // skip computing output for unused tokens
  14006. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  14007. n_tokens = n_outputs;
  14008. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  14009. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  14010. }
  14011. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  14012. cb(ffn_inp, "ffn_inp", il);
  14013. // feed-forward network
  14014. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  14015. model.layers[il].ffn_norm, NULL,
  14016. LLM_NORM_RMS, cb, il);
  14017. cb(cur, "ffn_norm", il);
  14018. cur = llm_build_ffn(ctx0, lctx, cur,
  14019. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  14020. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  14021. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  14022. NULL,
  14023. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  14024. cb(cur, "ffn_out", il);
  14025. cur = ggml_add(ctx0, cur, ffn_inp);
  14026. cb(cur, "ffn_out", il);
  14027. cur = lctx.cvec.apply_to(ctx0, cur, il);
  14028. cb(cur, "l_out", il);
  14029. // input for next layer
  14030. inpL = cur;
  14031. }
  14032. cur = inpL;
  14033. cur = llm_build_norm(ctx0, cur, hparams,
  14034. model.output_norm, NULL,
  14035. LLM_NORM_RMS, cb, -1);
  14036. cb(cur, "result_norm", -1);
  14037. // lm_head
  14038. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  14039. cb(cur, "result_output", -1);
  14040. ggml_build_forward_expand(gf, cur);
  14041. return gf;
  14042. }
  14043. };
  14044. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  14045. llama_ubatch dummy = {};
  14046. dummy.equal_seqs = true;
  14047. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  14048. struct llm_build_context llm(lctx, dummy, cb, false);
  14049. llm.init();
  14050. struct ggml_cgraph * result = llm.build_defrag(ids);
  14051. llm.free();
  14052. return result;
  14053. }
  14054. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  14055. llama_ubatch dummy = {};
  14056. dummy.equal_seqs = true;
  14057. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  14058. struct llm_build_context llm(lctx, dummy, cb, false);
  14059. llm.init();
  14060. struct ggml_cgraph * result = llm.build_k_shift();
  14061. llm.free();
  14062. return result;
  14063. }
  14064. static struct ggml_cgraph * llama_build_graph(
  14065. llama_context & lctx,
  14066. const llama_ubatch & batch,
  14067. bool worst_case) {
  14068. const auto & model = lctx.model;
  14069. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  14070. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  14071. if (il >= 0) {
  14072. ggml_format_name(cur, "%s-%d", name, il);
  14073. } else {
  14074. ggml_set_name(cur, name);
  14075. }
  14076. if (!lctx.cparams.offload_kqv) {
  14077. if (strcmp(name, "kqv_merged_cont") == 0) {
  14078. // all nodes between the KV store and the attention output are run on the CPU
  14079. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, lctx.backend_cpu);
  14080. }
  14081. }
  14082. // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
  14083. // FIXME: fix in ggml_backend_sched
  14084. const bool full_offload = lctx.model.n_gpu_layers > (int)lctx.model.hparams.n_layer;
  14085. if (batch.n_tokens < 32 || full_offload) {
  14086. if (il != -1 && strcmp(name, "norm") == 0) {
  14087. for (auto * backend : lctx.backends) {
  14088. if (ggml_backend_supports_buft(backend, lctx.model.buft_layer[il].buft) &&
  14089. (ggml_backend_supports_op(backend, cur) || ggml_backend_offload_op(backend, cur))) {
  14090. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, backend);
  14091. break;
  14092. }
  14093. }
  14094. }
  14095. }
  14096. };
  14097. struct ggml_cgraph * result = NULL;
  14098. struct llm_build_context llm(lctx, batch, cb, worst_case);
  14099. llm.init();
  14100. switch (model.arch) {
  14101. case LLM_ARCH_LLAMA:
  14102. case LLM_ARCH_GRANITE:
  14103. case LLM_ARCH_GRANITE_MOE:
  14104. {
  14105. result = llm.build_llama();
  14106. } break;
  14107. case LLM_ARCH_MLLAMA:
  14108. {
  14109. result = llm.build_mllama();
  14110. } break;
  14111. case LLM_ARCH_BAICHUAN:
  14112. {
  14113. result = llm.build_baichuan();
  14114. } break;
  14115. case LLM_ARCH_FALCON:
  14116. {
  14117. result = llm.build_falcon();
  14118. } break;
  14119. case LLM_ARCH_GROK:
  14120. {
  14121. result = llm.build_grok();
  14122. } break;
  14123. case LLM_ARCH_STARCODER:
  14124. {
  14125. result = llm.build_starcoder();
  14126. } break;
  14127. case LLM_ARCH_REFACT:
  14128. {
  14129. result = llm.build_refact();
  14130. } break;
  14131. case LLM_ARCH_BERT:
  14132. case LLM_ARCH_JINA_BERT_V2:
  14133. case LLM_ARCH_NOMIC_BERT:
  14134. {
  14135. result = llm.build_bert();
  14136. } break;
  14137. case LLM_ARCH_BLOOM:
  14138. {
  14139. result = llm.build_bloom();
  14140. } break;
  14141. case LLM_ARCH_MPT:
  14142. {
  14143. result = llm.build_mpt();
  14144. } break;
  14145. case LLM_ARCH_STABLELM:
  14146. {
  14147. result = llm.build_stablelm();
  14148. } break;
  14149. case LLM_ARCH_QWEN:
  14150. {
  14151. result = llm.build_qwen();
  14152. } break;
  14153. case LLM_ARCH_QWEN2:
  14154. {
  14155. result = llm.build_qwen2();
  14156. } break;
  14157. case LLM_ARCH_QWEN2MOE:
  14158. {
  14159. result = llm.build_qwen2moe();
  14160. } break;
  14161. case LLM_ARCH_PHI2:
  14162. {
  14163. result = llm.build_phi2();
  14164. } break;
  14165. case LLM_ARCH_PHI3:
  14166. {
  14167. result = llm.build_phi3();
  14168. } break;
  14169. case LLM_ARCH_PLAMO:
  14170. {
  14171. result = llm.build_plamo();
  14172. } break;
  14173. case LLM_ARCH_GPT2:
  14174. {
  14175. result = llm.build_gpt2();
  14176. } break;
  14177. case LLM_ARCH_CODESHELL:
  14178. {
  14179. result = llm.build_codeshell();
  14180. } break;
  14181. case LLM_ARCH_ORION:
  14182. {
  14183. result = llm.build_orion();
  14184. } break;
  14185. case LLM_ARCH_INTERNLM2:
  14186. {
  14187. result = llm.build_internlm2();
  14188. } break;
  14189. case LLM_ARCH_MINICPM:
  14190. {
  14191. result = llm.build_minicpm();
  14192. } break;
  14193. case LLM_ARCH_MINICPM3:
  14194. {
  14195. result = llm.build_minicpm3();
  14196. } break;
  14197. case LLM_ARCH_GEMMA:
  14198. {
  14199. result = llm.build_gemma();
  14200. } break;
  14201. case LLM_ARCH_GEMMA2:
  14202. {
  14203. result = llm.build_gemma2();
  14204. } break;
  14205. case LLM_ARCH_STARCODER2:
  14206. {
  14207. result = llm.build_starcoder2();
  14208. } break;
  14209. case LLM_ARCH_MAMBA:
  14210. {
  14211. result = llm.build_mamba();
  14212. } break;
  14213. case LLM_ARCH_XVERSE:
  14214. {
  14215. result = llm.build_xverse();
  14216. } break;
  14217. case LLM_ARCH_COMMAND_R:
  14218. {
  14219. result = llm.build_command_r();
  14220. } break;
  14221. case LLM_ARCH_DBRX:
  14222. {
  14223. result = llm.build_dbrx();
  14224. } break;
  14225. case LLM_ARCH_OLMO:
  14226. {
  14227. result = llm.build_olmo();
  14228. } break;
  14229. case LLM_ARCH_OLMOE:
  14230. {
  14231. result = llm.build_olmoe();
  14232. } break;
  14233. case LLM_ARCH_OPENELM:
  14234. {
  14235. result = llm.build_openelm();
  14236. } break;
  14237. case LLM_ARCH_GPTNEOX:
  14238. {
  14239. result = llm.build_gptneox();
  14240. } break;
  14241. case LLM_ARCH_ARCTIC:
  14242. {
  14243. result = llm.build_arctic();
  14244. } break;
  14245. case LLM_ARCH_DEEPSEEK2:
  14246. {
  14247. result = llm.build_deepseek2();
  14248. } break;
  14249. case LLM_ARCH_CHATGLM:
  14250. {
  14251. result = llm.build_chatglm();
  14252. } break;
  14253. case LLM_ARCH_BITNET:
  14254. {
  14255. result = llm.build_bitnet();
  14256. } break;
  14257. case LLM_ARCH_T5:
  14258. {
  14259. if (lctx.is_encoding) {
  14260. result = llm.build_t5_encoder();
  14261. } else {
  14262. result = llm.build_t5_decoder();
  14263. }
  14264. } break;
  14265. case LLM_ARCH_T5ENCODER:
  14266. {
  14267. result = llm.build_t5_encoder();
  14268. } break;
  14269. case LLM_ARCH_JAIS:
  14270. {
  14271. result = llm.build_jais();
  14272. } break;
  14273. case LLM_ARCH_NEMOTRON:
  14274. {
  14275. result = llm.build_nemotron();
  14276. } break;
  14277. case LLM_ARCH_EXAONE:
  14278. {
  14279. result = llm.build_exaone();
  14280. } break;
  14281. case LLM_ARCH_RWKV6:
  14282. {
  14283. result = llm.build_rwkv6();
  14284. } break;
  14285. case LLM_ARCH_CHAMELEON:
  14286. {
  14287. result = llm.build_chameleon();
  14288. } break;
  14289. case LLM_ARCH_SOLAR:
  14290. {
  14291. result = llm.build_solar();
  14292. } break;
  14293. default:
  14294. GGML_ABORT("fatal error");
  14295. }
  14296. // add on pooling layer
  14297. if (lctx.cparams.embeddings) {
  14298. result = llm.append_pooling(result);
  14299. }
  14300. llm.free();
  14301. return result;
  14302. }
  14303. static void llama_set_k_shift(llama_context & lctx) {
  14304. const int64_t kv_size = lctx.kv_self.size;
  14305. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  14306. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  14307. for (int i = 0; i < kv_size; ++i) {
  14308. data[i] = lctx.kv_self.cells[i].delta;
  14309. }
  14310. }
  14311. static void llama_set_s_copy(llama_context & lctx) {
  14312. const int64_t kv_size = lctx.kv_self.size;
  14313. assert(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  14314. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  14315. for (int i = 0; i < kv_size; ++i) {
  14316. data[i] = lctx.kv_self.cells[i].src;
  14317. }
  14318. }
  14319. static int32_t llama_relative_position_bucket(llama_pos x, llama_pos y, uint64_t n_buckets, bool bidirectional) {
  14320. // TODO move to hparams if a T5 variant appears that uses a different value
  14321. const int64_t max_distance = 128;
  14322. if (bidirectional) {
  14323. n_buckets >>= 1;
  14324. }
  14325. const int64_t max_exact = n_buckets >> 1;
  14326. int32_t relative_position = x - y;
  14327. int32_t relative_bucket = 0;
  14328. if (bidirectional) {
  14329. relative_bucket += (relative_position > 0) * n_buckets;
  14330. relative_position = abs(relative_position);
  14331. } else {
  14332. relative_position = -std::min<int32_t>(relative_position, 0);
  14333. }
  14334. 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));
  14335. relative_position_if_large = std::min<int32_t>(relative_position_if_large, n_buckets - 1);
  14336. relative_bucket += (relative_position < max_exact ? relative_position : relative_position_if_large);
  14337. return relative_bucket;
  14338. }
  14339. static void llama_set_inputs(llama_context & lctx, const llama_ubatch & batch) {
  14340. //
  14341. // set input data
  14342. //
  14343. const auto & hparams = lctx.model.hparams;
  14344. const auto & cparams = lctx.cparams;
  14345. const auto & kv_self = lctx.kv_self;
  14346. if (batch.token) {
  14347. const int64_t n_tokens = batch.n_tokens;
  14348. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  14349. }
  14350. if (batch.embd) {
  14351. const int64_t n_embd = hparams.n_embd;
  14352. const int64_t n_tokens = batch.n_tokens;
  14353. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  14354. }
  14355. if (batch.pos && lctx.inp_pos) {
  14356. const int64_t n_tokens = batch.n_tokens;
  14357. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  14358. }
  14359. // TODO (jmorganca): this might copy a lot of data on every request of a
  14360. // single generation even though it doesn't change, so we should
  14361. // find a way to not set this more than one time per image
  14362. if (lctx.inp_cross_attn_state &&
  14363. lctx.inp_cross_attn_state->buffer) {
  14364. ggml_backend_tensor_set(lctx.inp_cross_attn_state, lctx.cross_attn_state, 0, hparams.n_embd * 1601 * 4 * ggml_element_size(lctx.inp_cross_attn_state));
  14365. }
  14366. if (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE) {
  14367. GGML_ASSERT(lctx.inp_out_ids && "every model that can must skip unused outputs");
  14368. const int64_t n_tokens = batch.n_tokens;
  14369. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_out_ids->buffer));
  14370. int32_t * data = (int32_t *) lctx.inp_out_ids->data;
  14371. if (lctx.n_outputs == n_tokens) {
  14372. for (int i = 0; i < n_tokens; ++i) {
  14373. data[i] = i;
  14374. }
  14375. } else if (batch.output) {
  14376. int32_t n_outputs = 0;
  14377. for (int i = 0; i < n_tokens; ++i) {
  14378. if (batch.output[i]) {
  14379. data[n_outputs++] = i;
  14380. }
  14381. }
  14382. // the graph needs to have been passed the correct number of outputs
  14383. GGML_ASSERT(lctx.n_outputs == n_outputs);
  14384. } else if (lctx.n_outputs == 1) {
  14385. // only keep last output
  14386. data[0] = n_tokens - 1;
  14387. } else {
  14388. GGML_ASSERT(lctx.n_outputs == 0);
  14389. }
  14390. }
  14391. GGML_ASSERT(
  14392. // (!a || b) is a logical implication (a -> b)
  14393. // !hparams.causal_attn -> !cparams.causal_attn
  14394. (hparams.causal_attn || !cparams.causal_attn) &&
  14395. "causal attention is not supported by this model"
  14396. );
  14397. if (lctx.inp_KQ_mask || lctx.inp_KQ_mask_swa) {
  14398. // NOTE: hparams.causal_attn indicates the model is capable of generation and uses the kv cache.
  14399. if (cparams.causal_attn && !lctx.is_encoding) {
  14400. const int64_t n_kv = kv_self.n;
  14401. const int64_t n_tokens = batch.n_tokens;
  14402. const int64_t n_seq_tokens = batch.n_seq_tokens;
  14403. const int64_t n_seqs = batch.n_seqs;
  14404. float * data = nullptr;
  14405. float * data_swa = nullptr;
  14406. if (lctx.inp_KQ_mask) {
  14407. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  14408. data = (float *) lctx.inp_KQ_mask->data;
  14409. }
  14410. if (lctx.inp_KQ_mask_swa) {
  14411. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask_swa->buffer));
  14412. data_swa = (float *) lctx.inp_KQ_mask_swa->data;
  14413. }
  14414. // For causal attention, use only the previous KV cells
  14415. // of the correct sequence for each token of the batch.
  14416. // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
  14417. for (int h = 0; h < 1; ++h) {
  14418. for (int s = 0; s < n_seqs; ++s) {
  14419. const llama_seq_id seq_id = batch.seq_id[s][0];
  14420. for (int j = 0; j < n_seq_tokens; ++j) {
  14421. const llama_pos pos = batch.pos[s*n_seq_tokens + j];
  14422. for (int i = 0; i < n_kv; ++i) {
  14423. float f;
  14424. if (!kv_self.cells[i].has_seq_id(seq_id) || kv_self.cells[i].pos > pos) {
  14425. f = -INFINITY;
  14426. } else {
  14427. if (hparams.use_alibi) {
  14428. f = -std::abs(kv_self.cells[i].pos - pos);
  14429. } else {
  14430. f = 0.0f;
  14431. }
  14432. }
  14433. if (data) {
  14434. data[h*(n_kv*n_tokens) + s*(n_kv*n_seq_tokens) + j*n_kv + i] = f;
  14435. }
  14436. // may need to cut off old tokens for sliding window
  14437. if (data_swa) {
  14438. if (pos - kv_self.cells[i].pos >= (int32_t)hparams.n_swa) {
  14439. f = -INFINITY;
  14440. }
  14441. data_swa[h*(n_kv*n_tokens) + s*(n_kv*n_seq_tokens) + j*n_kv + i] = f;
  14442. }
  14443. }
  14444. }
  14445. }
  14446. if (data) {
  14447. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  14448. for (int j = 0; j < n_kv; ++j) {
  14449. data[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
  14450. }
  14451. }
  14452. }
  14453. if (data_swa) {
  14454. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  14455. for (int j = 0; j < n_kv; ++j) {
  14456. data_swa[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
  14457. }
  14458. }
  14459. }
  14460. }
  14461. } else {
  14462. const int64_t n_tokens = batch.n_tokens;
  14463. const int64_t n_seq_tokens = batch.n_seq_tokens;
  14464. const int64_t n_seqs = batch.n_seqs;
  14465. // when using kv cache, the mask needs to match the kv cache size
  14466. const int64_t n_stride = hparams.causal_attn && !lctx.is_encoding ? kv_self.n : n_tokens;
  14467. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  14468. float * data = (float *) lctx.inp_KQ_mask->data;
  14469. for (int h = 0; h < 1; ++h) {
  14470. for (int s1 = 0; s1 < n_seqs; ++s1) {
  14471. const llama_seq_id seq_id = batch.seq_id[s1][0];
  14472. for (int j = 0; j < n_seq_tokens; ++j) {
  14473. const int32_t tj = s1*n_seq_tokens + j;
  14474. for (int s0 = 0; s0 < n_seqs; ++s0) {
  14475. for (int i = 0; i < n_seq_tokens; ++i) {
  14476. const int32_t ti = s0*n_seq_tokens + i;
  14477. float f = -INFINITY;
  14478. for (int s = 0; s < batch.n_seq_id[s0]; ++s) {
  14479. if (batch.seq_id[s0][s] == seq_id) {
  14480. if (hparams.use_alibi) {
  14481. f = -std::abs(batch.pos[ti] - batch.pos[tj]);
  14482. } else {
  14483. f = 0.0f;
  14484. }
  14485. break;
  14486. }
  14487. }
  14488. data[h*(n_tokens*n_tokens) + tj*n_stride + ti] = f;
  14489. }
  14490. }
  14491. for (int i = n_tokens; i < n_stride; ++i) {
  14492. data[h*(n_tokens*n_tokens) + tj*n_stride + i] = -INFINITY;
  14493. }
  14494. }
  14495. }
  14496. }
  14497. }
  14498. }
  14499. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  14500. const int64_t n_tokens = batch.n_tokens;
  14501. const int64_t n_seq_tokens = batch.n_seq_tokens;
  14502. const int64_t n_seqs = batch.n_seqs;
  14503. GGML_ASSERT(lctx.inp_mean);
  14504. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  14505. float * data = (float *) lctx.inp_mean->data;
  14506. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  14507. std::vector<uint64_t> sum(n_tokens, 0);
  14508. for (int s = 0; s < n_seqs; ++s) {
  14509. const llama_seq_id seq_id = batch.seq_id[s][0];
  14510. // TODO: adapt limits to n_seqs when batch.equal_seqs is true
  14511. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
  14512. sum[seq_id] += batch.n_seq_tokens;
  14513. }
  14514. std::vector<float> div(n_tokens, 0.0f);
  14515. for (int i = 0; i < n_tokens; ++i) {
  14516. const uint64_t s = sum[i];
  14517. if (s > 0) {
  14518. div[i] = 1.0f/float(s);
  14519. }
  14520. }
  14521. for (int s = 0; s < n_seqs; ++s) {
  14522. const llama_seq_id seq_id = batch.seq_id[s][0];
  14523. for (int i = 0; i < n_seq_tokens; ++i) {
  14524. data[seq_id*n_tokens + s*n_seq_tokens + i] = div[seq_id];
  14525. }
  14526. }
  14527. }
  14528. if (cparams.embeddings && (
  14529. cparams.pooling_type == LLAMA_POOLING_TYPE_CLS ||
  14530. cparams.pooling_type == LLAMA_POOLING_TYPE_RANK)) {
  14531. const int64_t n_tokens = batch.n_tokens;
  14532. const int64_t n_seq_tokens = batch.n_seq_tokens;
  14533. const int64_t n_seqs = batch.n_seqs;
  14534. GGML_ASSERT(lctx.inp_cls);
  14535. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  14536. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  14537. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  14538. for (int s = 0; s < n_seqs; ++s) {
  14539. const llama_seq_id seq_id = batch.seq_id[s][0];
  14540. // TODO: adapt limits to n_seqs when batch.equal_seqs is true
  14541. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS or RANK");
  14542. for (int i = 0; i < n_seq_tokens; ++i) {
  14543. const llama_pos pos = batch.pos[s*n_seq_tokens + i];
  14544. if (pos == 0) {
  14545. data[seq_id] = s*n_seq_tokens + i;
  14546. }
  14547. }
  14548. }
  14549. }
  14550. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_LAST) {
  14551. const int64_t n_tokens = batch.n_tokens;
  14552. const int64_t n_seq_tokens = batch.n_seq_tokens;
  14553. const int64_t n_seqs = batch.n_seqs;
  14554. GGML_ASSERT(lctx.inp_cls);
  14555. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  14556. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  14557. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  14558. std::vector<int> last_pos(n_tokens, -1);
  14559. std::vector<int> last_row(n_tokens, -1);
  14560. for (int s = 0; s < n_seqs; ++s) {
  14561. const llama_seq_id seq_id = batch.seq_id[s][0];
  14562. // TODO: adapt limits to n_seqs when batch.equal_seqs is true
  14563. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == LAST");
  14564. for (int i = 0; i < n_seq_tokens; ++i) {
  14565. const llama_pos pos = batch.pos[s*n_seq_tokens + i];
  14566. if (pos >= last_pos[seq_id]) {
  14567. last_pos[seq_id] = pos;
  14568. last_row[seq_id] = s*n_seq_tokens + i;
  14569. }
  14570. }
  14571. }
  14572. for (int i = 0; i < n_tokens; ++i) {
  14573. if (last_row[i] >= 0) {
  14574. data[i] = last_row[i];
  14575. }
  14576. }
  14577. }
  14578. if (kv_self.recurrent) {
  14579. const int64_t n_kv = kv_self.n;
  14580. if (lctx.inp_s_mask) {
  14581. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_mask->buffer));
  14582. float * data = (float *) lctx.inp_s_mask->data;
  14583. // clear unused states
  14584. for (int i = 0; i < n_kv; ++i) {
  14585. const uint32_t cell_id = i + kv_self.head;
  14586. llama_kv_cell & kv_cell = lctx.kv_self.cells[cell_id];
  14587. data[i] = (float) (kv_cell.src >= 0);
  14588. // only clear once
  14589. if (kv_cell.src < 0) {
  14590. kv_cell.src = cell_id;
  14591. }
  14592. }
  14593. }
  14594. if (lctx.inp_s_copy) {
  14595. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  14596. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  14597. // assuming copy destinations ALWAYS happen ONLY on the cells between head and head+n
  14598. for (uint32_t i = 0; i < n_kv; ++i) {
  14599. const uint32_t cell_id = i + kv_self.head;
  14600. llama_kv_cell & kv_cell = lctx.kv_self.cells[cell_id];
  14601. // prevent out-of-bound sources
  14602. if (kv_cell.src < 0 || (uint32_t) kv_cell.src >= kv_self.size) {
  14603. kv_cell.src = cell_id;
  14604. }
  14605. data[i] = kv_cell.src;
  14606. // ensure copy only happens once
  14607. if (kv_cell.src != (int32_t) cell_id) {
  14608. kv_cell.src = cell_id;
  14609. }
  14610. }
  14611. }
  14612. }
  14613. if (lctx.inp_pos_bucket) {
  14614. const int64_t n_tokens = batch.n_tokens;
  14615. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_pos_bucket->buffer));
  14616. GGML_ASSERT(!batch.equal_seqs); // TODO: use batch.n_seqs instead of failing
  14617. int32_t * data = (int32_t *) lctx.inp_pos_bucket->data;
  14618. if (!lctx.is_encoding) {
  14619. const int64_t n_kv = kv_self.n;
  14620. for (int h = 0; h < 1; ++h) {
  14621. for (int j = 0; j < n_tokens; ++j) {
  14622. for (int i = 0; i < n_kv; ++i) {
  14623. data[h*(n_kv*n_tokens) + j*n_kv + i] = llama_relative_position_bucket(lctx.kv_self.cells[i].pos, batch.pos[j], hparams.n_rel_attn_bkts, lctx.is_encoding);
  14624. }
  14625. }
  14626. }
  14627. } else {
  14628. for (int h = 0; h < 1; ++h) {
  14629. for (int j = 0; j < n_tokens; ++j) {
  14630. for (int i = 0; i < n_tokens; ++i) {
  14631. data[h*(n_tokens*n_tokens) + j*n_tokens + i] = llama_relative_position_bucket(batch.pos[i], batch.pos[j], hparams.n_rel_attn_bkts, lctx.is_encoding);
  14632. }
  14633. }
  14634. }
  14635. }
  14636. }
  14637. if (!lctx.is_encoding && lctx.inp_embd_enc) {
  14638. assert(lctx.inp_embd_enc->type == GGML_TYPE_F32);
  14639. assert((size_t) ggml_nelements(lctx.inp_embd_enc) == lctx.embd_enc.size());
  14640. ggml_backend_tensor_set(lctx.inp_embd_enc, lctx.embd_enc.data(), 0, ggml_nbytes(lctx.inp_embd_enc));
  14641. }
  14642. if (!lctx.is_encoding && lctx.inp_KQ_mask_cross) {
  14643. const int64_t n_output_enc = lctx.embd_enc.size() / hparams.n_embd;
  14644. const int64_t n_tokens = batch.n_tokens;
  14645. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask_cross->buffer));
  14646. GGML_ASSERT(!batch.equal_seqs); // TODO: use batch.n_seqs instead of failing
  14647. float * data = (float *) lctx.inp_KQ_mask_cross->data;
  14648. for (int h = 0; h < 1; ++h) {
  14649. for (int j = 0; j < n_tokens; ++j) {
  14650. for (int i = 0; i < n_output_enc; ++i) {
  14651. float f = -INFINITY;
  14652. for (int s = 0; s < batch.n_seq_id[j]; ++s) {
  14653. const llama_seq_id seq_id = batch.seq_id[j][s];
  14654. if (lctx.seq_ids_enc[i].find(seq_id) != lctx.seq_ids_enc[i].end()) {
  14655. f = 0.0f;
  14656. }
  14657. }
  14658. data[h*(n_output_enc*n_tokens) + j*n_output_enc + i] = f;
  14659. }
  14660. }
  14661. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  14662. for (int j = 0; j < n_output_enc; ++j) {
  14663. data[h*(n_output_enc*n_tokens) + i*n_output_enc + j] = -INFINITY;
  14664. }
  14665. }
  14666. }
  14667. }
  14668. }
  14669. // Make sure enough space is available for outputs.
  14670. // Returns max number of outputs for which space was reserved.
  14671. static size_t llama_output_reserve(llama_context & lctx, size_t n_outputs) {
  14672. const auto & cparams = lctx.cparams;
  14673. const auto & hparams = lctx.model.hparams;
  14674. const size_t n_outputs_max = std::max(n_outputs, (size_t) cparams.n_seq_max);
  14675. const auto n_batch = cparams.n_batch;
  14676. const auto n_vocab = hparams.n_vocab;
  14677. const auto n_embd = hparams.n_embd;
  14678. // TODO: use a per-batch flag for logits presence instead
  14679. const bool has_logits = cparams.causal_attn;
  14680. const bool has_embd = cparams.embeddings && (cparams.pooling_type == LLAMA_POOLING_TYPE_NONE);
  14681. const size_t logits_size = has_logits ? n_vocab*n_outputs_max : 0;
  14682. const size_t embd_size = has_embd ? n_embd*n_outputs_max : 0;
  14683. if (lctx.output_ids.empty()) {
  14684. // init, never resized afterwards
  14685. lctx.output_ids.resize(n_batch);
  14686. }
  14687. const size_t prev_size = lctx.buf_output ? ggml_backend_buffer_get_size(lctx.buf_output) : 0;
  14688. const size_t new_size = (logits_size + embd_size) * sizeof(float);
  14689. // alloc only when more than the current capacity is required
  14690. // TODO: also consider shrinking the buffer
  14691. if (!lctx.buf_output || prev_size < new_size) {
  14692. if (lctx.buf_output) {
  14693. #ifndef NDEBUG
  14694. // This doesn't happen often, but may be annoying in some cases (like the HellaSwag benchmark)
  14695. 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);
  14696. #endif
  14697. ggml_backend_buffer_free(lctx.buf_output);
  14698. lctx.buf_output = nullptr;
  14699. lctx.logits = nullptr;
  14700. lctx.embd = nullptr;
  14701. }
  14702. lctx.buf_output = ggml_backend_buft_alloc_buffer(llama_default_buffer_type_cpu(true), new_size);
  14703. if (lctx.buf_output == nullptr) {
  14704. LLAMA_LOG_ERROR("%s: failed to allocate output buffer of size %.2f MiB\n", __func__, new_size / (1024.0 * 1024.0));
  14705. return 0;
  14706. }
  14707. }
  14708. float * output_base = (float *) ggml_backend_buffer_get_base(lctx.buf_output);
  14709. lctx.logits = has_logits ? output_base : nullptr;
  14710. lctx.embd = has_embd ? output_base + logits_size : nullptr;
  14711. lctx.output_size = n_outputs_max;
  14712. lctx.logits_size = logits_size;
  14713. lctx.embd_size = embd_size;
  14714. // set all ids as invalid (negative)
  14715. std::fill(lctx.output_ids.begin(), lctx.output_ids.end(), -1);
  14716. ggml_backend_buffer_clear(lctx.buf_output, 0);
  14717. lctx.n_outputs = 0;
  14718. return n_outputs_max;
  14719. }
  14720. // make the outputs have the same order they had in the user-provided batch
  14721. static void llama_output_reorder(struct llama_context * ctx) {
  14722. std::vector<size_t> & out_ids = ctx->sbatch.out_ids;
  14723. if (!out_ids.empty()) {
  14724. uint32_t n_vocab = ctx->model.hparams.n_vocab;
  14725. uint32_t n_embd = ctx->model.hparams.n_embd;
  14726. int32_t n_outputs = ctx->n_outputs;
  14727. GGML_ASSERT((size_t) n_outputs == out_ids.size());
  14728. // TODO: is there something more efficient which also minimizes swaps?
  14729. // selection sort, to minimize swaps (from https://en.wikipedia.org/wiki/Selection_sort)
  14730. for (int32_t i = 0; i < n_outputs - 1; ++i) {
  14731. int32_t j_min = i;
  14732. for (int32_t j = i + 1; j < n_outputs; ++j) {
  14733. if (out_ids[j] < out_ids[j_min]) {
  14734. j_min = j;
  14735. }
  14736. }
  14737. if (j_min == i) { continue; }
  14738. std::swap(out_ids[i], out_ids[j_min]);
  14739. if (ctx->logits_size > 0) {
  14740. for (uint32_t k = 0; k < n_vocab; k++) {
  14741. std::swap(ctx->logits[i*n_vocab + k], ctx->logits[j_min*n_vocab + k]);
  14742. }
  14743. }
  14744. if (ctx->embd_size > 0) {
  14745. for (uint32_t k = 0; k < n_embd; k++) {
  14746. std::swap(ctx->embd[i*n_embd + k], ctx->embd[j_min*n_embd + k]);
  14747. }
  14748. }
  14749. }
  14750. std::fill(ctx->output_ids.begin(), ctx->output_ids.end(), -1);
  14751. for (int32_t i = 0; i < n_outputs; ++i) {
  14752. ctx->output_ids[out_ids[i]] = i;
  14753. }
  14754. out_ids.clear();
  14755. }
  14756. }
  14757. static void llama_graph_compute(
  14758. llama_context & lctx,
  14759. ggml_cgraph * gf,
  14760. int n_threads,
  14761. ggml_threadpool * threadpool) {
  14762. if (lctx.backend_cpu != nullptr) {
  14763. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  14764. ggml_backend_cpu_set_threadpool(lctx.backend_cpu, threadpool);
  14765. ggml_backend_cpu_set_abort_callback(lctx.backend_cpu, lctx.abort_callback, lctx.abort_callback_data);
  14766. }
  14767. #ifdef GGML_USE_BLAS
  14768. if (lctx.backend_blas != nullptr) {
  14769. ggml_backend_blas_set_n_threads(lctx.backend_blas, n_threads);
  14770. }
  14771. #endif
  14772. ggml_backend_sched_graph_compute_async(lctx.sched, gf);
  14773. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  14774. }
  14775. // decode a batch of tokens by evaluating the transformer
  14776. //
  14777. // - lctx: llama context
  14778. // - batch: batch to evaluate
  14779. //
  14780. // return 0 on success
  14781. // return positive int on warning
  14782. // return negative int on error
  14783. //
  14784. static int llama_decode_internal(
  14785. llama_context & lctx,
  14786. llama_batch batch_all) { // TODO: rename back to batch
  14787. lctx.is_encoding = false;
  14788. const uint32_t n_tokens_all = batch_all.n_tokens;
  14789. if (n_tokens_all == 0) {
  14790. LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__);
  14791. return -1;
  14792. }
  14793. const auto & model = lctx.model;
  14794. const auto & hparams = model.hparams;
  14795. const auto & cparams = lctx.cparams;
  14796. GGML_ASSERT((!batch_all.token && batch_all.embd) || (batch_all.token && !batch_all.embd)); // NOLINT
  14797. if (batch_all.token) {
  14798. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  14799. if (batch_all.token[i] < 0 || (uint32_t)batch_all.token[i] >= model.vocab.n_vocab) {
  14800. LLAMA_LOG_ERROR("%s: invalid token[%d] = %d\n", __func__, i, batch_all.token[i]);
  14801. return -1;
  14802. }
  14803. }
  14804. }
  14805. GGML_ASSERT(n_tokens_all <= cparams.n_batch);
  14806. GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
  14807. if (lctx.t_compute_start_us == 0) {
  14808. lctx.t_compute_start_us = ggml_time_us();
  14809. }
  14810. lctx.n_queued_tokens += n_tokens_all;
  14811. auto & kv_self = lctx.kv_self;
  14812. const int64_t n_embd = hparams.n_embd;
  14813. const int64_t n_vocab = hparams.n_vocab;
  14814. uint32_t n_outputs = 0;
  14815. uint32_t n_outputs_prev = 0;
  14816. const auto n_ubatch = cparams.n_ubatch;
  14817. // this indicates we are doing pooled embedding, so we ignore batch.logits and output all tokens
  14818. const bool embd_pooled = cparams.embeddings && cparams.pooling_type != LLAMA_POOLING_TYPE_NONE;
  14819. lctx.embd_seq.clear();
  14820. // count outputs
  14821. if (batch_all.logits && !embd_pooled) {
  14822. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  14823. n_outputs += batch_all.logits[i] != 0;
  14824. }
  14825. } else if (lctx.logits_all || embd_pooled) {
  14826. n_outputs = n_tokens_all;
  14827. } else {
  14828. // keep last output only
  14829. n_outputs = 1;
  14830. }
  14831. lctx.sbatch.from_batch(batch_all, n_embd,
  14832. /* simple_split */ !kv_self.recurrent,
  14833. /* logits_all */ n_outputs == n_tokens_all);
  14834. // reserve output buffer
  14835. if (llama_output_reserve(lctx, n_outputs) < n_outputs) {
  14836. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_outputs);
  14837. return -2;
  14838. };
  14839. while (lctx.sbatch.n_tokens > 0) {
  14840. llama_ubatch ubatch;
  14841. if (kv_self.recurrent) {
  14842. if (embd_pooled) {
  14843. // Pooled embeddings cannot be split across ubatches (yet)
  14844. ubatch = lctx.sbatch.split_seq(n_ubatch);
  14845. } else {
  14846. // recurrent model architectures are easier to implement
  14847. // with equal-length sequences
  14848. ubatch = lctx.sbatch.split_equal(n_ubatch);
  14849. }
  14850. } else {
  14851. ubatch = lctx.sbatch.split_simple(n_ubatch);
  14852. }
  14853. const uint32_t n_tokens = ubatch.n_tokens;
  14854. // count the outputs in this u_batch
  14855. {
  14856. int32_t n_outputs_new = 0;
  14857. if (n_outputs == n_tokens_all) {
  14858. n_outputs_new = n_tokens;
  14859. } else {
  14860. GGML_ASSERT(ubatch.output);
  14861. for (uint32_t i = 0; i < n_tokens; i++) {
  14862. n_outputs_new += (int32_t) (ubatch.output[i] != 0);
  14863. }
  14864. }
  14865. // needs to happen before the graph is built
  14866. lctx.n_outputs = n_outputs_new;
  14867. }
  14868. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  14869. ggml_threadpool_t threadpool = n_tokens == 1 ? lctx.threadpool : lctx.threadpool_batch;
  14870. GGML_ASSERT(n_threads > 0);
  14871. // non-causal masks do not use the KV cache
  14872. if (hparams.causal_attn) {
  14873. llama_kv_cache_update(&lctx);
  14874. // if we have enough unused cells before the current head ->
  14875. // better to start searching from the beginning of the cache, hoping to fill it
  14876. if (kv_self.head > kv_self.used + 2*n_tokens) {
  14877. kv_self.head = 0;
  14878. }
  14879. if (!llama_kv_cache_find_slot(kv_self, ubatch)) {
  14880. return 1;
  14881. }
  14882. if (!kv_self.recurrent) {
  14883. // a heuristic, to avoid attending the full cache if it is not yet utilized
  14884. // after enough generations, the benefit from this heuristic disappears
  14885. // if we start defragmenting the cache, the benefit from this will be more important
  14886. const uint32_t pad = llama_kv_cache_get_padding(cparams);
  14887. kv_self.n = std::min(kv_self.size, std::max(pad, GGML_PAD(llama_kv_cache_cell_max(kv_self), pad)));
  14888. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  14889. }
  14890. }
  14891. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  14892. ggml_backend_sched_reset(lctx.sched);
  14893. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  14894. ggml_cgraph * gf = llama_build_graph(lctx, ubatch, false);
  14895. // the output is always the last tensor in the graph
  14896. struct ggml_tensor * res = ggml_graph_node(gf, -1);
  14897. struct ggml_tensor * embd = ggml_graph_node(gf, -2);
  14898. if (lctx.n_outputs == 0) {
  14899. // no output
  14900. res = nullptr;
  14901. embd = nullptr;
  14902. }
  14903. if (cparams.embeddings) {
  14904. for (int i = ggml_graph_n_nodes(gf) - 1; i >= 0; --i) {
  14905. embd = ggml_graph_node(gf, i);
  14906. if (strcmp(ggml_graph_node(gf, i)->name, "result_embd_pooled") == 0) {
  14907. break;
  14908. }
  14909. }
  14910. } else {
  14911. embd = nullptr; // do not extract embeddings when not needed
  14912. GGML_ASSERT(strcmp(res->name, "result_output") == 0 && "missing result_output tensor");
  14913. }
  14914. if (!cparams.causal_attn) {
  14915. res = nullptr; // do not extract logits when not needed
  14916. }
  14917. // 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);
  14918. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  14919. llama_set_inputs(lctx, ubatch);
  14920. // TODO: replace with something better to find out if its
  14921. // our first actual pass
  14922. lctx.cross_attn_state_first_pass = false;
  14923. llama_graph_compute(lctx, gf, n_threads, threadpool);
  14924. // update the kv ring buffer
  14925. {
  14926. kv_self.head += n_tokens;
  14927. // Ensure kv cache head points to a valid index.
  14928. if (kv_self.head >= kv_self.size) {
  14929. kv_self.head = 0;
  14930. }
  14931. }
  14932. // plot the computation graph in dot format (for debugging purposes)
  14933. //if (n_past%100 == 0) {
  14934. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  14935. //}
  14936. // extract logits
  14937. if (res) {
  14938. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(lctx.sched, res);
  14939. GGML_ASSERT(backend_res != nullptr);
  14940. GGML_ASSERT(lctx.logits != nullptr);
  14941. float * logits_out = lctx.logits + n_outputs_prev*n_vocab;
  14942. const int32_t n_outputs_new = lctx.n_outputs;
  14943. if (n_outputs_new) {
  14944. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  14945. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_vocab <= (int64_t) lctx.logits_size);
  14946. ggml_backend_tensor_get_async(backend_res, res, logits_out, 0, n_outputs_new*n_vocab*sizeof(float));
  14947. }
  14948. }
  14949. // extract embeddings
  14950. if (embd) {
  14951. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched, embd);
  14952. GGML_ASSERT(backend_embd != nullptr);
  14953. switch (cparams.pooling_type) {
  14954. case LLAMA_POOLING_TYPE_NONE:
  14955. {
  14956. // extract token embeddings
  14957. GGML_ASSERT(lctx.embd != nullptr);
  14958. float * embd_out = lctx.embd + n_outputs_prev*n_embd;
  14959. const int32_t n_outputs_new = lctx.n_outputs;
  14960. if (n_outputs_new) {
  14961. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  14962. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_embd <= (int64_t) lctx.embd_size);
  14963. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_outputs_new*n_embd*sizeof(float));
  14964. }
  14965. } break;
  14966. case LLAMA_POOLING_TYPE_MEAN:
  14967. case LLAMA_POOLING_TYPE_CLS:
  14968. case LLAMA_POOLING_TYPE_LAST:
  14969. {
  14970. // extract sequence embeddings (cleared before processing each batch)
  14971. auto & embd_seq_out = lctx.embd_seq;
  14972. for (uint32_t s = 0; s < ubatch.n_seqs; ++s) {
  14973. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  14974. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  14975. continue;
  14976. }
  14977. embd_seq_out[seq_id].resize(n_embd);
  14978. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  14979. }
  14980. } break;
  14981. case LLAMA_POOLING_TYPE_RANK:
  14982. {
  14983. // extract the rerank score - a single float per sequence
  14984. auto & embd_seq_out = lctx.embd_seq;
  14985. for (uint32_t s = 0; s < ubatch.n_seqs; ++s) {
  14986. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  14987. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  14988. continue;
  14989. }
  14990. embd_seq_out[seq_id].resize(1);
  14991. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (seq_id)*sizeof(float), sizeof(float));
  14992. }
  14993. } break;
  14994. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  14995. {
  14996. GGML_ABORT("unknown pooling type");
  14997. }
  14998. }
  14999. }
  15000. n_outputs_prev += lctx.n_outputs;
  15001. }
  15002. // set output mappings
  15003. {
  15004. bool sorted_output = true;
  15005. GGML_ASSERT(lctx.sbatch.out_ids.size() == n_outputs);
  15006. for (size_t i = 0; i < n_outputs; ++i) {
  15007. size_t out_id = lctx.sbatch.out_ids[i];
  15008. lctx.output_ids[out_id] = i;
  15009. if (out_id != i) {
  15010. sorted_output = false;
  15011. }
  15012. }
  15013. if (sorted_output) {
  15014. lctx.sbatch.out_ids.clear();
  15015. }
  15016. }
  15017. // set to total number of outputs in the batch, for use in llama_get_logits_ith
  15018. lctx.n_outputs = n_outputs;
  15019. // wait for the computation to finish (automatically done when obtaining the model output)
  15020. //llama_synchronize(&lctx);
  15021. // decide if we need to defrag the kv cache
  15022. if (cparams.causal_attn && cparams.defrag_thold >= 0.0f) {
  15023. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used)/float(kv_self.n) : 0.0f;
  15024. // queue defragmentation for next llama_kv_cache_update
  15025. if (fragmentation > cparams.defrag_thold) {
  15026. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  15027. llama_kv_cache_defrag(kv_self);
  15028. }
  15029. }
  15030. // Reset state for the next token before backend sync, to allow the CPU activities in the reset to
  15031. // overlap with device computation.
  15032. ggml_backend_sched_reset(lctx.sched);
  15033. return 0;
  15034. }
  15035. // encode a batch of tokens by evaluating the encoder part of the transformer
  15036. //
  15037. // - lctx: llama context
  15038. // - batch: batch to evaluate
  15039. //
  15040. // return 0 on success
  15041. // return positive int on warning
  15042. // return negative int on error
  15043. //
  15044. static int llama_encode_internal(
  15045. llama_context & lctx,
  15046. llama_batch batch) {
  15047. lctx.is_encoding = true;
  15048. const uint32_t n_tokens = batch.n_tokens;
  15049. if (n_tokens == 0) {
  15050. LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__);
  15051. return -1;
  15052. }
  15053. const auto & model = lctx.model;
  15054. const auto & hparams = model.hparams;
  15055. const auto & cparams = lctx.cparams;
  15056. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  15057. if (batch.token) {
  15058. for (uint32_t i = 0; i < n_tokens; ++i) {
  15059. if (batch.token[i] < 0 || (uint32_t)batch.token[i] >= model.vocab.n_vocab) {
  15060. LLAMA_LOG_ERROR("%s: invalid token[%d] = %d\n", __func__, i, batch.token[i]);
  15061. return -1;
  15062. }
  15063. }
  15064. }
  15065. // micro-batching is not possible for non-causal encoding, so we process the batch in a single shot
  15066. GGML_ASSERT(cparams.n_ubatch >= n_tokens && "encoder requires n_ubatch >= n_tokens");
  15067. if (lctx.t_compute_start_us == 0) {
  15068. lctx.t_compute_start_us = ggml_time_us();
  15069. }
  15070. lctx.n_queued_tokens += n_tokens;
  15071. const int64_t n_embd = hparams.n_embd;
  15072. lctx.sbatch.from_batch(batch, n_embd, /* simple_split */ true, /* logits_all */ true);
  15073. const llama_ubatch ubatch = lctx.sbatch.split_simple(n_tokens);
  15074. // reserve output buffer
  15075. if (llama_output_reserve(lctx, n_tokens) < n_tokens) {
  15076. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_tokens);
  15077. return -2;
  15078. };
  15079. for (uint32_t i = 0; i < n_tokens; ++i) {
  15080. lctx.output_ids[i] = i;
  15081. }
  15082. lctx.inp_embd_enc = NULL;
  15083. lctx.n_outputs = n_tokens;
  15084. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  15085. ggml_threadpool_t threadpool = n_tokens == 1 ? lctx.threadpool : lctx.threadpool_batch;
  15086. GGML_ASSERT(n_threads > 0);
  15087. ggml_backend_sched_reset(lctx.sched);
  15088. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  15089. ggml_cgraph * gf = llama_build_graph(lctx, ubatch, false);
  15090. // the output embeddings after the final encoder normalization
  15091. struct ggml_tensor * embd = nullptr;
  15092. // there are two cases here
  15093. if (llama_model_has_decoder(&lctx.model)) {
  15094. // first case is an encoder-decoder T5 model where embeddings are passed to decoder
  15095. embd = ggml_graph_node(gf, -1);
  15096. GGML_ASSERT(strcmp(embd->name, "result_norm") == 0 && "missing result_output tensor");
  15097. } else {
  15098. // second case is an encoder-only T5 model
  15099. if (cparams.embeddings) {
  15100. // only output embeddings if required
  15101. embd = ggml_graph_node(gf, -1);
  15102. if (strcmp(embd->name, "result_embd_pooled") != 0) {
  15103. embd = ggml_graph_node(gf, -2);
  15104. }
  15105. GGML_ASSERT(strcmp(embd->name, "result_embd_pooled") == 0 && "missing embeddings tensor");
  15106. }
  15107. }
  15108. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  15109. llama_set_inputs(lctx, ubatch);
  15110. llama_graph_compute(lctx, gf, n_threads, threadpool);
  15111. // extract embeddings
  15112. if (embd) {
  15113. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched, embd);
  15114. GGML_ASSERT(backend_embd != nullptr);
  15115. if (llama_model_has_decoder(&lctx.model)) {
  15116. lctx.embd_enc.resize(n_tokens*n_embd);
  15117. float * embd_out = lctx.embd_enc.data();
  15118. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_tokens*n_embd*sizeof(float));
  15119. GGML_ASSERT(!ubatch.equal_seqs); // TODO: handle equal splits
  15120. // remember the sequence ids used during the encoding - needed for cross attention later
  15121. lctx.seq_ids_enc.resize(n_tokens);
  15122. for (uint32_t i = 0; i < n_tokens; i++) {
  15123. for (int s = 0; s < ubatch.n_seq_id[i]; s++) {
  15124. llama_seq_id seq_id = ubatch.seq_id[i][s];
  15125. lctx.seq_ids_enc[i].insert(seq_id);
  15126. }
  15127. }
  15128. } else {
  15129. GGML_ASSERT(lctx.embd != nullptr);
  15130. switch (cparams.pooling_type) {
  15131. case LLAMA_POOLING_TYPE_NONE:
  15132. {
  15133. // extract token embeddings
  15134. GGML_ASSERT(lctx.embd != nullptr);
  15135. float * embd_out = lctx.embd;
  15136. GGML_ASSERT(n_tokens*n_embd <= (int64_t) lctx.embd_size);
  15137. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_tokens*n_embd*sizeof(float));
  15138. } break;
  15139. case LLAMA_POOLING_TYPE_MEAN:
  15140. case LLAMA_POOLING_TYPE_CLS:
  15141. case LLAMA_POOLING_TYPE_LAST:
  15142. {
  15143. // extract sequence embeddings
  15144. auto & embd_seq_out = lctx.embd_seq;
  15145. embd_seq_out.clear();
  15146. GGML_ASSERT(!ubatch.equal_seqs); // TODO: handle equal splits
  15147. for (uint32_t i = 0; i < n_tokens; i++) {
  15148. const llama_seq_id seq_id = ubatch.seq_id[i][0];
  15149. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  15150. continue;
  15151. }
  15152. embd_seq_out[seq_id].resize(n_embd);
  15153. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  15154. }
  15155. } break;
  15156. case LLAMA_POOLING_TYPE_RANK:
  15157. {
  15158. // TODO: this likely should be the same logic as in llama_decoder_internal, but better to
  15159. // wait for an encoder model that requires this pooling type in order to test it
  15160. // https://github.com/ggerganov/llama.cpp/pull/9510
  15161. GGML_ABORT("RANK pooling not implemented yet");
  15162. }
  15163. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  15164. {
  15165. GGML_ABORT("unknown pooling type");
  15166. }
  15167. }
  15168. }
  15169. }
  15170. // Reset state for the next token before backend sync, to allow the CPU activities in the reset to
  15171. // overlap with device computation.
  15172. ggml_backend_sched_reset(lctx.sched);
  15173. return 0;
  15174. }
  15175. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  15176. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  15177. auto & kv_self = lctx.kv_self;
  15178. const auto & hparams = lctx.model.hparams;
  15179. const uint32_t n_layer = hparams.n_layer;
  15180. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  15181. const uint32_t n_used = kv_self.used;
  15182. assert(n_used <= n_kv);
  15183. //const int64_t t_start = ggml_time_us();
  15184. // number of cells moved
  15185. uint32_t n_moves = 0;
  15186. // each move requires 6*n_layer tensors (see build_defrag)
  15187. // - source view, destination view, copy operation
  15188. // - x2 for keys and values
  15189. //const uint32_t max_moves = llama_model_max_nodes(model)/(6*n_layer);
  15190. // TODO: tmp fix https://github.com/ggerganov/llama.cpp/issues/6685#issuecomment-2057579516
  15191. const uint32_t max_moves = (llama_model_max_nodes(lctx.model) - 2*n_layer)/(6*n_layer);
  15192. // determine which KV cells to move where
  15193. //
  15194. // cell i moves to ids[i]
  15195. //
  15196. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  15197. //
  15198. std::vector<uint32_t> ids(n_kv, n_kv);
  15199. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  15200. const auto & cell0 = kv_self.cells[i0];
  15201. if (!cell0.is_empty()) {
  15202. ids[i0] = i0;
  15203. continue;
  15204. }
  15205. // found a hole - fill it with data from the end of the cache
  15206. uint32_t nh = 1;
  15207. // determine the size of the hole
  15208. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  15209. nh++;
  15210. }
  15211. uint32_t nf = 0;
  15212. uint32_t is = n_kv - 1;
  15213. // starting from the end, find nh non-empty cells
  15214. for (; is > i0; --is) {
  15215. const auto & cell1 = kv_self.cells[is];
  15216. if (cell1.is_empty() || ids[is] != n_kv) {
  15217. continue;
  15218. }
  15219. // non-empty cell which is not yet moved
  15220. nf++;
  15221. if (nf == nh) {
  15222. break;
  15223. }
  15224. }
  15225. // this can only happen if `n_used` is not accurate, which would be a bug
  15226. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  15227. nf = 0;
  15228. uint32_t i1 = is;
  15229. // are we moving a continuous block of memory?
  15230. bool cont = false;
  15231. // should we stop searching for the next move?
  15232. bool stop = false;
  15233. // go back and move the nf cells to the hole
  15234. for (; i1 < n_kv; ++i1) {
  15235. auto & cell1 = kv_self.cells[i1];
  15236. if (cell1.is_empty() || ids[i1] != n_kv) {
  15237. if (n_moves == max_moves) {
  15238. stop = true;
  15239. break;
  15240. }
  15241. cont = false;
  15242. continue;
  15243. }
  15244. // this cell goes to (i0 + nf)
  15245. ids[i1] = i0 + nf;
  15246. // move the cell meta data
  15247. kv_self.cells[i0 + nf] = cell1;
  15248. // clear the old cell and move the head there
  15249. cell1 = llama_kv_cell();
  15250. kv_self.head = n_used;
  15251. if (!cont) {
  15252. n_moves++;
  15253. cont = true;
  15254. }
  15255. nf++;
  15256. if (nf == nh) {
  15257. break;
  15258. }
  15259. }
  15260. if (stop || n_moves == max_moves) {
  15261. break;
  15262. }
  15263. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  15264. i0 += nh - 1;
  15265. }
  15266. if (n_moves == 0) {
  15267. return;
  15268. }
  15269. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  15270. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  15271. #if 0
  15272. // CPU defrag
  15273. //
  15274. // TODO: optimizations are possible:
  15275. // - multiple threads
  15276. // - avoid copying to the host memory when already there
  15277. //
  15278. // likely not worth the effort, as we have ggml_graph based defrag
  15279. //
  15280. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  15281. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  15282. const uint32_t kv_size = kv_self.size;
  15283. std::vector<uint8_t> buf_k;
  15284. std::vector<uint8_t> buf_v;
  15285. for (uint32_t il = 0; il < n_layer; ++il) {
  15286. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  15287. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  15288. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  15289. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  15290. buf_k.resize(k_size);
  15291. buf_v.resize(v_size);
  15292. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  15293. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  15294. // batch move [i, i+nm) to [id, id+nm)
  15295. // note: cells can move only to a lower index
  15296. for (uint32_t i = 0; i < n_kv; ++i) {
  15297. const uint32_t id = ids[i];
  15298. if (i == id || id == n_kv) {
  15299. continue;
  15300. }
  15301. uint32_t nm = 1;
  15302. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  15303. nm++;
  15304. }
  15305. // move keys
  15306. {
  15307. const int64_t os = i*k_size_row;
  15308. const int64_t od = id*k_size_row;
  15309. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  15310. }
  15311. // move values (note: they are transposed)
  15312. {
  15313. const int64_t os = i;
  15314. const int64_t od = id;
  15315. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  15316. 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);
  15317. }
  15318. }
  15319. i += nm - 1;
  15320. }
  15321. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  15322. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  15323. }
  15324. #else
  15325. // ggml_graph defrag
  15326. ggml_backend_sched_reset(lctx.sched);
  15327. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  15328. llama_graph_compute(lctx, gf, lctx.cparams.n_threads, lctx.threadpool);
  15329. #endif
  15330. //const int64_t t_end = ggml_time_us();
  15331. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  15332. }
  15333. static void llama_kv_cache_update_internal(struct llama_context & lctx) {
  15334. bool need_reserve = false;
  15335. // apply K-shift if needed
  15336. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE && lctx.kv_self.has_shift) {
  15337. if (lctx.model.arch == LLM_ARCH_DEEPSEEK2) { // not supported due to MLA
  15338. GGML_ABORT("Deepseek2 does not support K-shift");
  15339. }
  15340. {
  15341. ggml_backend_sched_reset(lctx.sched);
  15342. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  15343. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  15344. llama_set_k_shift(lctx);
  15345. llama_graph_compute(lctx, gf, lctx.cparams.n_threads, lctx.threadpool);
  15346. need_reserve = true;
  15347. }
  15348. {
  15349. auto & kv_self = lctx.kv_self;
  15350. kv_self.has_shift = false;
  15351. for (uint32_t i = 0; i < kv_self.size; ++i) {
  15352. kv_self.cells[i].delta = 0;
  15353. }
  15354. }
  15355. }
  15356. // defragment the KV cache if needed
  15357. if (lctx.kv_self.do_defrag) {
  15358. llama_kv_cache_defrag_internal(lctx);
  15359. need_reserve = true;
  15360. lctx.kv_self.do_defrag = false;
  15361. }
  15362. // reserve a worst case graph again
  15363. if (need_reserve) {
  15364. // TODO: extract to a function
  15365. // build worst-case graph
  15366. uint32_t n_seqs = 1; // TODO: worst-case number of sequences
  15367. uint32_t n_tokens = std::min(lctx.cparams.n_ctx, lctx.cparams.n_ubatch);
  15368. 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
  15369. llama_ubatch ubatch = { true, n_tokens, n_tokens / n_seqs, n_seqs, &token, nullptr, nullptr, nullptr, nullptr, nullptr};
  15370. ggml_cgraph * gf = llama_build_graph(lctx, ubatch, true);
  15371. // initialize scheduler with the worst-case graph
  15372. ggml_backend_sched_reset(lctx.sched);
  15373. if (!ggml_backend_sched_reserve(lctx.sched, gf)) {
  15374. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  15375. }
  15376. }
  15377. }
  15378. //
  15379. // quantization
  15380. //
  15381. struct quantize_state_internal {
  15382. const llama_model & model;
  15383. const llama_model_quantize_params * params;
  15384. int n_attention_wv = 0;
  15385. int n_ffn_down = 0;
  15386. int n_ffn_gate = 0;
  15387. int n_ffn_up = 0;
  15388. int i_attention_wv = 0;
  15389. int i_ffn_down = 0;
  15390. int i_ffn_gate = 0;
  15391. int i_ffn_up = 0;
  15392. int n_k_quantized = 0;
  15393. int n_fallback = 0;
  15394. bool has_imatrix = false;
  15395. // used to figure out if a model shares tok_embd with the output weight
  15396. bool has_output = false;
  15397. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  15398. : model(model)
  15399. , params(params)
  15400. {}
  15401. };
  15402. static void llama_tensor_dequantize_internal(
  15403. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  15404. const size_t nelements, const int nthread
  15405. ) {
  15406. if (output.size() < nelements) {
  15407. output.resize(nelements);
  15408. }
  15409. float * f32_output = (float *) output.data();
  15410. ggml_type_traits_t qtype;
  15411. if (ggml_is_quantized(tensor->type)) {
  15412. qtype = ggml_internal_get_type_traits(tensor->type);
  15413. if (qtype.to_float == NULL) {
  15414. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  15415. }
  15416. } else if (tensor->type != GGML_TYPE_F16 &&
  15417. tensor->type != GGML_TYPE_BF16) {
  15418. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  15419. }
  15420. if (nthread < 2) {
  15421. if (tensor->type == GGML_TYPE_F16) {
  15422. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  15423. } else if (tensor->type == GGML_TYPE_BF16) {
  15424. ggml_bf16_to_fp32_row((ggml_bf16_t *)tensor->data, f32_output, nelements);
  15425. } else if (ggml_is_quantized(tensor->type)) {
  15426. qtype.to_float(tensor->data, f32_output, nelements);
  15427. } else {
  15428. GGML_ABORT("fatal error"); // unreachable
  15429. }
  15430. return;
  15431. }
  15432. size_t block_size;
  15433. if (tensor->type == GGML_TYPE_F16 ||
  15434. tensor->type == GGML_TYPE_BF16) {
  15435. block_size = 1;
  15436. } else {
  15437. block_size = (size_t)ggml_blck_size(tensor->type);
  15438. }
  15439. size_t block_size_bytes = ggml_type_size(tensor->type);
  15440. GGML_ASSERT(nelements % block_size == 0);
  15441. size_t nblocks = nelements / block_size;
  15442. size_t blocks_per_thread = nblocks / nthread;
  15443. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  15444. size_t in_buff_offs = 0;
  15445. size_t out_buff_offs = 0;
  15446. for (int tnum = 0; tnum < nthread; tnum++) {
  15447. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  15448. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  15449. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  15450. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  15451. if (typ == GGML_TYPE_F16) {
  15452. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  15453. } else if (typ == GGML_TYPE_BF16) {
  15454. ggml_bf16_to_fp32_row((ggml_bf16_t *)inbuf, outbuf, nels);
  15455. } else {
  15456. qtype.to_float(inbuf, outbuf, nels);
  15457. }
  15458. };
  15459. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  15460. in_buff_offs += thr_block_bytes;
  15461. out_buff_offs += thr_elems;
  15462. }
  15463. for (auto & w : workers) { w.join(); }
  15464. workers.clear();
  15465. }
  15466. static ggml_type llama_tensor_get_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  15467. const std::string name = ggml_get_name(tensor);
  15468. // TODO: avoid hardcoded tensor names - use the TN_* constants
  15469. const llm_arch arch = qs.model.arch;
  15470. const auto tn = LLM_TN(arch);
  15471. auto use_more_bits = [](int i_layer, int n_layers) -> bool {
  15472. return i_layer < n_layers/8 || i_layer >= 7*n_layers/8 || (i_layer - n_layers/8)%3 == 2;
  15473. };
  15474. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  15475. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  15476. if (n_expert > 1) {
  15477. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but occasionally randomly
  15478. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  15479. // for getting the current layer as I initially thought, and we need to resort to parsing the
  15480. // tensor name.
  15481. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  15482. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  15483. }
  15484. if (i_layer < 0 || i_layer >= n_layer) {
  15485. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  15486. }
  15487. }
  15488. return std::make_pair(i_layer, n_layer);
  15489. };
  15490. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  15491. // with the quantization of the output tensor
  15492. if (name == tn(LLM_TENSOR_OUTPUT, "weight") || (!qs.has_output && name == tn(LLM_TENSOR_TOKEN_EMBD, "weight"))) {
  15493. if (qs.params->output_tensor_type < GGML_TYPE_COUNT) {
  15494. new_type = qs.params->output_tensor_type;
  15495. } else {
  15496. int nx = tensor->ne[0];
  15497. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  15498. new_type = GGML_TYPE_Q8_0;
  15499. }
  15500. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  15501. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ||
  15502. ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  15503. new_type = GGML_TYPE_Q5_K;
  15504. }
  15505. else if (new_type != GGML_TYPE_Q8_0) {
  15506. new_type = GGML_TYPE_Q6_K;
  15507. }
  15508. }
  15509. } else if (name == "token_embd.weight") {
  15510. if (qs.params->token_embedding_type < GGML_TYPE_COUNT) {
  15511. new_type = qs.params->token_embedding_type;
  15512. } else {
  15513. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
  15514. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  15515. new_type = GGML_TYPE_Q2_K;
  15516. }
  15517. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  15518. new_type = GGML_TYPE_IQ3_S;
  15519. }
  15520. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  15521. new_type = GGML_TYPE_IQ3_S;
  15522. }
  15523. else if (new_type == GGML_TYPE_Q4_0_4_4 || new_type == GGML_TYPE_Q4_0_4_8 ||
  15524. new_type == GGML_TYPE_Q4_0_8_8) {
  15525. new_type = GGML_TYPE_Q4_0;
  15526. }
  15527. else if (ftype == LLAMA_FTYPE_MOSTLY_TQ1_0 || ftype == LLAMA_FTYPE_MOSTLY_TQ2_0) {
  15528. new_type = GGML_TYPE_Q4_K;
  15529. }
  15530. }
  15531. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  15532. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  15533. if (name.find("attn_v.weight") != std::string::npos) {
  15534. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  15535. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  15536. ++qs.i_attention_wv;
  15537. }
  15538. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  15539. new_type = GGML_TYPE_Q4_K;
  15540. }
  15541. else if (name.find("ffn_down") != std::string::npos) {
  15542. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  15543. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  15544. }
  15545. ++qs.i_ffn_down;
  15546. }
  15547. else if (name.find("attn_output.weight") != std::string::npos) {
  15548. if (qs.model.hparams.n_expert == 8) {
  15549. new_type = GGML_TYPE_Q5_K;
  15550. } else {
  15551. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) new_type = GGML_TYPE_IQ2_XXS;
  15552. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  15553. }
  15554. }
  15555. } else if (name.find("attn_v.weight") != std::string::npos) {
  15556. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  15557. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  15558. }
  15559. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  15560. new_type = GGML_TYPE_Q4_K;
  15561. }
  15562. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  15563. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  15564. }
  15565. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S) && qs.model.hparams.n_gqa() >= 4) {
  15566. new_type = GGML_TYPE_Q4_K;
  15567. }
  15568. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  15569. new_type = GGML_TYPE_Q4_K;
  15570. }
  15571. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  15572. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  15573. }
  15574. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  15575. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  15576. new_type = GGML_TYPE_Q5_K;
  15577. }
  15578. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  15579. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  15580. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  15581. if (qs.model.type == MODEL_70B) {
  15582. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  15583. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  15584. // nearly negligible increase in model size by quantizing this tensor with more bits:
  15585. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  15586. }
  15587. if (qs.model.hparams.n_expert == 8) {
  15588. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  15589. // TODO: explore better strategies
  15590. new_type = GGML_TYPE_Q8_0;
  15591. }
  15592. ++qs.i_attention_wv;
  15593. } else if (name.find("attn_k.weight") != std::string::npos) {
  15594. if (qs.model.hparams.n_expert == 8) {
  15595. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  15596. // TODO: explore better strategies
  15597. new_type = GGML_TYPE_Q8_0;
  15598. }
  15599. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  15600. new_type = GGML_TYPE_IQ3_XXS;
  15601. }
  15602. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  15603. new_type = GGML_TYPE_IQ2_S;
  15604. }
  15605. } else if (name.find("attn_q.weight") != std::string::npos) {
  15606. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  15607. new_type = GGML_TYPE_IQ3_XXS;
  15608. }
  15609. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  15610. new_type = GGML_TYPE_IQ2_S;
  15611. }
  15612. } else if (name.find("ffn_down") != std::string::npos) {
  15613. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  15614. int i_layer = info.first, n_layer = info.second;
  15615. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  15616. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  15617. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  15618. }
  15619. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  15620. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  15621. }
  15622. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  15623. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  15624. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  15625. : GGML_TYPE_Q3_K;
  15626. }
  15627. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  15628. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  15629. new_type = GGML_TYPE_Q4_K;
  15630. }
  15631. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  15632. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  15633. }
  15634. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  15635. if (arch == LLM_ARCH_FALCON) {
  15636. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  15637. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  15638. } else {
  15639. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  15640. }
  15641. }
  15642. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  15643. new_type = GGML_TYPE_Q5_K;
  15644. }
  15645. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  15646. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  15647. new_type = GGML_TYPE_Q5_K;
  15648. }
  15649. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  15650. && qs.has_imatrix && i_layer < n_layer/8) {
  15651. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  15652. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  15653. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  15654. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  15655. }
  15656. ++qs.i_ffn_down;
  15657. } else if (name.find("attn_output.weight") != std::string::npos) {
  15658. if (arch != LLM_ARCH_FALCON) {
  15659. if (qs.model.hparams.n_expert == 8) {
  15660. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  15661. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  15662. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  15663. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  15664. new_type = GGML_TYPE_Q5_K;
  15665. }
  15666. } else {
  15667. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  15668. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  15669. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  15670. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  15671. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  15672. }
  15673. } else {
  15674. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  15675. }
  15676. }
  15677. else if (name.find("attn_qkv.weight") != std::string::npos) {
  15678. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  15679. new_type = GGML_TYPE_Q4_K;
  15680. }
  15681. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  15682. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  15683. }
  15684. else if (name.find("ffn_gate") != std::string::npos) {
  15685. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  15686. int i_layer = info.first, n_layer = info.second;
  15687. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  15688. new_type = GGML_TYPE_IQ3_XXS;
  15689. }
  15690. ++qs.i_ffn_gate;
  15691. }
  15692. else if (name.find("ffn_up") != std::string::npos) {
  15693. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  15694. int i_layer = info.first, n_layer = info.second;
  15695. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  15696. new_type = GGML_TYPE_IQ3_XXS;
  15697. }
  15698. ++qs.i_ffn_up;
  15699. }
  15700. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  15701. //}
  15702. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  15703. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  15704. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  15705. //}
  15706. // This can be used to reduce the size of the Q5_K_S model.
  15707. // The associated PPL increase is fully in line with the size reduction
  15708. //else {
  15709. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  15710. //}
  15711. bool convert_incompatible_tensor = false;
  15712. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  15713. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  15714. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  15715. new_type == GGML_TYPE_IQ3_XXS || new_type == GGML_TYPE_IQ1_S || new_type == GGML_TYPE_IQ3_S ||
  15716. new_type == GGML_TYPE_IQ1_M) {
  15717. int nx = tensor->ne[0];
  15718. int ny = tensor->ne[1];
  15719. if (nx % QK_K != 0) {
  15720. 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));
  15721. convert_incompatible_tensor = true;
  15722. } else {
  15723. ++qs.n_k_quantized;
  15724. }
  15725. }
  15726. if (convert_incompatible_tensor) {
  15727. switch (new_type) {
  15728. case GGML_TYPE_TQ1_0:
  15729. case GGML_TYPE_TQ2_0: new_type = GGML_TYPE_Q4_0; break; // TODO: use a symmetric type instead
  15730. case GGML_TYPE_IQ2_XXS:
  15731. case GGML_TYPE_IQ2_XS:
  15732. case GGML_TYPE_IQ2_S:
  15733. case GGML_TYPE_IQ3_XXS:
  15734. case GGML_TYPE_IQ3_S:
  15735. case GGML_TYPE_IQ1_S:
  15736. case GGML_TYPE_IQ1_M:
  15737. case GGML_TYPE_Q2_K:
  15738. case GGML_TYPE_Q3_K:
  15739. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  15740. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  15741. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  15742. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  15743. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  15744. }
  15745. if (tensor->ne[0] % ggml_blck_size(new_type) != 0) {
  15746. new_type = GGML_TYPE_F16;
  15747. }
  15748. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  15749. ++qs.n_fallback;
  15750. }
  15751. return new_type;
  15752. }
  15753. 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) {
  15754. if (nthread < 2) {
  15755. // single-thread
  15756. size_t new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, imatrix);
  15757. if (!ggml_validate_row_data(new_type, new_data, new_size)) {
  15758. throw std::runtime_error("quantized data validation failed");
  15759. }
  15760. return new_size;
  15761. }
  15762. std::mutex mutex;
  15763. int64_t counter = 0;
  15764. size_t new_size = 0;
  15765. bool valid = true;
  15766. auto compute = [&mutex, &counter, &new_size, &valid, new_type, f32_data, new_data, chunk_size,
  15767. nrows, n_per_row, imatrix]() {
  15768. const int64_t nrows_per_chunk = chunk_size / n_per_row;
  15769. size_t local_size = 0;
  15770. while (true) {
  15771. std::unique_lock<std::mutex> lock(mutex);
  15772. int64_t first_row = counter; counter += nrows_per_chunk;
  15773. if (first_row >= nrows) {
  15774. if (local_size > 0) {
  15775. new_size += local_size;
  15776. }
  15777. break;
  15778. }
  15779. lock.unlock();
  15780. const int64_t this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  15781. size_t this_size = ggml_quantize_chunk(new_type, f32_data, new_data, first_row * n_per_row, this_nrow, n_per_row, imatrix);
  15782. local_size += this_size;
  15783. // validate the quantized data
  15784. const size_t row_size = ggml_row_size(new_type, n_per_row);
  15785. void * this_data = (char *) new_data + first_row * row_size;
  15786. if (!ggml_validate_row_data(new_type, this_data, this_size)) {
  15787. std::unique_lock<std::mutex> lock(mutex);
  15788. valid = false;
  15789. break;
  15790. }
  15791. }
  15792. };
  15793. for (int it = 0; it < nthread - 1; ++it) {
  15794. workers.emplace_back(compute);
  15795. }
  15796. compute();
  15797. for (auto & w : workers) { w.join(); }
  15798. workers.clear();
  15799. if (!valid) {
  15800. throw std::runtime_error("quantized data validation failed");
  15801. }
  15802. return new_size;
  15803. }
  15804. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  15805. ggml_type default_type;
  15806. llama_ftype ftype = params->ftype;
  15807. switch (params->ftype) {
  15808. case LLAMA_FTYPE_MOSTLY_Q4_0: default_type = GGML_TYPE_Q4_0; break;
  15809. case LLAMA_FTYPE_MOSTLY_Q4_1: default_type = GGML_TYPE_Q4_1; break;
  15810. case LLAMA_FTYPE_MOSTLY_Q5_0: default_type = GGML_TYPE_Q5_0; break;
  15811. case LLAMA_FTYPE_MOSTLY_Q5_1: default_type = GGML_TYPE_Q5_1; break;
  15812. case LLAMA_FTYPE_MOSTLY_Q8_0: default_type = GGML_TYPE_Q8_0; break;
  15813. case LLAMA_FTYPE_MOSTLY_F16: default_type = GGML_TYPE_F16; break;
  15814. case LLAMA_FTYPE_MOSTLY_BF16: default_type = GGML_TYPE_BF16; break;
  15815. case LLAMA_FTYPE_ALL_F32: default_type = GGML_TYPE_F32; break;
  15816. // K-quants
  15817. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  15818. case LLAMA_FTYPE_MOSTLY_Q2_K: default_type = GGML_TYPE_Q2_K; break;
  15819. case LLAMA_FTYPE_MOSTLY_IQ3_XS: default_type = GGML_TYPE_IQ3_S; break;
  15820. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  15821. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  15822. case LLAMA_FTYPE_MOSTLY_Q3_K_L: default_type = GGML_TYPE_Q3_K; break;
  15823. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  15824. case LLAMA_FTYPE_MOSTLY_Q4_K_M: default_type = GGML_TYPE_Q4_K; break;
  15825. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  15826. case LLAMA_FTYPE_MOSTLY_Q5_K_M: default_type = GGML_TYPE_Q5_K; break;
  15827. case LLAMA_FTYPE_MOSTLY_Q6_K: default_type = GGML_TYPE_Q6_K; break;
  15828. case LLAMA_FTYPE_MOSTLY_TQ1_0: default_type = GGML_TYPE_TQ1_0; break;
  15829. case LLAMA_FTYPE_MOSTLY_TQ2_0: default_type = GGML_TYPE_TQ2_0; break;
  15830. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: default_type = GGML_TYPE_IQ2_XXS; break;
  15831. case LLAMA_FTYPE_MOSTLY_IQ2_XS: default_type = GGML_TYPE_IQ2_XS; break;
  15832. case LLAMA_FTYPE_MOSTLY_IQ2_S: default_type = GGML_TYPE_IQ2_XS; break;
  15833. case LLAMA_FTYPE_MOSTLY_IQ2_M: default_type = GGML_TYPE_IQ2_S; break;
  15834. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: default_type = GGML_TYPE_IQ3_XXS; break;
  15835. case LLAMA_FTYPE_MOSTLY_IQ1_S: default_type = GGML_TYPE_IQ1_S; break;
  15836. case LLAMA_FTYPE_MOSTLY_IQ1_M: default_type = GGML_TYPE_IQ1_M; break;
  15837. case LLAMA_FTYPE_MOSTLY_IQ4_NL: default_type = GGML_TYPE_IQ4_NL; break;
  15838. case LLAMA_FTYPE_MOSTLY_IQ4_XS: default_type = GGML_TYPE_IQ4_XS; break;
  15839. case LLAMA_FTYPE_MOSTLY_IQ3_S: default_type = GGML_TYPE_IQ3_S; break;
  15840. case LLAMA_FTYPE_MOSTLY_IQ3_M: default_type = GGML_TYPE_IQ3_S; break;
  15841. case LLAMA_FTYPE_MOSTLY_Q4_0_4_4: default_type = GGML_TYPE_Q4_0_4_4; break;
  15842. case LLAMA_FTYPE_MOSTLY_Q4_0_4_8: default_type = GGML_TYPE_Q4_0_4_8; break;
  15843. case LLAMA_FTYPE_MOSTLY_Q4_0_8_8: default_type = GGML_TYPE_Q4_0_8_8; break;
  15844. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  15845. }
  15846. int nthread = params->nthread;
  15847. if (nthread <= 0) {
  15848. nthread = std::thread::hardware_concurrency();
  15849. }
  15850. // mmap consistently increases speed Linux, and also increases speed on Windows with
  15851. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  15852. #if defined(__linux__) || defined(_WIN32)
  15853. constexpr bool use_mmap = true;
  15854. #else
  15855. constexpr bool use_mmap = false;
  15856. #endif
  15857. llama_model_kv_override * kv_overrides = nullptr;
  15858. if (params->kv_overrides) {
  15859. auto v = (std::vector<llama_model_kv_override>*)params->kv_overrides;
  15860. kv_overrides = v->data();
  15861. }
  15862. llama_model_loader ml(fname_inp, use_mmap, /*check_tensors*/ true, kv_overrides);
  15863. ml.init_mappings(false); // no prefetching
  15864. llama_model model;
  15865. llm_load_arch(ml, model);
  15866. llm_load_hparams(ml, model);
  15867. struct quantize_state_internal qs(model, params);
  15868. if (params->only_copy) {
  15869. ftype = model.ftype;
  15870. }
  15871. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  15872. if (params->imatrix) {
  15873. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  15874. if (imatrix_data) {
  15875. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  15876. qs.has_imatrix = true;
  15877. // check imatrix for nans or infs
  15878. for (const auto & kv : *imatrix_data) {
  15879. for (float f : kv.second) {
  15880. if (!std::isfinite(f)) {
  15881. throw std::runtime_error(format("imatrix contains non-finite value %f\n", f));
  15882. }
  15883. }
  15884. }
  15885. }
  15886. }
  15887. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  15888. struct gguf_context * ctx_out = gguf_init_empty();
  15889. // copy the KV pairs from the input file
  15890. gguf_set_kv (ctx_out, ml.meta);
  15891. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION); // TODO: use LLM_KV
  15892. gguf_set_val_u32(ctx_out, "general.file_type", ftype); // TODO: use LLM_KV
  15893. // Remove split metadata
  15894. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_NO).c_str());
  15895. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_COUNT).c_str());
  15896. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str());
  15897. if (params->kv_overrides) {
  15898. const std::vector<llama_model_kv_override> & overrides = *(const std::vector<llama_model_kv_override> *)params->kv_overrides;
  15899. for (auto & o : overrides) {
  15900. if (o.key[0] == 0) break;
  15901. if (o.tag == LLAMA_KV_OVERRIDE_TYPE_FLOAT) {
  15902. gguf_set_val_f32(ctx_out, o.key, o.val_f64);
  15903. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_INT) {
  15904. gguf_set_val_i32(ctx_out, o.key, o.val_i64);
  15905. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_BOOL) {
  15906. gguf_set_val_bool(ctx_out, o.key, o.val_bool);
  15907. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_STR) {
  15908. gguf_set_val_str(ctx_out, o.key, o.val_str);
  15909. } else {
  15910. LLAMA_LOG_WARN("%s: unknown KV override type for key %s\n", __func__, o.key);
  15911. }
  15912. }
  15913. }
  15914. for (int i = 0; i < ml.n_tensors; ++i) {
  15915. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  15916. const std::string name = ggml_get_name(meta);
  15917. // TODO: avoid hardcoded tensor names - use the TN_* constants
  15918. if (name.find("attn_v.weight") != std::string::npos ||
  15919. name.find("attn_qkv.weight") != std::string::npos ||
  15920. name.find("attn_kv_b.weight")!= std::string::npos) {
  15921. ++qs.n_attention_wv;
  15922. } else if (name == LLM_TN(model.arch)(LLM_TENSOR_OUTPUT, "weight")) {
  15923. qs.has_output = true;
  15924. }
  15925. }
  15926. qs.n_ffn_down = qs.n_ffn_gate = qs.n_ffn_up = (int)model.hparams.n_layer;
  15927. // sanity checks
  15928. {
  15929. const auto & n_head_kv_iter = model.hparams.n_head_kv_arr.begin();
  15930. // attention layers have a non-zero number of kv heads
  15931. int32_t n_attn_layer = model.hparams.n_layer - std::count(n_head_kv_iter, n_head_kv_iter + model.hparams.n_layer, 0);
  15932. if (llama_model_has_encoder(&model)) {
  15933. n_attn_layer *= 3;
  15934. }
  15935. if (qs.n_attention_wv != n_attn_layer) {
  15936. LLAMA_LOG_WARN("%s: n_attention_wv is unexpected, expected: %d, found: %d\n", __func__, n_attn_layer, qs.n_attention_wv);
  15937. }
  15938. }
  15939. size_t total_size_org = 0;
  15940. size_t total_size_new = 0;
  15941. std::vector<std::thread> workers;
  15942. workers.reserve(nthread);
  15943. int idx = 0;
  15944. std::vector<no_init<uint8_t>> read_data;
  15945. std::vector<no_init<uint8_t>> work;
  15946. std::vector<no_init<float>> f32_conv_buf;
  15947. uint16_t n_split = 1;
  15948. // Assume split index is continuous
  15949. if (params->keep_split) {
  15950. for (int i = 0; i < ml.n_tensors; ++i) {
  15951. n_split = std::max(uint16_t(ml.get_weight(i)->idx+1), n_split);
  15952. }
  15953. }
  15954. std::vector<gguf_context*> ctx_outs(n_split, NULL);
  15955. ctx_outs[0] = ctx_out;
  15956. // populate the original tensors so we get an initial meta data
  15957. for (int i = 0; i < ml.n_tensors; ++i) {
  15958. auto weight = ml.get_weight(i);
  15959. uint16_t i_split = params->keep_split ? weight->idx : 0;
  15960. struct ggml_tensor * tensor = weight->tensor;
  15961. if (ctx_outs[i_split] == NULL) {
  15962. ctx_outs[i_split] = gguf_init_empty();
  15963. }
  15964. gguf_add_tensor(ctx_outs[i_split], tensor);
  15965. }
  15966. // Set split info if needed
  15967. if (n_split > 1) {
  15968. for (size_t i = 0; i < ctx_outs.size(); ++i) {
  15969. gguf_set_val_u16(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_NO).c_str(), i);
  15970. gguf_set_val_u16(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_COUNT).c_str(), n_split);
  15971. gguf_set_val_i32(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str(), ml.n_tensors);
  15972. }
  15973. }
  15974. int cur_split = -1;
  15975. std::ofstream fout;
  15976. auto close_ofstream = [&]() {
  15977. // Write metadata and close file handler
  15978. if (fout.is_open()) {
  15979. fout.seekp(0);
  15980. std::vector<uint8_t> data(gguf_get_meta_size(ctx_outs[cur_split]));
  15981. gguf_get_meta_data(ctx_outs[cur_split], data.data());
  15982. fout.write((const char *) data.data(), data.size());
  15983. fout.close();
  15984. }
  15985. };
  15986. auto new_ofstream = [&](int index) {
  15987. cur_split = index;
  15988. GGML_ASSERT(ctx_outs[cur_split] && "Find uninitialized gguf_context");
  15989. std::string fname = fname_out;
  15990. if (params->keep_split) {
  15991. char split_path[PATH_MAX] = {0};
  15992. llama_split_path(split_path, sizeof(split_path), fname_out.c_str(), cur_split, n_split);
  15993. fname = std::string(split_path);
  15994. }
  15995. fout = std::ofstream(fname, std::ios::binary);
  15996. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  15997. const size_t meta_size = gguf_get_meta_size(ctx_outs[cur_split]);
  15998. // placeholder for the meta data
  15999. ::zeros(fout, meta_size);
  16000. };
  16001. const auto tn = LLM_TN(model.arch);
  16002. new_ofstream(0);
  16003. for (int i = 0; i < ml.n_tensors; ++i) {
  16004. auto weight = ml.get_weight(i);
  16005. struct ggml_tensor * tensor = weight->tensor;
  16006. if (weight->idx != cur_split && params->keep_split) {
  16007. close_ofstream();
  16008. new_ofstream(weight->idx);
  16009. }
  16010. const std::string name = ggml_get_name(tensor);
  16011. if (!ml.use_mmap) {
  16012. if (read_data.size() < ggml_nbytes(tensor)) {
  16013. read_data.resize(ggml_nbytes(tensor));
  16014. }
  16015. tensor->data = read_data.data();
  16016. }
  16017. ml.load_data_for(tensor);
  16018. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  16019. ++idx, ml.n_tensors,
  16020. ggml_get_name(tensor),
  16021. llama_format_tensor_shape(tensor).c_str(),
  16022. ggml_type_name(tensor->type));
  16023. // This used to be a regex, but <regex> has an extreme cost to compile times.
  16024. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  16025. // quantize only 2D and 3D tensors (experts)
  16026. quantize &= (ggml_n_dims(tensor) >= 2);
  16027. // do not quantize norm tensors
  16028. quantize &= name.find("_norm.weight") == std::string::npos;
  16029. quantize &= params->quantize_output_tensor || name != "output.weight";
  16030. quantize &= !params->only_copy;
  16031. // do not quantize expert gating tensors
  16032. // NOTE: can't use LLM_TN here because the layer number is not known
  16033. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  16034. // do not quantize positional embeddings and token types (BERT)
  16035. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  16036. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  16037. // do not quantize Mamba's small yet 2D weights
  16038. // NOTE: can't use LLM_TN here because the layer number is not known
  16039. quantize &= name.find("ssm_conv1d.weight") == std::string::npos;
  16040. // do not quantize RWKV's time_mix_first tensors
  16041. quantize &= name.find("time_mix_first.weight") == std::string::npos;
  16042. quantize &= name.find("time_mix_w1.weight") == std::string::npos;
  16043. quantize &= name.find("time_mix_w2.weight") == std::string::npos;
  16044. quantize &= name.find("time_mix_decay_w1.weight") == std::string::npos;
  16045. quantize &= name.find("time_mix_decay_w2.weight") == std::string::npos;
  16046. // do not quantize relative position bias (T5)
  16047. quantize &= name.find("attn_rel_b.weight") == std::string::npos;
  16048. enum ggml_type new_type;
  16049. void * new_data;
  16050. size_t new_size;
  16051. if (quantize) {
  16052. new_type = default_type;
  16053. // get more optimal quantization type based on the tensor shape, layer, etc.
  16054. if (!params->pure && ggml_is_quantized(default_type)) {
  16055. new_type = llama_tensor_get_type(qs, new_type, tensor, ftype);
  16056. }
  16057. if (params->token_embedding_type < GGML_TYPE_COUNT && strcmp(tensor->name, "token_embd.weight") == 0) {
  16058. new_type = params->token_embedding_type;
  16059. }
  16060. if (params->output_tensor_type < GGML_TYPE_COUNT && strcmp(tensor->name, "output.weight") == 0) {
  16061. new_type = params->output_tensor_type;
  16062. }
  16063. // If we've decided to quantize to the same type the tensor is already
  16064. // in then there's nothing to do.
  16065. quantize = tensor->type != new_type;
  16066. }
  16067. if (!quantize) {
  16068. new_type = tensor->type;
  16069. new_data = tensor->data;
  16070. new_size = ggml_nbytes(tensor);
  16071. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  16072. } else {
  16073. const int64_t nelements = ggml_nelements(tensor);
  16074. const float * imatrix = nullptr;
  16075. if (imatrix_data) {
  16076. auto it = imatrix_data->find(tensor->name);
  16077. if (it == imatrix_data->end()) {
  16078. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  16079. } else {
  16080. if (it->second.size() == (size_t)tensor->ne[0]*tensor->ne[2]) {
  16081. imatrix = it->second.data();
  16082. } else {
  16083. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  16084. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name);
  16085. // this can happen when quantizing an old mixtral model with split tensors with a new incompatible imatrix
  16086. // this is a significant error and it may be good idea to abort the process if this happens,
  16087. // since many people will miss the error and not realize that most of the model is being quantized without an imatrix
  16088. // tok_embd should be ignored in this case, since it always causes this warning
  16089. if (name != tn(LLM_TENSOR_TOKEN_EMBD, "weight")) {
  16090. throw std::runtime_error(format("imatrix size %d is different from tensor size %d for %s",
  16091. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name));
  16092. }
  16093. }
  16094. }
  16095. }
  16096. if ((new_type == GGML_TYPE_IQ2_XXS ||
  16097. new_type == GGML_TYPE_IQ2_XS ||
  16098. new_type == GGML_TYPE_IQ2_S ||
  16099. new_type == GGML_TYPE_IQ1_S ||
  16100. (new_type == GGML_TYPE_IQ1_M && strcmp(tensor->name, "token_embd.weight") && strcmp(tensor->name, "output.weight")) ||
  16101. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  16102. LLAMA_LOG_ERROR("\n\n============================================================\n");
  16103. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  16104. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  16105. LLAMA_LOG_ERROR("============================================================\n\n");
  16106. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  16107. }
  16108. float * f32_data;
  16109. if (tensor->type == GGML_TYPE_F32) {
  16110. f32_data = (float *) tensor->data;
  16111. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  16112. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  16113. } else {
  16114. llama_tensor_dequantize_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  16115. f32_data = (float *) f32_conv_buf.data();
  16116. }
  16117. int chunk_size_multiplier = 1;
  16118. if (new_type == GGML_TYPE_Q4_0_4_4 || new_type == GGML_TYPE_Q4_0_4_8 || new_type == GGML_TYPE_Q4_0_8_8) {
  16119. if ((new_type == GGML_TYPE_Q4_0_8_8) && (tensor->ne[1] % 8 != 0)) new_type = GGML_TYPE_Q4_0;
  16120. else if (tensor->ne[1] % 4 != 0) new_type = GGML_TYPE_Q4_0;
  16121. if (new_type == GGML_TYPE_Q4_0_8_8) chunk_size_multiplier = 8;
  16122. else if (new_type == GGML_TYPE_Q4_0_4_4 || new_type == GGML_TYPE_Q4_0_4_8) chunk_size_multiplier = 4;
  16123. }
  16124. LLAMA_LOG_INFO("converting to %s .. ", ggml_type_name(new_type));
  16125. fflush(stdout);
  16126. if (work.size() < (size_t)nelements * 4) {
  16127. work.resize(nelements * 4); // upper bound on size
  16128. }
  16129. new_data = work.data();
  16130. const int64_t n_per_row = tensor->ne[0];
  16131. const int64_t nrows = tensor->ne[1];
  16132. static const int64_t min_chunk_size = 32 * 512;
  16133. 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)) *
  16134. chunk_size_multiplier;
  16135. const int64_t nelements_matrix = tensor->ne[0] * tensor->ne[1];
  16136. const int64_t nchunk = (nelements_matrix + chunk_size - 1)/chunk_size;
  16137. const int64_t nthread_use = nthread > 1 ? std::max((int64_t)1, std::min((int64_t)nthread, nchunk)) : 1;
  16138. // quantize each expert separately since they have different importance matrices
  16139. new_size = 0;
  16140. for (int64_t i03 = 0; i03 < tensor->ne[2]; ++i03) {
  16141. const float * f32_data_03 = f32_data + i03 * nelements_matrix;
  16142. void * new_data_03 = (char *)new_data + ggml_row_size(new_type, n_per_row) * i03 * nrows;
  16143. const float * imatrix_03 = imatrix ? imatrix + i03 * n_per_row : nullptr;
  16144. 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);
  16145. }
  16146. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB\n", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  16147. }
  16148. total_size_org += ggml_nbytes(tensor);
  16149. total_size_new += new_size;
  16150. // update the gguf meta data as we go
  16151. gguf_set_tensor_type(ctx_outs[cur_split], name.c_str(), new_type);
  16152. gguf_set_tensor_data(ctx_outs[cur_split], name.c_str(), new_data, new_size);
  16153. // write tensor data + padding
  16154. fout.write((const char *) new_data, new_size);
  16155. zeros(fout, GGML_PAD(new_size, align) - new_size);
  16156. }
  16157. close_ofstream();
  16158. for (auto & c:ctx_outs) {
  16159. gguf_free(c);
  16160. }
  16161. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  16162. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  16163. if (qs.n_fallback > 0) {
  16164. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n",
  16165. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  16166. }
  16167. }
  16168. static void llama_lora_adapter_init_internal(struct llama_model * model, const char * path_lora, struct llama_lora_adapter & adapter) {
  16169. LLAMA_LOG_INFO("%s: loading lora adapter from '%s' ...\n", __func__, path_lora);
  16170. ggml_context * ctx = nullptr;
  16171. struct gguf_init_params meta_gguf_params = {
  16172. /* .no_alloc = */ true,
  16173. /* .ctx = */ &ctx,
  16174. };
  16175. struct gguf_context * ctx_gguf = gguf_init_from_file(path_lora, meta_gguf_params);
  16176. if (!ctx_gguf) {
  16177. throw std::runtime_error("failed to load lora adapter file from " + std::string(path_lora));
  16178. }
  16179. // check metadata
  16180. {
  16181. auto get_kv_str = [&](const std::string & key) -> std::string {
  16182. int id = gguf_find_key(ctx_gguf, key.c_str());
  16183. return id < 0 ? "" : std::string(gguf_get_val_str(ctx_gguf, id));
  16184. };
  16185. auto get_kv_f32 = [&](const std::string & key) -> float {
  16186. int id = gguf_find_key(ctx_gguf, key.c_str());
  16187. return id < 0 ? 0.0f : gguf_get_val_f32(ctx_gguf, id);
  16188. };
  16189. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  16190. auto general_type = get_kv_str(llm_kv(LLM_KV_GENERAL_TYPE));
  16191. if (general_type != "adapter") {
  16192. gguf_free(ctx_gguf);
  16193. throw std::runtime_error("expect general.type to be 'adapter', but got: " + general_type);
  16194. }
  16195. auto general_arch_str = get_kv_str(llm_kv(LLM_KV_GENERAL_ARCHITECTURE));
  16196. auto general_arch = llm_arch_from_string(general_arch_str);
  16197. if (general_arch != model->arch) {
  16198. gguf_free(ctx_gguf);
  16199. throw std::runtime_error("model arch and LoRA arch mismatch");
  16200. }
  16201. auto adapter_type = get_kv_str(llm_kv(LLM_KV_ADAPTER_TYPE));
  16202. if (adapter_type != "lora") {
  16203. gguf_free(ctx_gguf);
  16204. throw std::runtime_error("expect adapter.type to be 'lora', but got: " + adapter_type);
  16205. }
  16206. adapter.alpha = get_kv_f32(llm_kv(LLM_KV_ADAPTER_LORA_ALPHA));
  16207. }
  16208. int n_tensors = gguf_get_n_tensors(ctx_gguf);
  16209. // contexts for each buffer type
  16210. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  16211. auto get_ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
  16212. auto it = ctx_map.find(buft);
  16213. if (it == ctx_map.end()) {
  16214. // add a new context
  16215. struct ggml_init_params params = {
  16216. /*.mem_size =*/ n_tensors*ggml_tensor_overhead(),
  16217. /*.mem_buffer =*/ NULL,
  16218. /*.no_alloc =*/ true,
  16219. };
  16220. ggml_context * buft_ctx = ggml_init(params);
  16221. ctx_map[buft] = buft_ctx;
  16222. return buft_ctx;
  16223. };
  16224. return it->second;
  16225. };
  16226. // bundle lora_a and lora_b into pairs
  16227. std::map<std::string, llama_lora_weight> ab_map;
  16228. auto str_endswith = [](const std::string & str, const std::string & suffix) {
  16229. return str.size() >= suffix.size() && str.compare(str.size()-suffix.size(), suffix.size(), suffix) == 0;
  16230. };
  16231. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  16232. std::string name(cur->name);
  16233. if (str_endswith(name, ".lora_a")) {
  16234. replace_all(name, ".lora_a", "");
  16235. if (ab_map.find(name) == ab_map.end()) {
  16236. ab_map[name] = llama_lora_weight(cur, nullptr);
  16237. } else {
  16238. ab_map[name].a = cur;
  16239. }
  16240. } else if (str_endswith(name, ".lora_b")) {
  16241. replace_all(name, ".lora_b", "");
  16242. if (ab_map.find(name) == ab_map.end()) {
  16243. ab_map[name] = llama_lora_weight(nullptr, cur);
  16244. } else {
  16245. ab_map[name].b = cur;
  16246. }
  16247. } else {
  16248. gguf_free(ctx_gguf);
  16249. ggml_free(ctx);
  16250. throw std::runtime_error("LoRA tensor '" + name + "' has unexpected suffix");
  16251. }
  16252. }
  16253. // add tensors
  16254. for (auto & it : ab_map) {
  16255. const std::string & name = it.first;
  16256. llama_lora_weight & w = it.second;
  16257. if (!w.a || !w.b) {
  16258. gguf_free(ctx_gguf);
  16259. ggml_free(ctx);
  16260. throw std::runtime_error("LoRA tensor pair for '" + name + "' is missing one component");
  16261. }
  16262. // device buft and device ctx
  16263. auto * model_tensor = llama_get_model_tensor(model, name.c_str());
  16264. if (!model_tensor) {
  16265. gguf_free(ctx_gguf);
  16266. ggml_free(ctx);
  16267. throw std::runtime_error("LoRA tensor '" + name + "' does not exist in base model");
  16268. }
  16269. struct ggml_context * dev_ctx = get_ctx_for_buft(ggml_backend_buffer_get_type(model_tensor->buffer));
  16270. // validate tensor shape
  16271. if (model_tensor->ne[0] != w.a->ne[0] || model_tensor->ne[1] != w.b->ne[1]) {
  16272. gguf_free(ctx_gguf);
  16273. ggml_free(ctx);
  16274. throw std::runtime_error("tensor '" + name + "' has incorrect shape");
  16275. }
  16276. if (w.a->ne[1] != w.b->ne[0]) {
  16277. gguf_free(ctx_gguf);
  16278. ggml_free(ctx);
  16279. throw std::runtime_error("lora_a tensor is not transposed (hint: adapter from \"finetune\" example is no longer supported)");
  16280. }
  16281. // save tensor to adapter
  16282. struct ggml_tensor * tensor_a = ggml_dup_tensor(dev_ctx, w.a);
  16283. struct ggml_tensor * tensor_b = ggml_dup_tensor(dev_ctx, w.b);
  16284. ggml_set_name(tensor_a, w.a->name);
  16285. ggml_set_name(tensor_b, w.b->name);
  16286. adapter.ab_map[name] = llama_lora_weight(tensor_a, tensor_b);
  16287. }
  16288. // allocate tensors / buffers and zero
  16289. {
  16290. adapter.ctxs.reserve(ctx_map.size());
  16291. adapter.bufs.reserve(ctx_map.size());
  16292. for (auto it : ctx_map) {
  16293. ggml_backend_buffer_type_t buft = it.first;
  16294. ggml_context * ctx_dev = it.second;
  16295. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx_dev, buft);
  16296. if (!buf) {
  16297. gguf_free(ctx_gguf);
  16298. ggml_free(ctx);
  16299. throw std::runtime_error("failed to allocate buffer for lora adapter\n");
  16300. }
  16301. LLAMA_LOG_INFO("%s: %10s LoRA buffer size = %8.2f MiB\n", __func__, ggml_backend_buffer_name(buf), ggml_backend_buffer_get_size(buf)/1024.0/1024.0);
  16302. adapter.ctxs.push_back(ctx_dev);
  16303. adapter.bufs.push_back(buf);
  16304. }
  16305. }
  16306. // set tensor data
  16307. {
  16308. llama_file gguf_file(path_lora, "rb");
  16309. std::vector<uint8_t> read_buf;
  16310. auto set_tensor = [&](struct ggml_tensor * orig, struct ggml_tensor * dev) {
  16311. size_t offs = gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, gguf_find_tensor(ctx_gguf, orig->name));
  16312. size_t size = ggml_nbytes(orig);
  16313. read_buf.resize(size);
  16314. gguf_file.seek(offs, SEEK_SET);
  16315. gguf_file.read_raw(read_buf.data(), size);
  16316. ggml_backend_tensor_set(dev, read_buf.data(), 0, size);
  16317. };
  16318. for (auto & it : adapter.ab_map) {
  16319. auto orig = ab_map[it.first];
  16320. auto dev = it.second;
  16321. set_tensor(orig.a, dev.a);
  16322. set_tensor(orig.b, dev.b);
  16323. }
  16324. }
  16325. LLAMA_LOG_INFO("%s: loaded %ld tensors from lora file\n", __func__, adapter.ab_map.size()*2);
  16326. // free ctx for reading gguf
  16327. gguf_free(ctx_gguf);
  16328. ggml_free(ctx);
  16329. }
  16330. int32_t llama_lora_adapter_set(
  16331. struct llama_context * ctx,
  16332. struct llama_lora_adapter * adapter,
  16333. float scale) {
  16334. if (ctx->cparams.flash_attn) {
  16335. LLAMA_LOG_ERROR("%s: flash_attn is not compatible with LoRA\n", __func__);
  16336. return -1;
  16337. }
  16338. ctx->lora_adapters[adapter] = scale;
  16339. return 0;
  16340. }
  16341. int32_t llama_lora_adapter_remove(
  16342. struct llama_context * ctx,
  16343. struct llama_lora_adapter * adapter) {
  16344. auto pos = ctx->lora_adapters.find(adapter);
  16345. if (pos != ctx->lora_adapters.end()) {
  16346. ctx->lora_adapters.erase(pos);
  16347. return 0;
  16348. }
  16349. return -1;
  16350. }
  16351. void llama_lora_adapter_clear(struct llama_context * ctx) {
  16352. ctx->lora_adapters.clear();
  16353. }
  16354. void llama_lora_adapter_free(struct llama_lora_adapter * adapter) {
  16355. delete adapter;
  16356. }
  16357. //
  16358. // interface implementation
  16359. //
  16360. struct llama_model_params llama_model_default_params() {
  16361. struct llama_model_params result = {
  16362. /*.n_gpu_layers =*/ 0,
  16363. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  16364. /*.main_gpu =*/ 0,
  16365. /*.tensor_split =*/ nullptr,
  16366. /*.rpc_servers =*/ nullptr,
  16367. /*.progress_callback =*/ nullptr,
  16368. /*.progress_callback_user_data =*/ nullptr,
  16369. /*.kv_overrides =*/ nullptr,
  16370. /*.vocab_only =*/ false,
  16371. /*.use_mmap =*/ true,
  16372. /*.use_mlock =*/ false,
  16373. /*.check_tensors =*/ false,
  16374. };
  16375. #ifdef GGML_USE_METAL
  16376. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  16377. result.n_gpu_layers = 999;
  16378. #endif
  16379. return result;
  16380. }
  16381. struct llama_context_params llama_context_default_params() {
  16382. struct llama_context_params result = {
  16383. /*.n_ctx =*/ 512,
  16384. /*.n_batch =*/ 2048,
  16385. /*.n_ubatch =*/ 512,
  16386. /*.n_seq_max =*/ 1,
  16387. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  16388. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  16389. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  16390. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  16391. /*.attention_type =*/ LLAMA_ATTENTION_TYPE_UNSPECIFIED,
  16392. /*.rope_freq_base =*/ 0.0f,
  16393. /*.rope_freq_scale =*/ 0.0f,
  16394. /*.yarn_ext_factor =*/ -1.0f,
  16395. /*.yarn_attn_factor =*/ 1.0f,
  16396. /*.yarn_beta_fast =*/ 32.0f,
  16397. /*.yarn_beta_slow =*/ 1.0f,
  16398. /*.yarn_orig_ctx =*/ 0,
  16399. /*.defrag_thold =*/ -1.0f,
  16400. /*.cb_eval =*/ nullptr,
  16401. /*.cb_eval_user_data =*/ nullptr,
  16402. /*.type_k =*/ GGML_TYPE_F16,
  16403. /*.type_v =*/ GGML_TYPE_F16,
  16404. /*.logits_all =*/ false,
  16405. /*.embeddings =*/ false,
  16406. /*.offload_kqv =*/ true,
  16407. /*.flash_attn =*/ false,
  16408. /*.no_perf =*/ true,
  16409. /*.abort_callback =*/ nullptr,
  16410. /*.abort_callback_data =*/ nullptr,
  16411. };
  16412. return result;
  16413. }
  16414. struct llama_sampler_chain_params llama_sampler_chain_default_params() {
  16415. struct llama_sampler_chain_params result = {
  16416. /*.no_perf =*/ true,
  16417. };
  16418. return result;
  16419. }
  16420. struct llama_model_quantize_params llama_model_quantize_default_params() {
  16421. struct llama_model_quantize_params result = {
  16422. /*.nthread =*/ 0,
  16423. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  16424. /*.output_tensor_type =*/ GGML_TYPE_COUNT,
  16425. /*.token_embedding_type =*/ GGML_TYPE_COUNT,
  16426. /*.allow_requantize =*/ false,
  16427. /*.quantize_output_tensor =*/ true,
  16428. /*.only_copy =*/ false,
  16429. /*.pure =*/ false,
  16430. /*.keep_split =*/ false,
  16431. /*.imatrix =*/ nullptr,
  16432. /*.kv_overrides =*/ nullptr,
  16433. };
  16434. return result;
  16435. }
  16436. size_t llama_max_devices(void) {
  16437. #if defined(GGML_USE_RPC)
  16438. return GGML_RPC_MAX_SERVERS;
  16439. #elif defined(GGML_USE_METAL)
  16440. return 1;
  16441. #elif defined(GGML_USE_CUDA)
  16442. return GGML_CUDA_MAX_DEVICES;
  16443. #elif defined(GGML_USE_SYCL)
  16444. return GGML_SYCL_MAX_DEVICES;
  16445. #elif defined(GGML_USE_VULKAN)
  16446. return GGML_VK_MAX_DEVICES;
  16447. #elif defined(GGML_USE_CANN)
  16448. return GGML_CANN_MAX_DEVICES;
  16449. #else
  16450. return 1;
  16451. #endif
  16452. }
  16453. bool llama_supports_mmap(void) {
  16454. return llama_mmap::SUPPORTED;
  16455. }
  16456. bool llama_supports_mlock(void) {
  16457. return llama_mlock::SUPPORTED;
  16458. }
  16459. bool llama_supports_gpu_offload(void) {
  16460. #if defined(GGML_USE_CUDA) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  16461. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE) || defined(GGML_USE_RPC)
  16462. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  16463. return true;
  16464. #else
  16465. return false;
  16466. #endif
  16467. }
  16468. void llama_backend_init(void) {
  16469. ggml_time_init();
  16470. // needed to initialize f16 tables
  16471. {
  16472. struct ggml_init_params params = { 0, NULL, false };
  16473. struct ggml_context * ctx = ggml_init(params);
  16474. ggml_free(ctx);
  16475. }
  16476. }
  16477. void llama_numa_init(enum ggml_numa_strategy numa) {
  16478. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  16479. ggml_numa_init(numa);
  16480. }
  16481. }
  16482. void llama_attach_threadpool(
  16483. struct llama_context * ctx,
  16484. ggml_threadpool_t threadpool,
  16485. ggml_threadpool_t threadpool_batch) {
  16486. ctx->threadpool = threadpool;
  16487. ctx->threadpool_batch = threadpool_batch ? threadpool_batch : threadpool;
  16488. }
  16489. void llama_detach_threadpool(struct llama_context * ctx) {
  16490. ctx->threadpool = nullptr;
  16491. ctx->threadpool_batch = nullptr;
  16492. }
  16493. void llama_backend_free(void) {
  16494. ggml_quantize_free();
  16495. }
  16496. int64_t llama_time_us(void) {
  16497. return ggml_time_us();
  16498. }
  16499. struct llama_model * llama_load_model_from_file(
  16500. const char * path_model,
  16501. struct llama_model_params params) {
  16502. ggml_time_init();
  16503. llama_model * model = new llama_model;
  16504. unsigned cur_percentage = 0;
  16505. if (params.progress_callback == NULL) {
  16506. params.progress_callback_user_data = &cur_percentage;
  16507. params.progress_callback = [](float progress, void * ctx) {
  16508. unsigned * cur_percentage_p = (unsigned *) ctx;
  16509. unsigned percentage = (unsigned) (100 * progress);
  16510. while (percentage > *cur_percentage_p) {
  16511. *cur_percentage_p = percentage;
  16512. LLAMA_LOG_CONT(".");
  16513. if (percentage >= 100) {
  16514. LLAMA_LOG_CONT("\n");
  16515. }
  16516. }
  16517. return true;
  16518. };
  16519. }
  16520. if (params.rpc_servers != nullptr && params.rpc_servers[0] != '\0') {
  16521. // split the servers set them into model->rpc_servers
  16522. std::string servers(params.rpc_servers);
  16523. size_t pos = 0;
  16524. while ((pos = servers.find(",")) != std::string::npos) {
  16525. std::string server = servers.substr(0, pos);
  16526. model->rpc_servers.push_back(server);
  16527. servers.erase(0, pos + 1);
  16528. }
  16529. model->rpc_servers.push_back(servers);
  16530. }
  16531. int status = llama_model_load(path_model, *model, params);
  16532. GGML_ASSERT(status <= 0);
  16533. if (status < 0) {
  16534. if (status == -1) {
  16535. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  16536. } else if (status == -2) {
  16537. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  16538. }
  16539. delete model;
  16540. return nullptr;
  16541. }
  16542. return model;
  16543. }
  16544. void llama_free_model(struct llama_model * model) {
  16545. delete model;
  16546. }
  16547. struct llama_context * llama_new_context_with_model(
  16548. struct llama_model * model,
  16549. struct llama_context_params params) {
  16550. if (!model) {
  16551. LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
  16552. return nullptr;
  16553. }
  16554. if (params.n_batch == 0 && params.n_ubatch == 0) {
  16555. LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
  16556. return nullptr;
  16557. }
  16558. if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
  16559. LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
  16560. return nullptr;
  16561. }
  16562. if (params.flash_attn && model->arch == LLM_ARCH_GROK) {
  16563. LLAMA_LOG_WARN("%s: flash_attn is not compatible with Grok - forcing off\n", __func__);
  16564. params.flash_attn = false;
  16565. }
  16566. if (params.flash_attn && model->hparams.n_embd_head_k != model->hparams.n_embd_head_v) {
  16567. LLAMA_LOG_WARN("%s: flash_attn requires n_embd_head_k == n_embd_head_v - forcing off\n", __func__);
  16568. params.flash_attn = false;
  16569. }
  16570. if (params.type_v != GGML_TYPE_F16 && !params.flash_attn) {
  16571. LLAMA_LOG_ERROR("%s: V cache quantization requires flash_attn\n", __func__);
  16572. return nullptr;
  16573. }
  16574. llama_context * ctx = new llama_context(*model);
  16575. const auto & hparams = model->hparams;
  16576. auto & cparams = ctx->cparams;
  16577. cparams.n_seq_max = std::max(1u, params.n_seq_max);
  16578. cparams.n_threads = params.n_threads;
  16579. cparams.n_threads_batch = params.n_threads_batch;
  16580. cparams.yarn_ext_factor = params.yarn_ext_factor;
  16581. cparams.yarn_attn_factor = params.yarn_attn_factor;
  16582. cparams.yarn_beta_fast = params.yarn_beta_fast;
  16583. cparams.yarn_beta_slow = params.yarn_beta_slow;
  16584. cparams.defrag_thold = params.defrag_thold;
  16585. cparams.embeddings = params.embeddings;
  16586. cparams.offload_kqv = params.offload_kqv;
  16587. cparams.flash_attn = params.flash_attn;
  16588. cparams.no_perf = params.no_perf;
  16589. cparams.pooling_type = params.pooling_type;
  16590. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  16591. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  16592. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  16593. // this is necessary due to kv_self.n being padded later during inference
  16594. cparams.n_ctx = GGML_PAD(cparams.n_ctx, llama_kv_cache_get_padding(cparams));
  16595. // with causal attention, the batch size is limited by the context size
  16596. cparams.n_batch = hparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
  16597. // the batch has to be at least GGML_KQ_MASK_PAD because we will be padding the KQ_mask
  16598. // this is required by GPU kernels in order to avoid out-of-bounds accesses (e.g. ggml_flash_attn_ext)
  16599. // ref: https://github.com/ggerganov/llama.cpp/pull/5021
  16600. if (cparams.n_batch < GGML_KQ_MASK_PAD) {
  16601. LLAMA_LOG_WARN("%s: n_batch is less than GGML_KQ_MASK_PAD - increasing to %d\n", __func__, GGML_KQ_MASK_PAD);
  16602. cparams.n_batch = GGML_KQ_MASK_PAD;
  16603. }
  16604. cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
  16605. cparams.n_ctx_orig_yarn = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  16606. hparams.n_ctx_orig_yarn != 0 ? hparams.n_ctx_orig_yarn :
  16607. hparams.n_ctx_train;
  16608. cparams.cb_eval = params.cb_eval;
  16609. cparams.cb_eval_user_data = params.cb_eval_user_data;
  16610. auto rope_scaling_type = params.rope_scaling_type;
  16611. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  16612. rope_scaling_type = hparams.rope_scaling_type_train;
  16613. }
  16614. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  16615. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  16616. }
  16617. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  16618. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  16619. }
  16620. cparams.yarn_attn_factor *= hparams.rope_attn_factor;
  16621. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  16622. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  16623. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  16624. } else {
  16625. cparams.pooling_type = hparams.pooling_type;
  16626. }
  16627. }
  16628. if (params.attention_type == LLAMA_ATTENTION_TYPE_UNSPECIFIED) {
  16629. cparams.causal_attn = hparams.causal_attn;
  16630. } else {
  16631. cparams.causal_attn = params.attention_type == LLAMA_ATTENTION_TYPE_CAUSAL;
  16632. }
  16633. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  16634. LLAMA_LOG_INFO("%s: n_batch = %u\n", __func__, cparams.n_batch);
  16635. LLAMA_LOG_INFO("%s: n_ubatch = %u\n", __func__, cparams.n_ubatch);
  16636. LLAMA_LOG_INFO("%s: flash_attn = %d\n", __func__, cparams.flash_attn);
  16637. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  16638. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  16639. ctx->abort_callback = params.abort_callback;
  16640. ctx->abort_callback_data = params.abort_callback_data;
  16641. ctx->logits_all = params.logits_all;
  16642. // build worst-case graph for encoder if a model contains encoder
  16643. ctx->is_encoding = llama_model_has_encoder(model);
  16644. uint32_t kv_size = cparams.n_ctx;
  16645. ggml_type type_k = params.type_k;
  16646. ggml_type type_v = params.type_v;
  16647. // Mamba only needs a constant number of KV cache cells per sequence
  16648. if (llama_model_is_recurrent(model)) {
  16649. // Mamba needs at least as many KV cells as there are sequences kept at any time
  16650. kv_size = std::max((uint32_t) 1, params.n_seq_max);
  16651. // it's probably best to keep as much precision as possible for the states
  16652. type_k = GGML_TYPE_F32; // required by ggml_ssm_conv for Mamba's conv_states
  16653. type_v = GGML_TYPE_F32; // required by ggml_ssm_scan for Mamba's ssm_states
  16654. }
  16655. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  16656. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  16657. if (!hparams.vocab_only) {
  16658. // initialize backends
  16659. #if defined(GGML_USE_RPC)
  16660. if (model->n_gpu_layers > 0) {
  16661. for (const auto & endpoint : model->rpc_servers) {
  16662. ggml_backend_t backend = ggml_backend_rpc_init(endpoint.c_str());
  16663. if (backend == nullptr) {
  16664. LLAMA_LOG_ERROR("%s: failed to initialize RPC to '%s'\n", __func__, endpoint.c_str());
  16665. llama_free(ctx);
  16666. return nullptr;
  16667. }
  16668. ctx->backends.push_back(backend);
  16669. }
  16670. }
  16671. #endif
  16672. #if defined(GGML_USE_METAL)
  16673. if (model->n_gpu_layers > 0) {
  16674. ctx->backend_metal = ggml_backend_metal_init();
  16675. if (ctx->backend_metal == nullptr) {
  16676. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  16677. llama_free(ctx);
  16678. return nullptr;
  16679. }
  16680. ctx->backends.push_back(ctx->backend_metal);
  16681. }
  16682. #elif defined(GGML_USE_CUDA)
  16683. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  16684. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  16685. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  16686. if (backend == nullptr) {
  16687. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  16688. llama_free(ctx);
  16689. return nullptr;
  16690. }
  16691. ctx->backends.push_back(backend);
  16692. } else {
  16693. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  16694. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  16695. ggml_backend_t backend = ggml_backend_cuda_init(device);
  16696. if (backend == nullptr) {
  16697. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  16698. llama_free(ctx);
  16699. return nullptr;
  16700. }
  16701. ctx->backends.push_back(backend);
  16702. }
  16703. }
  16704. #elif defined(GGML_USE_VULKAN)
  16705. if (model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  16706. LLAMA_LOG_ERROR("%s: Row split not supported. Failed to initialize Vulkan backend\n", __func__);
  16707. llama_free(ctx);
  16708. return nullptr;
  16709. }
  16710. if (model->split_mode == LLAMA_SPLIT_MODE_NONE) {
  16711. ggml_backend_t backend = ggml_backend_vk_init(model->main_gpu);
  16712. if (backend == nullptr) {
  16713. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan backend\n", __func__);
  16714. llama_free(ctx);
  16715. return nullptr;
  16716. }
  16717. ctx->backends.push_back(backend);
  16718. } else {
  16719. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  16720. ggml_backend_t backend = ggml_backend_vk_init(device);
  16721. if (backend == nullptr) {
  16722. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  16723. llama_free(ctx);
  16724. return nullptr;
  16725. }
  16726. ctx->backends.push_back(backend);
  16727. }
  16728. }
  16729. #elif defined(GGML_USE_SYCL)
  16730. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  16731. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  16732. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  16733. if (backend == nullptr) {
  16734. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d backend\n", __func__, model->main_gpu);
  16735. llama_free(ctx);
  16736. return nullptr;
  16737. }
  16738. ctx->backends.push_back(backend);
  16739. } else {
  16740. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  16741. for (int i = 0; i < ggml_backend_sycl_get_device_count(); ++i) {
  16742. ggml_backend_t backend = ggml_backend_sycl_init(i);
  16743. if (backend == nullptr) {
  16744. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d for No.%d backend\n", __func__, i, i);
  16745. llama_free(ctx);
  16746. return nullptr;
  16747. }
  16748. ctx->backends.push_back(backend);
  16749. }
  16750. }
  16751. #elif defined(GGML_USE_KOMPUTE)
  16752. if (model->n_gpu_layers > 0) {
  16753. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  16754. if (backend == nullptr) {
  16755. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  16756. llama_free(ctx);
  16757. return nullptr;
  16758. }
  16759. ctx->backends.push_back(backend);
  16760. }
  16761. #elif defined(GGML_USE_CANN)
  16762. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  16763. // TODO: ggml_backend_cann is not support split tensor now, just leave code here.
  16764. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  16765. ggml_backend_t backend = ggml_backend_cann_init(model->main_gpu);
  16766. if (backend == nullptr) {
  16767. LLAMA_LOG_ERROR("%s: failed to initialize CANN%d backend\n", __func__, model->main_gpu);
  16768. llama_free(ctx);
  16769. return nullptr;
  16770. }
  16771. ctx->backends.push_back(backend);
  16772. } else {
  16773. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  16774. // TODO: currently, CANN can't use multi-gpus, just leave code here for further cann version.
  16775. for (int32_t device = 0; device < ggml_backend_cann_get_device_count(); ++device) {
  16776. ggml_backend_t backend = ggml_backend_cann_init(device);
  16777. if (backend == nullptr) {
  16778. LLAMA_LOG_ERROR("%s: failed to initialize CANN%d backend\n", __func__, device);
  16779. llama_free(ctx);
  16780. return nullptr;
  16781. }
  16782. ctx->backends.push_back(backend);
  16783. }
  16784. }
  16785. #endif
  16786. #ifdef GGML_USE_BLAS
  16787. ctx->backend_blas = ggml_backend_blas_init();
  16788. if (ctx->backend_blas == nullptr) {
  16789. LLAMA_LOG_WARN("%s: failed to initialize BLAS backend\n", __func__);
  16790. } else {
  16791. ctx->backends.push_back(ctx->backend_blas);
  16792. }
  16793. #endif
  16794. ctx->backend_cpu = ggml_backend_cpu_init();
  16795. if (ctx->backend_cpu == nullptr) {
  16796. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  16797. llama_free(ctx);
  16798. return nullptr;
  16799. }
  16800. ctx->backends.push_back(ctx->backend_cpu);
  16801. if (!llama_kv_cache_init(ctx->kv_self, ctx, type_k, type_v, kv_size, cparams.offload_kqv)) {
  16802. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  16803. llama_free(ctx);
  16804. return nullptr;
  16805. }
  16806. {
  16807. size_t memory_size_k = 0;
  16808. size_t memory_size_v = 0;
  16809. for (auto & k : ctx->kv_self.k_l) {
  16810. memory_size_k += ggml_nbytes(k);
  16811. }
  16812. for (auto & v : ctx->kv_self.v_l) {
  16813. memory_size_v += ggml_nbytes(v);
  16814. }
  16815. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  16816. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  16817. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  16818. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  16819. }
  16820. // graph outputs buffer
  16821. {
  16822. // resized during inference when a batch uses more outputs
  16823. if (llama_output_reserve(*ctx, params.n_seq_max) < params.n_seq_max) {
  16824. LLAMA_LOG_ERROR("%s: failed to reserve initial output buffer\n", __func__);
  16825. llama_free(ctx);
  16826. return nullptr;
  16827. }
  16828. LLAMA_LOG_INFO("%s: %10s output buffer size = %8.2f MiB\n", __func__,
  16829. ggml_backend_buffer_name(ctx->buf_output),
  16830. ggml_backend_buffer_get_size(ctx->buf_output) / 1024.0 / 1024.0);
  16831. }
  16832. // scheduler and compute buffers
  16833. {
  16834. // buffer types used for the compute buffer of each backend
  16835. std::vector<ggml_backend_buffer_type_t> backend_buft;
  16836. for (auto * backend : ctx->backends) {
  16837. if (ggml_backend_is_cpu(backend)) {
  16838. // use host buffers for the CPU backend compute buffer
  16839. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  16840. } else {
  16841. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  16842. }
  16843. }
  16844. const size_t max_nodes = llama_model_max_nodes(*model);
  16845. // buffer used to store the computation graph and the tensor meta data
  16846. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*max_nodes + ggml_graph_overhead_custom(max_nodes, false));
  16847. // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
  16848. bool pipeline_parallel =
  16849. llama_get_device_count(*model) > 1 &&
  16850. model->n_gpu_layers > (int)model->hparams.n_layer &&
  16851. model->split_mode == LLAMA_SPLIT_MODE_LAYER &&
  16852. params.offload_kqv;
  16853. #ifndef GGML_USE_CUDA
  16854. // pipeline parallelism requires support for async compute and events
  16855. // currently this is only implemented in the CUDA backend
  16856. pipeline_parallel = false;
  16857. #endif
  16858. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), max_nodes, pipeline_parallel);
  16859. if (pipeline_parallel) {
  16860. LLAMA_LOG_INFO("%s: pipeline parallelism enabled (n_copies=%d)\n", __func__, ggml_backend_sched_get_n_copies(ctx->sched));
  16861. }
  16862. // build worst-case graph
  16863. uint32_t n_seqs = 1; // TODO: worst-case number of sequences
  16864. uint32_t n_tokens = std::min(cparams.n_ctx, cparams.n_ubatch);
  16865. 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
  16866. llama_ubatch ubatch = { true, n_tokens, n_tokens / n_seqs, n_seqs, &token, nullptr, nullptr, nullptr, nullptr, nullptr};
  16867. ggml_cgraph * gf = llama_build_graph(*ctx, ubatch, true);
  16868. // initialize scheduler with the worst-case graph
  16869. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  16870. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  16871. llama_free(ctx);
  16872. return nullptr;
  16873. }
  16874. for (size_t i = 0; i < ctx->backends.size(); i++) {
  16875. ggml_backend_t backend = ctx->backends[i];
  16876. ggml_backend_buffer_type_t buft = backend_buft[i];
  16877. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  16878. if (size > 1) {
  16879. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  16880. ggml_backend_buft_name(buft),
  16881. size / 1024.0 / 1024.0);
  16882. }
  16883. }
  16884. // note: the number of splits during measure is higher than during inference due to the kv shift
  16885. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  16886. LLAMA_LOG_INFO("%s: graph nodes = %d\n", __func__, ggml_graph_n_nodes(gf));
  16887. LLAMA_LOG_INFO("%s: graph splits = %d\n", __func__, n_splits);
  16888. }
  16889. }
  16890. return ctx;
  16891. }
  16892. void llama_set_cross_attn_state(struct llama_context * ctx, float * cross_attn_state) {
  16893. ctx->cross_attn_state_first_pass = true;
  16894. ctx->cross_attn_state = cross_attn_state;
  16895. }
  16896. void llama_free(struct llama_context * ctx) {
  16897. delete ctx;
  16898. }
  16899. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  16900. return ctx->cparams.n_ctx;
  16901. }
  16902. uint32_t llama_n_batch(const struct llama_context * ctx) {
  16903. return ctx->cparams.n_batch;
  16904. }
  16905. uint32_t llama_n_ubatch(const struct llama_context * ctx) {
  16906. return ctx->cparams.n_ubatch;
  16907. }
  16908. uint32_t llama_n_seq_max(const struct llama_context * ctx) {
  16909. return ctx->kv_self.size;
  16910. }
  16911. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  16912. return model->vocab.type;
  16913. }
  16914. int32_t llama_n_vocab(const struct llama_model * model) {
  16915. return model->hparams.n_vocab;
  16916. }
  16917. int32_t llama_n_ctx_train(const struct llama_model * model) {
  16918. return model->hparams.n_ctx_train;
  16919. }
  16920. int32_t llama_n_embd(const struct llama_model * model) {
  16921. return model->hparams.n_embd;
  16922. }
  16923. int32_t llama_n_layer(const struct llama_model * model) {
  16924. return model->hparams.n_layer;
  16925. }
  16926. int32_t llama_n_head(const struct llama_model * model) {
  16927. return model->hparams.n_head();
  16928. }
  16929. const struct llama_model * llama_get_model(const struct llama_context * ctx) {
  16930. return &ctx->model;
  16931. }
  16932. enum llama_pooling_type llama_pooling_type(const struct llama_context * ctx) {
  16933. return ctx->cparams.pooling_type;
  16934. }
  16935. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  16936. switch (model->arch) {
  16937. // these models do not use RoPE
  16938. case LLM_ARCH_GPT2:
  16939. case LLM_ARCH_GPTJ:
  16940. case LLM_ARCH_MPT:
  16941. case LLM_ARCH_REFACT:
  16942. case LLM_ARCH_BLOOM:
  16943. case LLM_ARCH_MAMBA:
  16944. case LLM_ARCH_JINA_BERT_V2:
  16945. case LLM_ARCH_T5:
  16946. case LLM_ARCH_T5ENCODER:
  16947. case LLM_ARCH_JAIS:
  16948. case LLM_ARCH_RWKV6:
  16949. return LLAMA_ROPE_TYPE_NONE;
  16950. // use what we call a normal RoPE, operating on pairs of consecutive head values
  16951. case LLM_ARCH_LLAMA:
  16952. case LLM_ARCH_MLLAMA:
  16953. case LLM_ARCH_BAICHUAN:
  16954. case LLM_ARCH_STARCODER:
  16955. case LLM_ARCH_PLAMO:
  16956. case LLM_ARCH_ORION:
  16957. case LLM_ARCH_INTERNLM2:
  16958. case LLM_ARCH_MINICPM:
  16959. case LLM_ARCH_XVERSE:
  16960. case LLM_ARCH_COMMAND_R:
  16961. case LLM_ARCH_OLMO:
  16962. case LLM_ARCH_ARCTIC:
  16963. case LLM_ARCH_DEEPSEEK2:
  16964. case LLM_ARCH_CHATGLM:
  16965. case LLM_ARCH_GRANITE:
  16966. case LLM_ARCH_GRANITE_MOE:
  16967. case LLM_ARCH_CHAMELEON:
  16968. case LLM_ARCH_SOLAR:
  16969. return LLAMA_ROPE_TYPE_NORM;
  16970. // the pairs of head values are offset by n_rot/2
  16971. case LLM_ARCH_FALCON:
  16972. case LLM_ARCH_GROK:
  16973. case LLM_ARCH_DBRX:
  16974. case LLM_ARCH_BERT:
  16975. case LLM_ARCH_NOMIC_BERT:
  16976. case LLM_ARCH_STABLELM:
  16977. case LLM_ARCH_BITNET:
  16978. case LLM_ARCH_QWEN:
  16979. case LLM_ARCH_QWEN2:
  16980. case LLM_ARCH_QWEN2MOE:
  16981. case LLM_ARCH_OLMOE:
  16982. case LLM_ARCH_PHI2:
  16983. case LLM_ARCH_PHI3:
  16984. case LLM_ARCH_GEMMA:
  16985. case LLM_ARCH_GEMMA2:
  16986. case LLM_ARCH_STARCODER2:
  16987. case LLM_ARCH_OPENELM:
  16988. case LLM_ARCH_GPTNEOX:
  16989. case LLM_ARCH_CODESHELL:
  16990. case LLM_ARCH_NEMOTRON:
  16991. case LLM_ARCH_EXAONE:
  16992. case LLM_ARCH_MINICPM3:
  16993. return LLAMA_ROPE_TYPE_NEOX;
  16994. // all model arches should be listed explicitly here
  16995. case LLM_ARCH_UNKNOWN:
  16996. GGML_ABORT("unknown architecture");
  16997. }
  16998. return LLAMA_ROPE_TYPE_NONE;
  16999. }
  17000. float llama_rope_freq_scale_train(const struct llama_model * model) {
  17001. return model->hparams.rope_freq_scale_train;
  17002. }
  17003. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  17004. const auto & it = model->gguf_kv.find(key);
  17005. if (it == model->gguf_kv.end()) {
  17006. if (buf_size > 0) {
  17007. buf[0] = '\0';
  17008. }
  17009. return -1;
  17010. }
  17011. return snprintf(buf, buf_size, "%s", it->second.c_str());
  17012. }
  17013. int32_t llama_model_meta_count(const struct llama_model * model) {
  17014. return (int)model->gguf_kv.size();
  17015. }
  17016. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  17017. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  17018. if (buf_size > 0) {
  17019. buf[0] = '\0';
  17020. }
  17021. return -1;
  17022. }
  17023. auto it = model->gguf_kv.begin();
  17024. std::advance(it, i);
  17025. return snprintf(buf, buf_size, "%s", it->first.c_str());
  17026. }
  17027. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  17028. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  17029. if (buf_size > 0) {
  17030. buf[0] = '\0';
  17031. }
  17032. return -1;
  17033. }
  17034. auto it = model->gguf_kv.begin();
  17035. std::advance(it, i);
  17036. return snprintf(buf, buf_size, "%s", it->second.c_str());
  17037. }
  17038. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  17039. return snprintf(buf, buf_size, "%s %s %s",
  17040. llama_model_arch_name(model->arch),
  17041. llama_model_type_name(model->type),
  17042. llama_model_ftype_name(model->ftype).c_str());
  17043. }
  17044. uint64_t llama_model_size(const struct llama_model * model) {
  17045. uint64_t size = 0;
  17046. for (const auto & it : model->tensors_by_name) {
  17047. size += ggml_nbytes(it.second);
  17048. }
  17049. return size;
  17050. }
  17051. uint64_t llama_model_n_params(const struct llama_model * model) {
  17052. uint64_t nparams = 0;
  17053. for (const auto & it : model->tensors_by_name) {
  17054. nparams += ggml_nelements(it.second);
  17055. }
  17056. return nparams;
  17057. }
  17058. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  17059. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  17060. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  17061. return it.first == name;
  17062. });
  17063. if (it == model->tensors_by_name.end()) {
  17064. return nullptr;
  17065. }
  17066. return it->second;
  17067. }
  17068. bool llama_model_has_encoder(const struct llama_model * model) {
  17069. switch (model->arch) {
  17070. case LLM_ARCH_T5: return true;
  17071. case LLM_ARCH_T5ENCODER: return true;
  17072. default: return false;
  17073. }
  17074. }
  17075. bool llama_model_has_decoder(const struct llama_model * model) {
  17076. switch (model->arch) {
  17077. case LLM_ARCH_T5ENCODER: return false;
  17078. default: return true;
  17079. }
  17080. }
  17081. llama_token llama_model_decoder_start_token(const struct llama_model * model) {
  17082. return model->hparams.dec_start_token_id;
  17083. }
  17084. bool llama_model_is_recurrent(const struct llama_model * model) {
  17085. switch (model->arch) {
  17086. case LLM_ARCH_MAMBA: return true;
  17087. case LLM_ARCH_RWKV6: return true;
  17088. default: return false;
  17089. }
  17090. }
  17091. uint32_t llama_model_quantize(
  17092. const char * fname_inp,
  17093. const char * fname_out,
  17094. const llama_model_quantize_params * params) {
  17095. try {
  17096. llama_model_quantize_internal(fname_inp, fname_out, params);
  17097. return 0;
  17098. } catch (const std::exception & err) {
  17099. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  17100. return 1;
  17101. }
  17102. }
  17103. struct llama_lora_adapter * llama_lora_adapter_init(struct llama_model * model, const char * path_lora) {
  17104. try {
  17105. struct llama_lora_adapter * adapter = new llama_lora_adapter(model);
  17106. llama_lora_adapter_init_internal(model, path_lora, *adapter);
  17107. return adapter;
  17108. } catch (const std::exception & err) {
  17109. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  17110. return nullptr;
  17111. }
  17112. }
  17113. static bool llama_control_vector_init(struct llama_control_vector & cvec, const llama_model & model) {
  17114. GGML_ASSERT(cvec.tensors.empty());
  17115. GGML_ASSERT(cvec.ctxs.empty());
  17116. GGML_ASSERT(cvec.bufs.empty());
  17117. // count layer buffer types
  17118. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  17119. for (int64_t i = 0; i < model.hparams.n_layer; i++) {
  17120. buft_layer_count[model.buft_layer[i].buft]++;
  17121. }
  17122. // allocate contexts
  17123. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  17124. for (auto & it : buft_layer_count) {
  17125. int n_layers = it.second;
  17126. struct ggml_init_params params = {
  17127. /*.mem_size =*/ n_layers * ggml_tensor_overhead(),
  17128. /*.mem_buffer =*/ NULL,
  17129. /*.no_alloc =*/ true,
  17130. };
  17131. ggml_context * ctx = ggml_init(params);
  17132. if (!ctx) {
  17133. LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
  17134. return 1;
  17135. }
  17136. ctx_map[it.first] = ctx;
  17137. }
  17138. // make tensors
  17139. cvec.tensors.reserve(model.hparams.n_layer);
  17140. cvec.tensors.push_back(nullptr); // there's never a tensor for layer 0
  17141. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  17142. struct ggml_context * ctx = ctx_map.at(model.buft_layer[il].buft);
  17143. ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_embd);
  17144. cvec.tensors.push_back(tensor);
  17145. }
  17146. // allocate tensors / buffers and zero
  17147. cvec.ctxs.reserve(ctx_map.size());
  17148. cvec.bufs.reserve(ctx_map.size());
  17149. for (auto it : ctx_map) {
  17150. ggml_backend_buffer_type_t buft = it.first;
  17151. ggml_context * ctx = it.second;
  17152. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  17153. if (!buf) {
  17154. LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
  17155. return false;
  17156. }
  17157. ggml_backend_buffer_clear(buf, 0);
  17158. cvec.ctxs.push_back(ctx);
  17159. cvec.bufs.push_back(buf);
  17160. }
  17161. return true;
  17162. }
  17163. 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) {
  17164. const llama_model & model = lctx->model;
  17165. llama_control_vector & cvec = lctx->cvec;
  17166. if (data == nullptr) {
  17167. // disable the current control vector (but leave allocated for later)
  17168. cvec.layer_start = -1;
  17169. cvec.layer_end = -1;
  17170. return 0;
  17171. }
  17172. if (n_embd != (int) model.hparams.n_embd) {
  17173. LLAMA_LOG_ERROR("%s: control vector n_embd does not match model\n", __func__);
  17174. return 1;
  17175. }
  17176. if (cvec.tensors.empty()) {
  17177. if (!llama_control_vector_init(cvec, model)) {
  17178. return 1;
  17179. }
  17180. }
  17181. cvec.layer_start = il_start;
  17182. cvec.layer_end = il_end;
  17183. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  17184. assert(cvec.tensors[il] != nullptr);
  17185. const size_t off = n_embd * (il - 1); // buffer doesn't have data for layer 0, since it's never present
  17186. if (off + n_embd <= len) {
  17187. ggml_backend_tensor_set(cvec.tensors[il], data + off, 0, n_embd * ggml_element_size(cvec.tensors[il]));
  17188. }
  17189. }
  17190. return 0;
  17191. }
  17192. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_seq_max) {
  17193. struct llama_kv_cache_view result = {
  17194. /*.n_cells = */ 0,
  17195. /*.n_seq_max = */ n_seq_max,
  17196. /*.token_count = */ 0,
  17197. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  17198. /*.max_contiguous = */ 0,
  17199. /*.max_contiguous_idx = */ -1,
  17200. /*.cells = */ nullptr,
  17201. /*.cells_sequences = */ nullptr,
  17202. };
  17203. return result;
  17204. }
  17205. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  17206. if (view->cells != nullptr) {
  17207. free(view->cells);
  17208. view->cells = nullptr;
  17209. }
  17210. if (view->cells_sequences != nullptr) {
  17211. free(view->cells_sequences);
  17212. view->cells_sequences = nullptr;
  17213. }
  17214. }
  17215. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  17216. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  17217. view->n_cells = int32_t(ctx->kv_self.size);
  17218. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  17219. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  17220. view->cells = (struct llama_kv_cache_view_cell *)p;
  17221. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_seq_max * view->n_cells);
  17222. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  17223. view->cells_sequences = (llama_seq_id *)p;
  17224. }
  17225. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  17226. llama_kv_cache_view_cell * c_curr = view->cells;
  17227. llama_seq_id * cs_curr = view->cells_sequences;
  17228. int32_t used_cells = 0;
  17229. int32_t token_count = 0;
  17230. int32_t curr_contig_idx = -1;
  17231. uint32_t max_contig = 0;
  17232. int32_t max_contig_idx = -1;
  17233. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_seq_max) {
  17234. const size_t curr_size = kv_cells[i].seq_id.size();
  17235. token_count += curr_size;
  17236. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  17237. if (curr_size > 0) {
  17238. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  17239. max_contig = i - curr_contig_idx;
  17240. max_contig_idx = curr_contig_idx;
  17241. }
  17242. curr_contig_idx = -1;
  17243. } else if (curr_contig_idx < 0) {
  17244. curr_contig_idx = i;
  17245. }
  17246. int seq_idx = 0;
  17247. for (const llama_seq_id it : kv_cells[i].seq_id) {
  17248. if (seq_idx >= view->n_seq_max) {
  17249. break;
  17250. }
  17251. cs_curr[seq_idx] = it;
  17252. seq_idx++;
  17253. }
  17254. if (seq_idx != 0) {
  17255. used_cells++;
  17256. }
  17257. for (; seq_idx < view->n_seq_max; seq_idx++) {
  17258. cs_curr[seq_idx] = -1;
  17259. }
  17260. }
  17261. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  17262. max_contig_idx = curr_contig_idx;
  17263. max_contig = kv_cells.size() - curr_contig_idx;
  17264. }
  17265. view->max_contiguous = max_contig;
  17266. view->max_contiguous_idx = max_contig_idx;
  17267. view->token_count = token_count;
  17268. view->used_cells = used_cells;
  17269. if (uint32_t(used_cells) != ctx->kv_self.used) {
  17270. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  17271. __func__, ctx->kv_self.used, used_cells);
  17272. }
  17273. }
  17274. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  17275. int result = 0;
  17276. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  17277. result += ctx->kv_self.cells[i].seq_id.size();
  17278. }
  17279. return result;
  17280. }
  17281. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  17282. return ctx->kv_self.used;
  17283. }
  17284. void llama_kv_cache_clear(struct llama_context * ctx) {
  17285. llama_kv_cache_clear(ctx->kv_self);
  17286. }
  17287. bool llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  17288. return llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  17289. }
  17290. 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) {
  17291. if (seq_id_src == seq_id_dst) {
  17292. return;
  17293. }
  17294. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  17295. }
  17296. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  17297. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  17298. }
  17299. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  17300. if (delta == 0) {
  17301. return;
  17302. }
  17303. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  17304. }
  17305. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  17306. if (d == 1) {
  17307. return;
  17308. }
  17309. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  17310. }
  17311. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  17312. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  17313. }
  17314. void llama_kv_cache_defrag(struct llama_context * ctx) {
  17315. llama_kv_cache_defrag(ctx->kv_self);
  17316. }
  17317. void llama_kv_cache_update(struct llama_context * ctx) {
  17318. llama_kv_cache_update_internal(*ctx);
  17319. }
  17320. // deprecated
  17321. size_t llama_get_state_size(struct llama_context * ctx) {
  17322. return llama_state_get_size(ctx);
  17323. }
  17324. // deprecated
  17325. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  17326. return llama_state_get_data(ctx, dst, -1);
  17327. }
  17328. // deprecated
  17329. size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
  17330. return llama_state_set_data(ctx, src, -1);
  17331. }
  17332. // deprecated
  17333. 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) {
  17334. return llama_state_load_file(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  17335. }
  17336. // deprecated
  17337. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  17338. return llama_state_save_file(ctx, path_session, tokens, n_token_count);
  17339. }
  17340. // TODO: replace all non-fatal assertions with returned errors or exceptions
  17341. struct llama_data_write {
  17342. virtual void write(const void * src, size_t size) = 0;
  17343. virtual void write_tensor_data(const struct ggml_tensor * tensor, size_t offset, size_t size) = 0;
  17344. virtual size_t get_size_written() = 0;
  17345. virtual ~llama_data_write() = default;
  17346. void write_string(const std::string & str) {
  17347. uint32_t str_size = str.size();
  17348. write(&str_size, sizeof(str_size));
  17349. write(str.data(), str_size);
  17350. }
  17351. void write_model_info(const struct llama_context * ctx) {
  17352. std::string arch_str = LLM_ARCH_NAMES.at(ctx->model.arch);
  17353. write_string(arch_str);
  17354. // TODO: add more model-specific info which should prevent loading the session file if not identical
  17355. }
  17356. //void write_rng(const std::mt19937 & rng) {
  17357. // std::ostringstream rng_ss;
  17358. // rng_ss << rng;
  17359. // const std::string & rng_str = rng_ss.str();
  17360. // write_string(rng_str);
  17361. //}
  17362. void write_output_ids(struct llama_context * ctx) {
  17363. llama_output_reorder(ctx);
  17364. const uint32_t n_outputs = ctx->n_outputs;
  17365. std::vector<int32_t> output_pos;
  17366. const size_t n_batch = ctx->cparams.n_batch;
  17367. const auto & output_ids = ctx->output_ids;
  17368. GGML_ASSERT(n_outputs <= ctx->output_size);
  17369. output_pos.resize(n_outputs);
  17370. // build a more compact representation of the output ids
  17371. for (size_t i = 0; i < n_batch; ++i) {
  17372. // map an output id to a position in the batch
  17373. int32_t pos = output_ids[i];
  17374. if (pos >= 0) {
  17375. GGML_ASSERT((uint32_t) pos < n_outputs);
  17376. output_pos[pos] = i;
  17377. }
  17378. }
  17379. write(&n_outputs, sizeof(n_outputs));
  17380. if (n_outputs) {
  17381. write(output_pos.data(), n_outputs * sizeof(int32_t));
  17382. }
  17383. }
  17384. void write_logits(const struct llama_context * ctx) {
  17385. const uint64_t logits_size = std::min((uint64_t) ctx->logits_size, (uint64_t) ctx->n_outputs * ctx->model.hparams.n_vocab);
  17386. write(&logits_size, sizeof(logits_size));
  17387. if (logits_size) {
  17388. write(ctx->logits, logits_size * sizeof(float));
  17389. }
  17390. }
  17391. void write_embeddings(const struct llama_context * ctx) {
  17392. const uint64_t embeddings_size = std::min((uint64_t) ctx->embd_size, (uint64_t) ctx->n_outputs * ctx->model.hparams.n_embd);
  17393. write(&embeddings_size, sizeof(embeddings_size));
  17394. if (embeddings_size) {
  17395. write(ctx->embd, embeddings_size * sizeof(float));
  17396. }
  17397. }
  17398. 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) {
  17399. for (const auto & range : cell_ranges) {
  17400. for (uint32_t i = range.first; i < range.second; ++i) {
  17401. const auto & cell = kv_self.cells[i];
  17402. const llama_pos pos = cell.pos;
  17403. const uint32_t n_seq_id = seq_id == -1 ? cell.seq_id.size() : 0;
  17404. write(&pos, sizeof(pos));
  17405. write(&n_seq_id, sizeof(n_seq_id));
  17406. if (n_seq_id) {
  17407. for (auto seq_id : cell.seq_id) {
  17408. write(&seq_id, sizeof(seq_id));
  17409. }
  17410. }
  17411. }
  17412. }
  17413. }
  17414. void write_kv_cache_data(const struct llama_context * ctx, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges) {
  17415. const struct llama_kv_cache & kv_self = ctx->kv_self;
  17416. const struct llama_hparams & hparams = ctx->model.hparams;
  17417. const uint32_t v_trans = kv_self.v_trans ? 1 : 0;
  17418. const uint32_t n_layer = hparams.n_layer;
  17419. write(&v_trans, sizeof(v_trans));
  17420. write(&n_layer, sizeof(n_layer));
  17421. std::vector<uint8_t> tmp_buf;
  17422. // Iterate and write all the keys first, each row is a cell
  17423. // Get whole range at a time
  17424. for (uint32_t il = 0; il < n_layer; ++il) {
  17425. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  17426. // Write key type
  17427. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  17428. write(&k_type_i, sizeof(k_type_i));
  17429. // Write row size of key
  17430. const uint64_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  17431. write(&k_size_row, sizeof(k_size_row));
  17432. // Read each range of cells of k_size length each into tmp_buf and write out
  17433. for (const auto & range : cell_ranges) {
  17434. const size_t range_size = range.second - range.first;
  17435. const size_t buf_size = range_size * k_size_row;
  17436. write_tensor_data(kv_self.k_l[il], range.first * k_size_row, buf_size);
  17437. }
  17438. }
  17439. if (!kv_self.v_trans) {
  17440. for (uint32_t il = 0; il < n_layer; ++il) {
  17441. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  17442. // Write value type
  17443. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  17444. write(&v_type_i, sizeof(v_type_i));
  17445. // Write row size of value
  17446. const uint64_t v_size_row = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa);
  17447. write(&v_size_row, sizeof(v_size_row));
  17448. // Read each range of cells of v_size length each into tmp_buf and write out
  17449. for (const auto & range : cell_ranges) {
  17450. const size_t range_size = range.second - range.first;
  17451. const size_t buf_size = range_size * v_size_row;
  17452. write_tensor_data(kv_self.v_l[il], range.first * v_size_row, buf_size);
  17453. }
  17454. }
  17455. } else {
  17456. // When v is transposed, we also need the element size and get the element ranges from each row
  17457. const uint32_t kv_size = kv_self.size;
  17458. for (uint32_t il = 0; il < n_layer; ++il) {
  17459. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  17460. // Write value type
  17461. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  17462. write(&v_type_i, sizeof(v_type_i));
  17463. // Write element size
  17464. const uint32_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  17465. write(&v_size_el, sizeof(v_size_el));
  17466. // Write GQA embedding size
  17467. write(&n_embd_v_gqa, sizeof(n_embd_v_gqa));
  17468. // For each row, we get the element values of each cell
  17469. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  17470. // Read each range of cells of v_size_el length each into tmp_buf and write out
  17471. for (const auto & range : cell_ranges) {
  17472. const size_t range_size = range.second - range.first;
  17473. const size_t src_offset = (range.first + j * kv_size) * v_size_el;
  17474. const size_t buf_size = range_size * v_size_el;
  17475. write_tensor_data(kv_self.v_l[il], src_offset, buf_size);
  17476. }
  17477. }
  17478. }
  17479. }
  17480. }
  17481. void write_kv_cache(const struct llama_context * ctx, llama_seq_id seq_id = -1) {
  17482. const struct llama_kv_cache & kv_self = ctx->kv_self;
  17483. std::vector<std::pair<uint32_t, uint32_t>> cell_ranges; // ranges, from inclusive, to exclusive
  17484. uint32_t cell_count = 0;
  17485. // Count the number of cells with the specified seq_id
  17486. // Find all the ranges of cells with this seq id (or all, when -1)
  17487. uint32_t cell_range_begin = kv_self.size;
  17488. for (uint32_t i = 0; i < kv_self.size; ++i) {
  17489. const auto & cell = kv_self.cells[i];
  17490. if ((seq_id == -1 && !cell.is_empty()) || cell.has_seq_id(seq_id)) {
  17491. ++cell_count;
  17492. if (cell_range_begin == kv_self.size) {
  17493. cell_range_begin = i;
  17494. }
  17495. } else {
  17496. if (cell_range_begin != kv_self.size) {
  17497. cell_ranges.emplace_back(cell_range_begin, i);
  17498. cell_range_begin = kv_self.size;
  17499. }
  17500. }
  17501. }
  17502. if (cell_range_begin != kv_self.size) {
  17503. cell_ranges.emplace_back(cell_range_begin, kv_self.size);
  17504. }
  17505. // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
  17506. uint32_t cell_count_check = 0;
  17507. for (const auto & range : cell_ranges) {
  17508. cell_count_check += range.second - range.first;
  17509. }
  17510. GGML_ASSERT(cell_count == cell_count_check);
  17511. write(&cell_count, sizeof(cell_count));
  17512. write_kv_cache_meta(kv_self, cell_ranges, seq_id);
  17513. write_kv_cache_data(ctx, cell_ranges);
  17514. }
  17515. };
  17516. struct llama_data_read {
  17517. virtual const uint8_t * read(size_t size) = 0;
  17518. virtual void read_to(void * dst, size_t size) = 0;
  17519. virtual size_t get_size_read() = 0;
  17520. virtual ~llama_data_read() = default;
  17521. void read_string(std::string & str) {
  17522. uint32_t str_size;
  17523. read_to(&str_size, sizeof(str_size));
  17524. str.assign((const char *) read(str_size), str_size);
  17525. }
  17526. // validate model information
  17527. void read_model_info(const struct llama_context * ctx) {
  17528. std::string cur_arch_str = LLM_ARCH_NAMES.at(ctx->model.arch);
  17529. std::string arch_str;
  17530. read_string(arch_str);
  17531. if (cur_arch_str != arch_str) {
  17532. throw std::runtime_error(format("wrong model arch: '%s' instead of '%s'", arch_str.c_str(), cur_arch_str.c_str()));
  17533. }
  17534. // TODO: add more info which needs to be identical but which is not verified otherwise
  17535. }
  17536. //void read_rng(std::mt19937 & rng) {
  17537. // std::string rng_str;
  17538. // read_string(rng_str);
  17539. // std::istringstream rng_ss(rng_str);
  17540. // rng_ss >> rng;
  17541. // if (rng_ss.fail()) {
  17542. // throw std::runtime_error("failed to load RNG state");
  17543. // }
  17544. //}
  17545. void read_output_ids(struct llama_context * ctx) {
  17546. std::vector<int32_t> output_pos;
  17547. uint32_t n_outputs;
  17548. read_to(&n_outputs, sizeof(n_outputs));
  17549. if (n_outputs > llama_output_reserve(*ctx, n_outputs)) {
  17550. throw std::runtime_error("could not reserve outputs");
  17551. }
  17552. if (n_outputs) {
  17553. output_pos.resize(n_outputs);
  17554. read_to(output_pos.data(), n_outputs * sizeof(int32_t));
  17555. for (int32_t i = 0; i < (int32_t) output_pos.size(); ++i) {
  17556. int32_t id = output_pos[i];
  17557. if ((uint32_t) id >= ctx->cparams.n_batch) {
  17558. throw std::runtime_error(format("invalid output id, %d does not fit in batch size of %u", id, ctx->cparams.n_batch));
  17559. }
  17560. ctx->output_ids[id] = i;
  17561. }
  17562. ctx->n_outputs = n_outputs;
  17563. }
  17564. }
  17565. void read_logits(struct llama_context * ctx) {
  17566. uint64_t logits_size;
  17567. read_to(&logits_size, sizeof(logits_size));
  17568. if (ctx->logits_size < logits_size) {
  17569. throw std::runtime_error("logits buffer too small");
  17570. }
  17571. if (logits_size) {
  17572. read_to(ctx->logits, logits_size * sizeof(float));
  17573. }
  17574. }
  17575. void read_embeddings(struct llama_context * ctx) {
  17576. uint64_t embeddings_size;
  17577. read_to(&embeddings_size, sizeof(embeddings_size));
  17578. if (ctx->embd_size < embeddings_size) {
  17579. throw std::runtime_error("embeddings buffer too small");
  17580. }
  17581. if (embeddings_size) {
  17582. read_to(ctx->embd, embeddings_size * sizeof(float));
  17583. }
  17584. }
  17585. bool read_kv_cache_meta(struct llama_context * ctx, uint32_t cell_count, llama_seq_id dest_seq_id = -1) {
  17586. struct llama_kv_cache & kv_self = ctx->kv_self;
  17587. if (dest_seq_id != -1) {
  17588. // single sequence
  17589. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  17590. llama_ubatch batch = ctx->sbatch.reserve_ubatch(cell_count, /* has_embd */ false);
  17591. batch.n_tokens = cell_count;
  17592. batch.n_seq_tokens = cell_count;
  17593. batch.n_seqs = 1;
  17594. for (uint32_t i = 0; i < cell_count; ++i) {
  17595. llama_pos pos;
  17596. uint32_t n_seq_id;
  17597. read_to(&pos, sizeof(pos));
  17598. read_to(&n_seq_id, sizeof(n_seq_id));
  17599. if (n_seq_id != 0) {
  17600. LLAMA_LOG_ERROR("%s: invalid seq_id-agnostic kv cell\n", __func__);
  17601. return false;
  17602. }
  17603. batch.pos[i] = pos;
  17604. }
  17605. batch.n_seq_id[0] = 1;
  17606. batch.seq_id[0] = &dest_seq_id;
  17607. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  17608. LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
  17609. return false;
  17610. }
  17611. // 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)
  17612. // Assume that this is one contiguous block of cells
  17613. GGML_ASSERT(kv_self.head + cell_count <= kv_self.size);
  17614. GGML_ASSERT(kv_self.cells[kv_self.head].pos == batch.pos[0]);
  17615. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].pos == batch.pos[cell_count - 1]);
  17616. GGML_ASSERT(kv_self.cells[kv_self.head].has_seq_id(dest_seq_id));
  17617. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].has_seq_id(dest_seq_id));
  17618. } else {
  17619. // whole KV cache restore
  17620. if (cell_count > kv_self.size) {
  17621. LLAMA_LOG_ERROR("%s: not enough cells in kv cache\n", __func__);
  17622. return false;
  17623. }
  17624. llama_kv_cache_clear(kv_self);
  17625. for (uint32_t i = 0; i < cell_count; ++i) {
  17626. llama_kv_cell & cell = kv_self.cells[i];
  17627. llama_pos pos;
  17628. uint32_t n_seq_id;
  17629. read_to(&pos, sizeof(pos));
  17630. read_to(&n_seq_id, sizeof(n_seq_id));
  17631. cell.pos = pos;
  17632. for (uint32_t j = 0; j < n_seq_id; ++j) {
  17633. llama_seq_id seq_id;
  17634. read_to(&seq_id, sizeof(seq_id));
  17635. if (seq_id < 0 || (uint32_t) seq_id >= llama_n_seq_max(ctx)) {
  17636. LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, %u)\n", __func__, seq_id, llama_n_seq_max(ctx));
  17637. return false;
  17638. }
  17639. cell.seq_id.insert(seq_id);
  17640. if (kv_self.recurrent) {
  17641. int32_t & tail = kv_self.cells[seq_id].tail;
  17642. if (tail != -1) {
  17643. LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tail);
  17644. return false;
  17645. }
  17646. tail = i;
  17647. }
  17648. }
  17649. }
  17650. kv_self.head = 0;
  17651. kv_self.used = cell_count;
  17652. }
  17653. if (kv_self.recurrent) {
  17654. for (uint32_t i = 0; i < cell_count; ++i) {
  17655. uint32_t cell_id = kv_self.head + i;
  17656. // make sure the recurrent states will keep their restored state
  17657. kv_self.cells[cell_id].src = cell_id;
  17658. }
  17659. }
  17660. return true;
  17661. }
  17662. bool read_kv_cache_data(struct llama_context * ctx, uint32_t cell_count) {
  17663. const struct llama_hparams & hparams = ctx->model.hparams;
  17664. struct llama_kv_cache & kv_self = ctx->kv_self;
  17665. uint32_t v_trans;
  17666. uint32_t n_layer;
  17667. read_to(&v_trans, sizeof(v_trans));
  17668. read_to(&n_layer, sizeof(n_layer));
  17669. if (n_layer != hparams.n_layer) {
  17670. LLAMA_LOG_ERROR("%s: mismatched layer count (%u instead of %u)\n", __func__, n_layer, hparams.n_layer);
  17671. return false;
  17672. }
  17673. if (cell_count > kv_self.size) {
  17674. LLAMA_LOG_ERROR("%s: not enough cells in kv cache to restore state (%u > %u)\n", __func__, cell_count, kv_self.size);
  17675. return false;
  17676. }
  17677. if (kv_self.v_trans != (bool) v_trans) {
  17678. LLAMA_LOG_ERROR("%s: incompatible V transposition\n", __func__);
  17679. return false;
  17680. }
  17681. // For each layer, read the keys for each cell, one row is one cell, read as one contiguous block
  17682. for (uint32_t il = 0; il < n_layer; ++il) {
  17683. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  17684. // Read type of key
  17685. int32_t k_type_i_ref;
  17686. read_to(&k_type_i_ref, sizeof(k_type_i_ref));
  17687. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  17688. if (k_type_i != k_type_i_ref) {
  17689. LLAMA_LOG_ERROR("%s: mismatched key type (%d != %d, layer %d)\n", __func__, k_type_i, k_type_i_ref, il);
  17690. return false;
  17691. }
  17692. // Read row size of key
  17693. uint64_t k_size_row_ref;
  17694. read_to(&k_size_row_ref, sizeof(k_size_row_ref));
  17695. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  17696. if (k_size_row != k_size_row_ref) {
  17697. LLAMA_LOG_ERROR("%s: mismatched key row size (%zu != %zu, layer %d)\n", __func__, k_size_row, (size_t) k_size_row_ref, il);
  17698. return false;
  17699. }
  17700. if (cell_count) {
  17701. // Read and set the keys for the whole cell range
  17702. 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);
  17703. }
  17704. }
  17705. if (!kv_self.v_trans) {
  17706. for (uint32_t il = 0; il < n_layer; ++il) {
  17707. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  17708. // Read type of value
  17709. int32_t v_type_i_ref;
  17710. read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  17711. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  17712. if (v_type_i != v_type_i_ref) {
  17713. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  17714. return false;
  17715. }
  17716. // Read row size of value
  17717. uint64_t v_size_row_ref;
  17718. read_to(&v_size_row_ref, sizeof(v_size_row_ref));
  17719. const size_t v_size_row = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa);
  17720. if (v_size_row != v_size_row_ref) {
  17721. LLAMA_LOG_ERROR("%s: mismatched value row size (%zu != %zu, layer %d)\n", __func__, v_size_row, (size_t) v_size_row_ref, il);
  17722. return false;
  17723. }
  17724. if (cell_count) {
  17725. // Read and set the values for the whole cell range
  17726. 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);
  17727. }
  17728. }
  17729. } else {
  17730. // For each layer, read the values for each cell (transposed)
  17731. for (uint32_t il = 0; il < n_layer; ++il) {
  17732. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  17733. // Read type of value
  17734. int32_t v_type_i_ref;
  17735. read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  17736. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  17737. if (v_type_i != v_type_i_ref) {
  17738. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  17739. return false;
  17740. }
  17741. // Read element size of value
  17742. uint32_t v_size_el_ref;
  17743. read_to(&v_size_el_ref, sizeof(v_size_el_ref));
  17744. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  17745. if (v_size_el != v_size_el_ref) {
  17746. LLAMA_LOG_ERROR("%s: mismatched value element size (%zu != %zu, layer %d)\n", __func__, v_size_el, (size_t) v_size_el_ref, il);
  17747. return false;
  17748. }
  17749. // Read GQA embedding size
  17750. uint32_t n_embd_v_gqa_ref;
  17751. read_to(&n_embd_v_gqa_ref, sizeof(n_embd_v_gqa_ref));
  17752. if (n_embd_v_gqa != n_embd_v_gqa_ref) {
  17753. LLAMA_LOG_ERROR("%s: mismatched GQA embedding size (%u != %u, layer %d)\n", __func__, n_embd_v_gqa, n_embd_v_gqa_ref, il);
  17754. return false;
  17755. }
  17756. if (cell_count) {
  17757. // For each row in the transposed matrix, read the values for the whole cell range
  17758. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  17759. const size_t dst_offset = (kv_self.head + j * kv_self.size) * v_size_el;
  17760. ggml_backend_tensor_set(kv_self.v_l[il], read(cell_count * v_size_el), dst_offset, cell_count * v_size_el);
  17761. }
  17762. }
  17763. }
  17764. }
  17765. return true;
  17766. }
  17767. void read_kv_cache(struct llama_context * ctx, llama_seq_id seq_id = -1) {
  17768. uint32_t cell_count;
  17769. read_to(&cell_count, sizeof(cell_count));
  17770. bool res = read_kv_cache_meta(ctx, cell_count, seq_id) && read_kv_cache_data(ctx, cell_count);
  17771. if (!res) {
  17772. if (seq_id == -1) {
  17773. llama_kv_cache_clear(ctx);
  17774. } else {
  17775. llama_kv_cache_seq_rm(ctx, seq_id, -1, -1);
  17776. }
  17777. throw std::runtime_error("failed to restore kv cache");
  17778. }
  17779. }
  17780. };
  17781. struct llama_data_write_dummy : llama_data_write {
  17782. size_t size_written = 0;
  17783. llama_data_write_dummy() {}
  17784. void write(const void * /* src */, size_t size) override {
  17785. size_written += size;
  17786. }
  17787. void write_tensor_data(const struct ggml_tensor * /* tensor */, size_t /* offset */, size_t size) override {
  17788. size_written += size;
  17789. }
  17790. size_t get_size_written() override {
  17791. return size_written;
  17792. }
  17793. };
  17794. struct llama_data_write_buffer : llama_data_write {
  17795. uint8_t * ptr;
  17796. size_t buf_size = 0;
  17797. size_t size_written = 0;
  17798. llama_data_write_buffer(uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
  17799. void write(const void * src, size_t size) override {
  17800. if (size > buf_size) {
  17801. throw std::runtime_error("unexpectedly reached end of buffer");
  17802. }
  17803. memcpy(ptr, src, size);
  17804. ptr += size;
  17805. size_written += size;
  17806. buf_size -= size;
  17807. }
  17808. void write_tensor_data(const struct ggml_tensor * tensor, size_t offset, size_t size) override {
  17809. if (size > buf_size) {
  17810. throw std::runtime_error("unexpectedly reached end of buffer");
  17811. }
  17812. ggml_backend_tensor_get(tensor, ptr, offset, size);
  17813. ptr += size;
  17814. size_written += size;
  17815. buf_size -= size;
  17816. }
  17817. size_t get_size_written() override {
  17818. return size_written;
  17819. }
  17820. };
  17821. struct llama_data_read_buffer : llama_data_read {
  17822. const uint8_t * ptr;
  17823. size_t buf_size = 0;
  17824. size_t size_read = 0;
  17825. llama_data_read_buffer(const uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
  17826. const uint8_t * read(size_t size) override {
  17827. const uint8_t * base_ptr = ptr;
  17828. if (size > buf_size) {
  17829. throw std::runtime_error("unexpectedly reached end of buffer");
  17830. }
  17831. ptr += size;
  17832. size_read += size;
  17833. buf_size -= size;
  17834. return base_ptr;
  17835. }
  17836. void read_to(void * dst, size_t size) override {
  17837. memcpy(dst, read(size), size);
  17838. }
  17839. size_t get_size_read() override {
  17840. return size_read;
  17841. }
  17842. };
  17843. struct llama_data_write_file : llama_data_write {
  17844. llama_file * file;
  17845. size_t size_written = 0;
  17846. std::vector<uint8_t> temp_buffer;
  17847. llama_data_write_file(llama_file * f) : file(f) {}
  17848. void write(const void * src, size_t size) override {
  17849. file->write_raw(src, size);
  17850. size_written += size;
  17851. }
  17852. void write_tensor_data(const struct ggml_tensor * tensor, size_t offset, size_t size) override {
  17853. temp_buffer.resize(size);
  17854. ggml_backend_tensor_get(tensor, temp_buffer.data(), offset, size);
  17855. write(temp_buffer.data(), temp_buffer.size());
  17856. }
  17857. size_t get_size_written() override {
  17858. return size_written;
  17859. }
  17860. };
  17861. struct llama_data_read_file : llama_data_read {
  17862. llama_file * file;
  17863. size_t size_read = 0;
  17864. std::vector<uint8_t> temp_buffer;
  17865. llama_data_read_file(llama_file * f) : file(f) {}
  17866. void read_to(void * dst, size_t size) override {
  17867. file->read_raw(dst, size);
  17868. size_read += size;
  17869. }
  17870. const uint8_t * read(size_t size) override {
  17871. temp_buffer.resize(size);
  17872. read_to(temp_buffer.data(), size);
  17873. return temp_buffer.data();
  17874. }
  17875. size_t get_size_read() override {
  17876. return size_read;
  17877. }
  17878. };
  17879. /** copy state data into either a buffer or file depending on the passed in context
  17880. *
  17881. * file context:
  17882. * llama_file file("/path", "wb");
  17883. * llama_data_write_file data_ctx(&file);
  17884. * llama_state_get_data_internal(ctx, data_ctx);
  17885. *
  17886. * buffer context:
  17887. * std::vector<uint8_t> buf(max_size, 0);
  17888. * llama_data_write_buffer data_ctx(buf.data(), max_size);
  17889. * llama_state_get_data_internal(ctx, data_ctx);
  17890. *
  17891. */
  17892. static size_t llama_state_get_data_internal(struct llama_context * ctx, llama_data_write & data_ctx) {
  17893. llama_synchronize(ctx);
  17894. data_ctx.write_model_info(ctx);
  17895. // copy outputs
  17896. data_ctx.write_output_ids(ctx);
  17897. data_ctx.write_logits(ctx);
  17898. data_ctx.write_embeddings(ctx);
  17899. data_ctx.write_kv_cache(ctx);
  17900. return data_ctx.get_size_written();
  17901. }
  17902. size_t llama_state_get_data(struct llama_context * ctx, uint8_t * dst, size_t size) {
  17903. llama_data_write_buffer data_ctx(dst, size);
  17904. try {
  17905. return llama_state_get_data_internal(ctx, data_ctx);
  17906. } catch (const std::exception & err) {
  17907. LLAMA_LOG_ERROR("%s: error saving state: %s\n", __func__, err.what());
  17908. return 0;
  17909. }
  17910. }
  17911. // Returns the *actual* size of the state.
  17912. // Intended to be used when saving to state to a buffer.
  17913. size_t llama_state_get_size(struct llama_context * ctx) {
  17914. llama_data_write_dummy data_ctx;
  17915. try {
  17916. return llama_state_get_data_internal(ctx, data_ctx);
  17917. } catch (const std::exception & err) {
  17918. LLAMA_LOG_ERROR("%s: error getting state size: %s\n", __func__, err.what());
  17919. return 0;
  17920. }
  17921. }
  17922. static size_t llama_state_set_data_internal(struct llama_context * ctx, llama_data_read & data_ctx) {
  17923. llama_synchronize(ctx);
  17924. data_ctx.read_model_info(ctx);
  17925. // set outputs
  17926. data_ctx.read_output_ids(ctx);
  17927. data_ctx.read_logits(ctx);
  17928. data_ctx.read_embeddings(ctx);
  17929. data_ctx.read_kv_cache(ctx);
  17930. return data_ctx.get_size_read();
  17931. }
  17932. // Sets the state reading from the specified source address
  17933. size_t llama_state_set_data(struct llama_context * ctx, const uint8_t * src, size_t size) {
  17934. llama_data_read_buffer data_ctx(src, size);
  17935. try {
  17936. return llama_state_set_data_internal(ctx, data_ctx);
  17937. } catch (const std::exception & err) {
  17938. LLAMA_LOG_ERROR("%s: error loading state: %s\n", __func__, err.what());
  17939. return 0;
  17940. }
  17941. }
  17942. 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) {
  17943. llama_file file(path_session, "rb");
  17944. // sanity checks
  17945. {
  17946. const uint32_t magic = file.read_u32();
  17947. const uint32_t version = file.read_u32();
  17948. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  17949. LLAMA_LOG_ERROR("%s: unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  17950. return false;
  17951. }
  17952. }
  17953. // load the prompt
  17954. {
  17955. const uint32_t n_token_count = file.read_u32();
  17956. if (n_token_count > n_token_capacity) {
  17957. LLAMA_LOG_ERROR("%s: token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  17958. return false;
  17959. }
  17960. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  17961. *n_token_count_out = n_token_count;
  17962. }
  17963. // restore the context state
  17964. {
  17965. const size_t n_state_size_cur = file.size - file.tell();
  17966. llama_data_read_file data_ctx(&file);
  17967. const size_t n_read = llama_state_set_data_internal(ctx, data_ctx);
  17968. if (n_read != n_state_size_cur) {
  17969. 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);
  17970. return false;
  17971. }
  17972. }
  17973. return true;
  17974. }
  17975. 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) {
  17976. try {
  17977. return llama_state_load_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  17978. } catch (const std::exception & err) {
  17979. LLAMA_LOG_ERROR("%s: error loading session file: %s\n", __func__, err.what());
  17980. return false;
  17981. }
  17982. }
  17983. static bool llama_state_save_file_internal(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  17984. llama_file file(path_session, "wb");
  17985. file.write_u32(LLAMA_SESSION_MAGIC);
  17986. file.write_u32(LLAMA_SESSION_VERSION);
  17987. // save the prompt
  17988. file.write_u32((uint32_t) n_token_count);
  17989. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  17990. // save the context state using stream saving
  17991. llama_data_write_file data_ctx(&file);
  17992. llama_state_get_data_internal(ctx, data_ctx);
  17993. return true;
  17994. }
  17995. bool llama_state_save_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  17996. try {
  17997. return llama_state_save_file_internal(ctx, path_session, tokens, n_token_count);
  17998. } catch (const std::exception & err) {
  17999. LLAMA_LOG_ERROR("%s: error saving session file: %s\n", __func__, err.what());
  18000. return false;
  18001. }
  18002. }
  18003. static size_t llama_state_seq_get_data_internal(struct llama_context * ctx, llama_data_write & data_ctx, llama_seq_id seq_id) {
  18004. llama_synchronize(ctx);
  18005. data_ctx.write_kv_cache(ctx, seq_id);
  18006. return data_ctx.get_size_written();
  18007. }
  18008. size_t llama_state_seq_get_size(struct llama_context * ctx, llama_seq_id seq_id) {
  18009. llama_data_write_dummy data_ctx;
  18010. return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  18011. }
  18012. size_t llama_state_seq_get_data(struct llama_context * ctx, uint8_t * dst, size_t size, llama_seq_id seq_id) {
  18013. llama_data_write_buffer data_ctx(dst, size);
  18014. try {
  18015. return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  18016. } catch (const std::exception & err) {
  18017. LLAMA_LOG_ERROR("%s: error saving sequence state: %s\n", __func__, err.what());
  18018. return 0;
  18019. }
  18020. }
  18021. static size_t llama_state_seq_set_data_internal(struct llama_context * ctx, llama_data_read & data_ctx, llama_seq_id dest_seq_id) {
  18022. llama_synchronize(ctx);
  18023. data_ctx.read_kv_cache(ctx, dest_seq_id);
  18024. return data_ctx.get_size_read();
  18025. }
  18026. size_t llama_state_seq_set_data(struct llama_context * ctx, const uint8_t * src, size_t size, llama_seq_id dest_seq_id) {
  18027. llama_data_read_buffer data_ctx(src, size);
  18028. try {
  18029. return llama_state_seq_set_data_internal(ctx, data_ctx, dest_seq_id);
  18030. } catch (const std::exception & err) {
  18031. LLAMA_LOG_ERROR("%s: error loading sequence state: %s\n", __func__, err.what());
  18032. return 0;
  18033. }
  18034. }
  18035. 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) {
  18036. llama_file file(filepath, "wb");
  18037. file.write_u32(LLAMA_STATE_SEQ_MAGIC);
  18038. file.write_u32(LLAMA_STATE_SEQ_VERSION);
  18039. // save the prompt
  18040. file.write_u32((uint32_t) n_token_count);
  18041. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  18042. // save the context state using stream saving
  18043. llama_data_write_file data_ctx(&file);
  18044. llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  18045. const size_t res = file.tell();
  18046. GGML_ASSERT(res == sizeof(uint32_t) * 3 + sizeof(llama_token) * n_token_count + data_ctx.get_size_written());
  18047. return res;
  18048. }
  18049. 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) {
  18050. llama_file file(filepath, "rb");
  18051. // version checks
  18052. {
  18053. const uint32_t magic = file.read_u32();
  18054. const uint32_t version = file.read_u32();
  18055. if (magic != LLAMA_STATE_SEQ_MAGIC || version != LLAMA_STATE_SEQ_VERSION) {
  18056. LLAMA_LOG_ERROR("%s: unknown (magic, version) for sequence state file: %08x, %08x\n", __func__, magic, version);
  18057. return 0;
  18058. }
  18059. }
  18060. // load the prompt
  18061. {
  18062. const uint32_t n_token_count = file.read_u32();
  18063. if (n_token_count > n_token_capacity) {
  18064. LLAMA_LOG_ERROR("%s: token count in sequence state file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  18065. return 0;
  18066. }
  18067. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  18068. *n_token_count_out = n_token_count;
  18069. }
  18070. // restore the context state
  18071. {
  18072. const size_t state_size = file.size - file.tell();
  18073. llama_data_read_file data_ctx(&file);
  18074. const size_t nread = llama_state_seq_set_data_internal(ctx, data_ctx, dest_seq_id);
  18075. if (!nread) {
  18076. LLAMA_LOG_ERROR("%s: failed to restore sequence state\n", __func__);
  18077. return 0;
  18078. }
  18079. GGML_ASSERT(nread <= state_size);
  18080. GGML_ASSERT(nread + sizeof(uint32_t) * 3 + sizeof(llama_token) * *n_token_count_out == file.tell());
  18081. }
  18082. return file.tell();
  18083. }
  18084. 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) {
  18085. try {
  18086. return llama_state_seq_save_file_internal(ctx, filepath, seq_id, tokens, n_token_count);
  18087. } catch (const std::exception & err) {
  18088. LLAMA_LOG_ERROR("%s: error saving sequence state file: %s\n", __func__, err.what());
  18089. return 0;
  18090. }
  18091. }
  18092. 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) {
  18093. try {
  18094. return llama_state_seq_load_file_internal(ctx, filepath, dest_seq_id, tokens_out, n_token_capacity, n_token_count_out);
  18095. } catch (const std::exception & err) {
  18096. LLAMA_LOG_ERROR("%s: error loading sequence state file: %s\n", __func__, err.what());
  18097. return 0;
  18098. }
  18099. }
  18100. void llama_set_n_threads(struct llama_context * ctx, int32_t n_threads, int32_t n_threads_batch) {
  18101. ctx->cparams.n_threads = n_threads;
  18102. ctx->cparams.n_threads_batch = n_threads_batch;
  18103. }
  18104. int32_t llama_n_threads(struct llama_context * ctx) {
  18105. return ctx->cparams.n_threads;
  18106. }
  18107. int32_t llama_n_threads_batch(struct llama_context * ctx) {
  18108. return ctx->cparams.n_threads_batch;
  18109. }
  18110. void llama_set_abort_callback(struct llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
  18111. ctx->abort_callback = abort_callback;
  18112. ctx->abort_callback_data = abort_callback_data;
  18113. }
  18114. void llama_set_embeddings(struct llama_context * ctx, bool embeddings) {
  18115. ctx->cparams.embeddings = embeddings;
  18116. }
  18117. void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn) {
  18118. ctx->cparams.causal_attn = causal_attn;
  18119. }
  18120. struct llama_batch llama_batch_get_one(
  18121. llama_token * tokens,
  18122. int32_t n_tokens,
  18123. llama_pos pos_0,
  18124. llama_seq_id seq_id) {
  18125. return {
  18126. /*n_tokens =*/ n_tokens,
  18127. /*tokens =*/ tokens,
  18128. /*embd =*/ nullptr,
  18129. /*pos =*/ nullptr,
  18130. /*n_seq_id =*/ nullptr,
  18131. /*seq_id =*/ nullptr,
  18132. /*logits =*/ nullptr,
  18133. /*all_pos_0 =*/ pos_0,
  18134. /*all_pos_1 =*/ 1,
  18135. /*all_seq_id =*/ seq_id,
  18136. };
  18137. }
  18138. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  18139. llama_batch batch = {
  18140. /*n_tokens =*/ 0,
  18141. /*tokens =*/ nullptr,
  18142. /*embd =*/ nullptr,
  18143. /*pos =*/ nullptr,
  18144. /*n_seq_id =*/ nullptr,
  18145. /*seq_id =*/ nullptr,
  18146. /*logits =*/ nullptr,
  18147. /*all_pos_0 =*/ 0,
  18148. /*all_pos_1 =*/ 0,
  18149. /*all_seq_id =*/ 0,
  18150. };
  18151. if (embd) {
  18152. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  18153. } else {
  18154. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  18155. }
  18156. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  18157. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  18158. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  18159. for (int i = 0; i < n_tokens_alloc; ++i) {
  18160. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  18161. }
  18162. batch.seq_id[n_tokens_alloc] = nullptr;
  18163. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  18164. return batch;
  18165. }
  18166. void llama_batch_free(struct llama_batch batch) {
  18167. if (batch.token) free(batch.token);
  18168. if (batch.embd) free(batch.embd);
  18169. if (batch.pos) free(batch.pos);
  18170. if (batch.n_seq_id) free(batch.n_seq_id);
  18171. if (batch.seq_id) {
  18172. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  18173. free(batch.seq_id[i]);
  18174. }
  18175. free(batch.seq_id);
  18176. }
  18177. if (batch.logits) free(batch.logits);
  18178. }
  18179. int32_t llama_encode(
  18180. struct llama_context * ctx,
  18181. struct llama_batch batch) {
  18182. const int ret = llama_encode_internal(*ctx, batch);
  18183. if (ret < 0) {
  18184. LLAMA_LOG_ERROR("%s: failed to encode, ret = %d\n", __func__, ret);
  18185. }
  18186. return ret;
  18187. }
  18188. int32_t llama_decode(
  18189. struct llama_context * ctx,
  18190. struct llama_batch batch) {
  18191. const int ret = llama_decode_internal(*ctx, batch);
  18192. if (ret < 0) {
  18193. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  18194. }
  18195. return ret;
  18196. }
  18197. void llama_synchronize(struct llama_context * ctx) {
  18198. ggml_backend_sched_synchronize(ctx->sched);
  18199. // FIXME: if multiple single tokens are evaluated without a synchronization,
  18200. // the stats will be added to the prompt evaluation stats
  18201. // this should only happen when using batch size 1 to evaluate a batch
  18202. // add the evaluation to the stats
  18203. if (ctx->n_queued_tokens == 1) {
  18204. if (!ctx->cparams.no_perf) {
  18205. ctx->t_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  18206. }
  18207. ctx->n_eval++;
  18208. } else if (ctx->n_queued_tokens > 1) {
  18209. if (!ctx->cparams.no_perf) {
  18210. ctx->t_p_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  18211. }
  18212. ctx->n_p_eval += ctx->n_queued_tokens;
  18213. }
  18214. // get a more accurate load time, upon first eval
  18215. if (ctx->n_queued_tokens > 0 && !ctx->has_evaluated_once) {
  18216. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  18217. ctx->has_evaluated_once = true;
  18218. }
  18219. ctx->n_queued_tokens = 0;
  18220. ctx->t_compute_start_us = 0;
  18221. }
  18222. float * llama_get_logits(struct llama_context * ctx) {
  18223. llama_synchronize(ctx);
  18224. // reorder logits for backward compatibility
  18225. // TODO: maybe deprecate this
  18226. llama_output_reorder(ctx);
  18227. return ctx->logits;
  18228. }
  18229. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  18230. int32_t j = -1;
  18231. llama_synchronize(ctx);
  18232. try {
  18233. if (ctx->logits == nullptr) {
  18234. throw std::runtime_error("no logits");
  18235. }
  18236. if (i < 0) {
  18237. j = ctx->n_outputs + i;
  18238. if (j < 0) {
  18239. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  18240. }
  18241. } else if ((size_t) i >= ctx->output_ids.size()) {
  18242. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  18243. } else {
  18244. j = ctx->output_ids[i];
  18245. }
  18246. if (j < 0) {
  18247. throw std::runtime_error(format("batch.logits[%d] != true", i));
  18248. }
  18249. if (j >= ctx->n_outputs) {
  18250. // This should not happen
  18251. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  18252. }
  18253. return ctx->logits + j*ctx->model.hparams.n_vocab;
  18254. } catch (const std::exception & err) {
  18255. LLAMA_LOG_ERROR("%s: invalid logits id %d, reason: %s\n", __func__, i, err.what());
  18256. #ifndef NDEBUG
  18257. GGML_ABORT("fatal error");
  18258. #else
  18259. return nullptr;
  18260. #endif
  18261. }
  18262. }
  18263. float * llama_get_embeddings(struct llama_context * ctx) {
  18264. llama_synchronize(ctx);
  18265. // reorder embeddings for backward compatibility
  18266. // TODO: maybe deprecate this
  18267. llama_output_reorder(ctx);
  18268. return ctx->embd;
  18269. }
  18270. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  18271. int32_t j = -1;
  18272. llama_synchronize(ctx);
  18273. try {
  18274. if (ctx->embd == nullptr) {
  18275. throw std::runtime_error("no embeddings");
  18276. }
  18277. if (i < 0) {
  18278. j = ctx->n_outputs + i;
  18279. if (j < 0) {
  18280. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  18281. }
  18282. } else if ((size_t) i >= ctx->output_ids.size()) {
  18283. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  18284. } else {
  18285. j = ctx->output_ids[i];
  18286. }
  18287. if (j < 0) {
  18288. throw std::runtime_error(format("batch.logits[%d] != true", i));
  18289. }
  18290. if (j >= ctx->n_outputs) {
  18291. // This should not happen
  18292. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  18293. }
  18294. return ctx->embd + j*ctx->model.hparams.n_embd;
  18295. } catch (const std::exception & err) {
  18296. LLAMA_LOG_ERROR("%s: invalid embeddings id %d, reason: %s\n", __func__, i, err.what());
  18297. #ifndef NDEBUG
  18298. GGML_ABORT("fatal error");
  18299. #else
  18300. return nullptr;
  18301. #endif
  18302. }
  18303. }
  18304. float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id) {
  18305. llama_synchronize(ctx);
  18306. auto it = ctx->embd_seq.find(seq_id);
  18307. if (it == ctx->embd_seq.end()) {
  18308. return nullptr;
  18309. }
  18310. return it->second.data();
  18311. }
  18312. //
  18313. // vocab
  18314. //
  18315. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  18316. return llama_token_get_text_impl(model->vocab, token);
  18317. }
  18318. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  18319. return llama_token_get_score_impl(model->vocab, token);
  18320. }
  18321. enum llama_token_attr llama_token_get_attr(const struct llama_model * model, llama_token token) {
  18322. return llama_token_get_attr_impl(model->vocab, token);
  18323. }
  18324. bool llama_token_is_eog(const struct llama_model * model, llama_token token) {
  18325. return llama_token_is_eog_impl(model->vocab, token);
  18326. }
  18327. bool llama_token_is_control(const struct llama_model * model, llama_token token) {
  18328. return llama_token_is_control_impl(model->vocab, token);
  18329. }
  18330. llama_token llama_token_bos(const struct llama_model * model) {
  18331. return llama_token_bos_impl(model->vocab);
  18332. }
  18333. llama_token llama_token_eos(const struct llama_model * model) {
  18334. return llama_token_eos_impl(model->vocab);
  18335. }
  18336. llama_token llama_token_cls(const struct llama_model * model) {
  18337. return llama_token_cls_impl(model->vocab);
  18338. }
  18339. llama_token llama_token_sep(const struct llama_model * model) {
  18340. return llama_token_sep_impl(model->vocab);
  18341. }
  18342. llama_token llama_token_nl (const struct llama_model * model) {
  18343. return llama_token_nl_impl(model->vocab);
  18344. }
  18345. llama_token llama_token_pad(const struct llama_model * model) {
  18346. return llama_token_pad_impl(model->vocab);
  18347. }
  18348. bool llama_add_bos_token(const struct llama_model * model) {
  18349. return llama_add_bos_token_impl(model->vocab);
  18350. }
  18351. bool llama_add_eos_token(const struct llama_model * model) {
  18352. return llama_add_eos_token_impl(model->vocab);
  18353. }
  18354. llama_token llama_token_prefix(const struct llama_model * model) {
  18355. return llama_token_prefix_impl(model->vocab);
  18356. }
  18357. llama_token llama_token_middle(const struct llama_model * model) {
  18358. return llama_token_middle_impl(model->vocab);
  18359. }
  18360. llama_token llama_token_suffix(const struct llama_model * model) {
  18361. return llama_token_suffix_impl(model->vocab);
  18362. }
  18363. llama_token llama_token_eot(const struct llama_model * model) {
  18364. return llama_token_eot_impl(model->vocab);
  18365. }
  18366. //
  18367. // tokenization
  18368. //
  18369. int32_t llama_tokenize(
  18370. const struct llama_model * model,
  18371. const char * text,
  18372. int32_t text_len,
  18373. llama_token * tokens,
  18374. int32_t n_tokens_max,
  18375. bool add_special,
  18376. bool parse_special) {
  18377. return llama_tokenize_impl(model->vocab, text, text_len, tokens, n_tokens_max, add_special, parse_special);
  18378. }
  18379. int32_t llama_token_to_piece(
  18380. const struct llama_model * model,
  18381. llama_token token,
  18382. char * buf,
  18383. int32_t length,
  18384. int32_t lstrip,
  18385. bool special) {
  18386. return llama_token_to_piece_impl(model->vocab, token, buf, length, lstrip, special);
  18387. }
  18388. int32_t llama_detokenize(
  18389. const struct llama_model * model,
  18390. const llama_token * tokens,
  18391. int32_t n_tokens,
  18392. char * text,
  18393. int32_t text_len_max,
  18394. bool remove_special,
  18395. bool unparse_special) {
  18396. return llama_detokenize_impl(model->vocab, tokens, n_tokens, text, text_len_max, remove_special, unparse_special);
  18397. }
  18398. //
  18399. // chat templates
  18400. //
  18401. // Simple version of "llama_apply_chat_template" that only works with strings
  18402. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  18403. static int32_t llama_chat_apply_template_internal(
  18404. const std::string & tmpl,
  18405. const std::vector<const llama_chat_message *> & chat,
  18406. std::string & dest, bool add_ass) {
  18407. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  18408. std::stringstream ss;
  18409. auto tmpl_contains = [&tmpl](std::string haystack) -> bool {
  18410. return tmpl.find(haystack) != std::string::npos;
  18411. };
  18412. if (tmpl == "chatml" || tmpl_contains("<|im_start|>")) {
  18413. // chatml template
  18414. for (auto message : chat) {
  18415. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  18416. }
  18417. if (add_ass) {
  18418. ss << "<|im_start|>assistant\n";
  18419. }
  18420. } else if (tmpl == "llama2" || tmpl == "mistral" || tmpl_contains("[INST]")) {
  18421. // llama2 template and its variants
  18422. // [variant] support system message
  18423. bool support_system_message = tmpl_contains("<<SYS>>") || tmpl == "mistral";
  18424. // [variant] space before + after response
  18425. bool space_around_response = tmpl_contains("' ' + eos_token");
  18426. // [variant] add BOS inside history
  18427. bool add_bos_inside_history = tmpl_contains("bos_token + '[INST]");
  18428. // [variant] trim spaces from the input message
  18429. bool strip_message = tmpl_contains("content.strip()");
  18430. // construct the prompt
  18431. bool is_inside_turn = true; // skip BOS at the beginning
  18432. ss << "[INST] ";
  18433. for (auto message : chat) {
  18434. std::string content = strip_message ? trim(message->content) : message->content;
  18435. std::string role(message->role);
  18436. if (!is_inside_turn) {
  18437. is_inside_turn = true;
  18438. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  18439. }
  18440. if (role == "system") {
  18441. if (support_system_message) {
  18442. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  18443. } else {
  18444. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  18445. ss << content << "\n";
  18446. }
  18447. } else if (role == "user") {
  18448. ss << content << " [/INST]";
  18449. } else {
  18450. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  18451. is_inside_turn = false;
  18452. }
  18453. }
  18454. // llama2 templates seem to not care about "add_generation_prompt"
  18455. } else if (tmpl == "phi3" || (tmpl_contains("<|assistant|>") && tmpl_contains("<|end|>"))) {
  18456. // Phi 3
  18457. for (auto message : chat) {
  18458. std::string role(message->role);
  18459. ss << "<|" << role << "|>\n" << message->content << "<|end|>\n";
  18460. }
  18461. if (add_ass) {
  18462. ss << "<|assistant|>\n";
  18463. }
  18464. } else if (tmpl == "zephyr" || tmpl_contains("<|user|>")) {
  18465. // zephyr template
  18466. for (auto message : chat) {
  18467. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  18468. }
  18469. if (add_ass) {
  18470. ss << "<|assistant|>\n";
  18471. }
  18472. } else if (tmpl == "monarch" || tmpl_contains("bos_token + message['role']")) {
  18473. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  18474. for (auto message : chat) {
  18475. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  18476. ss << bos << message->role << "\n" << message->content << "</s>\n";
  18477. }
  18478. if (add_ass) {
  18479. ss << "<s>assistant\n";
  18480. }
  18481. } else if (tmpl == "gemma" || tmpl == "gemma2" || tmpl_contains("<start_of_turn>")) {
  18482. // google/gemma-7b-it
  18483. std::string system_prompt = "";
  18484. for (auto message : chat) {
  18485. std::string role(message->role);
  18486. if (role == "system") {
  18487. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  18488. system_prompt = trim(message->content);
  18489. continue;
  18490. }
  18491. // in gemma, "assistant" is "model"
  18492. role = role == "assistant" ? "model" : message->role;
  18493. ss << "<start_of_turn>" << role << "\n";
  18494. if (!system_prompt.empty() && role != "model") {
  18495. ss << system_prompt << "\n\n";
  18496. system_prompt = "";
  18497. }
  18498. ss << trim(message->content) << "<end_of_turn>\n";
  18499. }
  18500. if (add_ass) {
  18501. ss << "<start_of_turn>model\n";
  18502. }
  18503. } else if (tmpl == "orion" || tmpl_contains("'\\n\\nAssistant: ' + eos_token")) {
  18504. // OrionStarAI/Orion-14B-Chat
  18505. std::string system_prompt = "";
  18506. for (auto message : chat) {
  18507. std::string role(message->role);
  18508. if (role == "system") {
  18509. // there is no system message support, we will merge it with user prompt
  18510. system_prompt = message->content;
  18511. continue;
  18512. } else if (role == "user") {
  18513. ss << "Human: ";
  18514. if (!system_prompt.empty()) {
  18515. ss << system_prompt << "\n\n";
  18516. system_prompt = "";
  18517. }
  18518. ss << message->content << "\n\nAssistant: </s>";
  18519. } else {
  18520. ss << message->content << "</s>";
  18521. }
  18522. }
  18523. } else if (tmpl == "openchat" || tmpl_contains("GPT4 Correct ")) {
  18524. // openchat/openchat-3.5-0106,
  18525. for (auto message : chat) {
  18526. std::string role(message->role);
  18527. if (role == "system") {
  18528. ss << message->content << "<|end_of_turn|>";
  18529. } else {
  18530. role[0] = toupper(role[0]);
  18531. ss << "GPT4 Correct " << role << ": " << message->content << "<|end_of_turn|>";
  18532. }
  18533. }
  18534. if (add_ass) {
  18535. ss << "GPT4 Correct Assistant:";
  18536. }
  18537. } else if (tmpl == "vicuna" || tmpl == "vicuna-orca" || (tmpl_contains("USER: ") && tmpl_contains("ASSISTANT: "))) {
  18538. // eachadea/vicuna-13b-1.1 (and Orca variant)
  18539. for (auto message : chat) {
  18540. std::string role(message->role);
  18541. if (role == "system") {
  18542. // Orca-Vicuna variant uses a system prefix
  18543. if (tmpl == "vicuna-orca" || tmpl_contains("SYSTEM: ")) {
  18544. ss << "SYSTEM: " << message->content << "\n";
  18545. } else {
  18546. ss << message->content << "\n\n";
  18547. }
  18548. } else if (role == "user") {
  18549. ss << "USER: " << message->content << "\n";
  18550. } else if (role == "assistant") {
  18551. ss << "ASSISTANT: " << message->content << "</s>\n";
  18552. }
  18553. }
  18554. if (add_ass) {
  18555. ss << "ASSISTANT:";
  18556. }
  18557. } else if (tmpl == "deepseek" || (tmpl_contains("### Instruction:") && tmpl_contains("<|EOT|>"))) {
  18558. // deepseek-ai/deepseek-coder-33b-instruct
  18559. for (auto message : chat) {
  18560. std::string role(message->role);
  18561. if (role == "system") {
  18562. ss << message->content;
  18563. } else if (role == "user") {
  18564. ss << "### Instruction:\n" << message->content << "\n";
  18565. } else if (role == "assistant") {
  18566. ss << "### Response:\n" << message->content << "\n<|EOT|>\n";
  18567. }
  18568. }
  18569. if (add_ass) {
  18570. ss << "### Response:\n";
  18571. }
  18572. } else if (tmpl == "command-r" || (tmpl_contains("<|START_OF_TURN_TOKEN|>") && tmpl_contains("<|USER_TOKEN|>"))) {
  18573. // CohereForAI/c4ai-command-r-plus
  18574. for (auto message : chat) {
  18575. std::string role(message->role);
  18576. if (role == "system") {
  18577. ss << "<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  18578. } else if (role == "user") {
  18579. ss << "<|START_OF_TURN_TOKEN|><|USER_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  18580. } else if (role == "assistant") {
  18581. ss << "<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  18582. }
  18583. }
  18584. if (add_ass) {
  18585. ss << "<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>";
  18586. }
  18587. } else if (tmpl == "llama3" || (tmpl_contains("<|start_header_id|>") && tmpl_contains("<|end_header_id|>"))) {
  18588. // Llama 3
  18589. for (auto message : chat) {
  18590. std::string role(message->role);
  18591. ss << "<|start_header_id|>" << role << "<|end_header_id|>\n\n" << trim(message->content) << "<|eot_id|>";
  18592. }
  18593. if (add_ass) {
  18594. ss << "<|start_header_id|>assistant<|end_header_id|>\n\n";
  18595. }
  18596. } else if (tmpl == "chatglm3" || tmpl_contains("[gMASK]sop")) {
  18597. // chatglm3-6b
  18598. ss << "[gMASK]" << "sop";
  18599. for (auto message : chat) {
  18600. std::string role(message->role);
  18601. ss << "<|" << role << "|>" << "\n " << message->content;
  18602. }
  18603. if (add_ass) {
  18604. ss << "<|assistant|>";
  18605. }
  18606. } else if (tmpl == "chatglm4" || tmpl_contains("[gMASK]<sop>")) {
  18607. ss << "[gMASK]" << "<sop>";
  18608. for (auto message : chat) {
  18609. std::string role(message->role);
  18610. ss << "<|" << role << "|>" << "\n" << message->content;
  18611. }
  18612. if (add_ass) {
  18613. ss << "<|assistant|>";
  18614. }
  18615. } else if (tmpl == "minicpm" || tmpl_contains(LU8("<用户>"))) {
  18616. // MiniCPM-3B-OpenHermes-2.5-v2-GGUF
  18617. for (auto message : chat) {
  18618. std::string role(message->role);
  18619. if (role == "user") {
  18620. ss << LU8("<用户>");
  18621. ss << trim(message->content);
  18622. ss << "<AI>";
  18623. } else {
  18624. ss << trim(message->content);
  18625. }
  18626. }
  18627. } else if (tmpl == "deepseek2" || tmpl_contains("'Assistant: ' + message['content'] + eos_token")) {
  18628. // DeepSeek-V2
  18629. for (auto message : chat) {
  18630. std::string role(message->role);
  18631. if (role == "system") {
  18632. ss << message->content << "\n\n";
  18633. } else if (role == "user") {
  18634. ss << "User: " << message->content << "\n\n";
  18635. } else if (role == "assistant") {
  18636. ss << "Assistant: " << message->content << LU8("<|end▁of▁sentence|>");
  18637. }
  18638. }
  18639. if (add_ass) {
  18640. ss << "Assistant:";
  18641. }
  18642. } else if (tmpl == "exaone3" || (tmpl_contains("[|system|]") && tmpl_contains("[|assistant|]") && tmpl_contains("[|endofturn|]"))) {
  18643. // ref: https://huggingface.co/LGAI-EXAONE/EXAONE-3.0-7.8B-Instruct/discussions/8#66bae61b1893d14ee8ed85bb
  18644. // EXAONE-3.0-7.8B-Instruct
  18645. for (auto message : chat) {
  18646. std::string role(message->role);
  18647. if (role == "system") {
  18648. ss << "[|system|]" << trim(message->content) << "[|endofturn|]\n";
  18649. } else if (role == "user") {
  18650. ss << "[|user|]" << trim(message->content) << "\n";
  18651. } else if (role == "assistant") {
  18652. ss << "[|assistant|]" << trim(message->content) << "[|endofturn|]\n";
  18653. }
  18654. }
  18655. if (add_ass) {
  18656. ss << "[|assistant|]";
  18657. }
  18658. } else {
  18659. // template not supported
  18660. return -1;
  18661. }
  18662. dest = ss.str();
  18663. return dest.size();
  18664. }
  18665. int32_t llama_chat_apply_template(
  18666. const struct llama_model * model,
  18667. const char * tmpl,
  18668. const struct llama_chat_message * chat,
  18669. size_t n_msg,
  18670. bool add_ass,
  18671. char * buf,
  18672. int32_t length) {
  18673. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  18674. if (tmpl == nullptr) {
  18675. GGML_ASSERT(model != nullptr);
  18676. // load template from model
  18677. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  18678. std::string template_key = "tokenizer.chat_template";
  18679. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  18680. if (res < 0) {
  18681. // worst case: there is no information about template, we will use chatml by default
  18682. curr_tmpl = "chatml"; // see llama_chat_apply_template_internal
  18683. } else {
  18684. curr_tmpl = std::string(model_template.data(), model_template.size());
  18685. }
  18686. }
  18687. // format the chat to string
  18688. std::vector<const llama_chat_message *> chat_vec;
  18689. chat_vec.resize(n_msg);
  18690. for (size_t i = 0; i < n_msg; i++) {
  18691. chat_vec[i] = &chat[i];
  18692. }
  18693. std::string formatted_chat;
  18694. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  18695. if (res < 0) {
  18696. return res;
  18697. }
  18698. if (buf && length > 0) {
  18699. strncpy(buf, formatted_chat.c_str(), length);
  18700. }
  18701. return res;
  18702. }
  18703. //
  18704. // sampling
  18705. //
  18706. // TODO: remove indirection when vocab becomes accesible in llama-sampling.cpp
  18707. struct llama_sampler * llama_sampler_init_grammar(const struct llama_model * model, const char * grammar_str, const char * grammar_root) {
  18708. return llama_sampler_init_grammar_impl(model->vocab, grammar_str, grammar_root);
  18709. }
  18710. //
  18711. // model split
  18712. //
  18713. int llama_split_path(char * split_path, size_t maxlen, const char * path_prefix, int split_no, int split_count) {
  18714. static const char * const SPLIT_PATH_FORMAT = "%s-%05d-of-%05d.gguf";
  18715. if (snprintf(split_path, maxlen, SPLIT_PATH_FORMAT, path_prefix, split_no + 1, split_count)) {
  18716. return strlen(split_path);
  18717. }
  18718. return 0;
  18719. }
  18720. int llama_split_prefix(char * dest, size_t maxlen, const char * split_path, int split_no, int split_count) {
  18721. std::string str_split_path(split_path);
  18722. char postfix[32];
  18723. snprintf(postfix, 32, "-%05d-of-%05d.gguf", split_no + 1, split_count);
  18724. std::string str_postfix(postfix);
  18725. // check if dest ends with postfix
  18726. int size_prefix = str_split_path.size() - str_postfix.size();
  18727. if (size_prefix > 0 && str_split_path.find(str_postfix, size_prefix) != std::string::npos) {
  18728. snprintf(dest, std::min((size_t) size_prefix + 1, maxlen), "%s", split_path);
  18729. return size_prefix;
  18730. }
  18731. return 0;
  18732. }
  18733. const char * llama_print_system_info(void) {
  18734. static std::string s;
  18735. s = "";
  18736. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  18737. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  18738. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  18739. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  18740. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  18741. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  18742. s += "AVX512_BF16 = " + std::to_string(ggml_cpu_has_avx512_bf16()) + " | ";
  18743. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  18744. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  18745. s += "SVE = " + std::to_string(ggml_cpu_has_sve()) + " | ";
  18746. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  18747. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  18748. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  18749. s += "RISCV_VECT = " + std::to_string(ggml_cpu_has_riscv_v()) + " | ";
  18750. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  18751. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  18752. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  18753. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  18754. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  18755. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  18756. s += "LLAMAFILE = " + std::to_string(ggml_cpu_has_llamafile()) + " | ";
  18757. return s.c_str();
  18758. }
  18759. struct llama_perf_context_data llama_perf_context(const struct llama_context * ctx) {
  18760. struct llama_perf_context_data data = {};
  18761. if (ctx == nullptr) {
  18762. return data;
  18763. }
  18764. data.t_start_ms = 1e-3 * ctx->t_start_us;
  18765. data.t_load_ms = 1e-3 * ctx->t_load_us;
  18766. data.t_p_eval_ms = 1e-3 * ctx->t_p_eval_us;
  18767. data.t_eval_ms = 1e-3 * ctx->t_eval_us;
  18768. data.n_p_eval = std::max(1, ctx->n_p_eval);
  18769. data.n_eval = std::max(1, ctx->n_eval);
  18770. return data;
  18771. }
  18772. void llama_perf_context_print(const struct llama_context * ctx) {
  18773. const auto data = llama_perf_context(ctx);
  18774. const double t_end_ms = 1e-3 * ggml_time_us();
  18775. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, data.t_load_ms);
  18776. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  18777. __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);
  18778. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  18779. __func__, data.t_eval_ms, data.n_eval, data.t_eval_ms / data.n_eval, 1e3 / data.t_eval_ms * data.n_eval);
  18780. 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));
  18781. }
  18782. void llama_perf_context_reset(struct llama_context * ctx) {
  18783. ctx->t_start_us = ggml_time_us();
  18784. ctx->t_eval_us = ctx->n_eval = 0;
  18785. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  18786. }
  18787. void llama_perf_dump_yaml(FILE * stream, const llama_context * ctx) {
  18788. fprintf(stream, "\n");
  18789. fprintf(stream, "###########\n");
  18790. fprintf(stream, "# Timings #\n");
  18791. fprintf(stream, "###########\n");
  18792. fprintf(stream, "\n");
  18793. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  18794. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  18795. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  18796. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  18797. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  18798. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  18799. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  18800. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  18801. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  18802. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  18803. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  18804. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  18805. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  18806. }
  18807. // For internal test use
  18808. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  18809. struct llama_context * ctx
  18810. ) {
  18811. return ctx->model.tensors_by_name;
  18812. }
  18813. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  18814. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  18815. g_state.log_callback_user_data = user_data;
  18816. #ifdef GGML_USE_METAL
  18817. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  18818. #elif defined(GGML_USE_CUDA)
  18819. ggml_backend_cuda_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  18820. #elif defined(GGML_USE_CANN)
  18821. ggml_backend_cann_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  18822. #endif
  18823. }
  18824. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  18825. va_list args_copy;
  18826. va_copy(args_copy, args);
  18827. char buffer[128];
  18828. int len = vsnprintf(buffer, 128, format, args);
  18829. if (len < 128) {
  18830. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  18831. } else {
  18832. char * buffer2 = new char[len + 1];
  18833. vsnprintf(buffer2, len + 1, format, args_copy);
  18834. buffer2[len] = 0;
  18835. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  18836. delete[] buffer2;
  18837. }
  18838. va_end(args_copy);
  18839. }
  18840. void llama_log_internal(ggml_log_level level, const char * format, ...) {
  18841. va_list args;
  18842. va_start(args, format);
  18843. llama_log_internal_v(level, format, args);
  18844. va_end(args);
  18845. }
  18846. void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  18847. (void) level;
  18848. (void) user_data;
  18849. fputs(text, stderr);
  18850. fflush(stderr);
  18851. }